diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..9c83142145c4befa8d9aab39a10039e3cd251672
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,92 @@
+# =============================================================================
+# GitPilot - Hugging Face Spaces Dockerfile
+# =============================================================================
+# Follows the official HF Docker Spaces pattern:
+# https://huggingface.co/docs/hub/spaces-sdks-docker
+#
+# Architecture:
+# React UI (Vite build) -> FastAPI backend -> OllaBridge Cloud / any LLM
+# =============================================================================
+
+# -- Stage 1: Build React frontend -------------------------------------------
+FROM node:20-slim AS frontend-builder
+
+WORKDIR /build
+
+COPY frontend/package.json frontend/package-lock.json ./
+RUN npm ci --production=false
+
+COPY frontend/ ./
+RUN npm run build
+
+# -- Stage 2: Python runtime -------------------------------------------------
+FROM python:3.12-slim
+
+# System deps needed at runtime
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ git curl ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
+
+# HF Spaces runs containers as UID 1000 — create user early (official pattern)
+RUN useradd -m -u 1000 user
+
+USER user
+
+ENV HOME=/home/user \
+ PATH=/home/user/.local/bin:$PATH \
+ PYTHONUNBUFFERED=1 \
+ GITPILOT_PROVIDER=ollabridge \
+ OLLABRIDGE_BASE_URL=https://ruslanmv-ollabridge.hf.space \
+ GITPILOT_OLLABRIDGE_MODEL=qwen2.5:1.5b \
+ CORS_ORIGINS="*" \
+ GITPILOT_CONFIG_DIR=/tmp/gitpilot
+
+WORKDIR $HOME/app
+
+# ── Install Python dependencies BEFORE copying source code ──────────
+# This ensures pip install layers are cached even when code changes.
+COPY --chown=user pyproject.toml README.md ./
+
+# Step 1: lightweight deps (cached layer)
+RUN pip install --no-cache-dir --upgrade pip && \
+ pip install --no-cache-dir \
+ "fastapi>=0.111.0" \
+ "uvicorn[standard]>=0.30.0" \
+ "httpx>=0.27.0" \
+ "python-dotenv>=1.1.0,<1.2.0" \
+ "typer>=0.12.0,<0.24.0" \
+ "pydantic>=2.7.0,<2.12.0" \
+ "rich>=13.0.0" \
+ "pyjwt[crypto]>=2.8.0"
+
+# Step 2: heavy ML/agent deps (separate layer for better caching)
+RUN pip install --no-cache-dir \
+ "litellm" \
+ "crewai[anthropic]>=0.76.9" \
+ "crewai-tools>=0.13.4" \
+ "anthropic>=0.39.0" \
+ "ibm-watsonx-ai>=1.1.0" \
+ "langchain-ibm>=0.3.0"
+
+# ── Now copy source code (cache-busting only affects layers below) ──
+COPY --chown=user gitpilot ./gitpilot
+
+# Copy built frontend into gitpilot/web/
+COPY --chown=user --from=frontend-builder /build/dist/ ./gitpilot/web/
+
+# Step 3: editable install of gitpilot itself (deps already satisfied)
+RUN pip install --no-cache-dir --no-deps -e .
+
+EXPOSE 7860
+
+# NOTE: Do NOT add a Docker HEALTHCHECK here.
+# HF Spaces has its own HTTP probe on app_port (7860) and ignores the
+# Docker HEALTHCHECK directive.
+
+# Direct CMD — no shell script, fewer failure points.
+CMD ["python", "-m", "uvicorn", "gitpilot.api:app", \
+ "--host", "0.0.0.0", \
+ "--port", "7860", \
+ "--workers", "2", \
+ "--limit-concurrency", "10", \
+ "--timeout-keep-alive", "120"]
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..5de6067d4f4f2254ae1c5014e1c868aac1865212
--- /dev/null
+++ b/README.md
@@ -0,0 +1,80 @@
+---
+title: GitPilot
+emoji: "\U0001F916"
+colorFrom: blue
+colorTo: indigo
+sdk: docker
+app_port: 7860
+startup_duration_timeout: 5m
+pinned: true
+license: mit
+short_description: Enterprise AI Coding Assistant for GitHub Repositories
+---
+
+# GitPilot — Hugging Face Spaces
+
+**Enterprise-grade AI coding assistant** for GitHub repositories with multi-LLM support, visual workflow insights, and intelligent code analysis.
+
+## What This Does
+
+This Space runs the full GitPilot stack:
+1. **React Frontend** — Professional dark-theme UI with chat, file browser, and workflow visualization
+2. **FastAPI Backend** — 80+ API endpoints for repository management, AI chat, planning, and execution
+3. **Multi-Agent AI** — CrewAI orchestration with 7 switchable agent topologies
+
+## LLM Providers
+
+GitPilot connects to your favorite LLM provider. Configure in **Admin / LLM Settings**:
+
+| Provider | Default | API Key Required |
+|---|---|---|
+| **OllaBridge Cloud** (default) | `qwen2.5:1.5b` | No |
+| OpenAI | `gpt-4o-mini` | Yes |
+| Anthropic Claude | `claude-sonnet-4-5` | Yes |
+| Ollama (local) | `llama3` | No |
+| Custom endpoint | Any model | Optional |
+
+## Quick Start
+
+1. Open the Space UI
+2. Enter your **GitHub Token** (Settings -> GitHub)
+3. Select a repository from the sidebar
+4. Start chatting with your AI coding assistant
+
+## API Endpoints
+
+| Endpoint | Description |
+|---|---|
+| `GET /api/health` | Health check |
+| `POST /api/chat/message` | Chat with AI assistant |
+| `POST /api/chat/plan` | Generate implementation plan |
+| `GET /api/repos` | List repositories |
+| `GET /api/settings` | View/update settings |
+| `GET /docs` | Interactive API docs (Swagger) |
+
+## Connect to OllaBridge Cloud
+
+By default, GitPilot connects to [OllaBridge Cloud](https://huggingface.co/spaces/ruslanmv/ollabridge) for LLM inference. This provides free access to open-source models without needing API keys.
+
+To use your own OllaBridge instance:
+1. Go to **Admin / LLM Settings**
+2. Select **OllaBridge** provider
+3. Enter your OllaBridge URL and model
+
+## Environment Variables
+
+Configure via HF Spaces secrets:
+
+| Variable | Description | Default |
+|---|---|---|
+| `GITPILOT_PROVIDER` | LLM provider | `ollabridge` |
+| `OLLABRIDGE_BASE_URL` | OllaBridge Cloud URL | `https://ruslanmv-ollabridge.hf.space` |
+| `GITHUB_TOKEN` | GitHub personal access token | - |
+| `OPENAI_API_KEY` | OpenAI API key (if using OpenAI) | - |
+| `ANTHROPIC_API_KEY` | Anthropic API key (if using Claude) | - |
+
+## Links
+
+- [GitPilot Repository](https://github.com/ruslanmv/gitpilot)
+- [OllaBridge Cloud](https://huggingface.co/spaces/ruslanmv/ollabridge)
+- [Documentation](https://github.com/ruslanmv/gitpilot#readme)
diff --git a/REPO_README.md b/REPO_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..62c078c50fc2200679db161fb2bb4432c973d2e2
--- /dev/null
+++ b/REPO_README.md
@@ -0,0 +1,418 @@
+
+
+
+
+# GitPilot
+
+### The first open-source multi-agent AI coding assistant.
+
+Multiple specialized agents — including Explorer, Planner, Coder, and Reviewer — collaborate seamlessly on every task. By default, GitPilot requests confirmation before executing high-impact actions. Switch to Auto or Plan mode at any time.
+
+[](https://pypi.org/project/gitcopilot/)
+[](https://www.python.org/)
+[](LICENSE)
+[](https://marketplace.visualstudio.com/)
+[](#contributing)
+
+[**Get Started**](#get-started) · [VS Code](#vs-code-extension) · [Web App](#web-app) · [How It Works](#how-it-works) · [Providers](#supported-ai-providers)
+
+
+
+---
+
+
+
+
+
+
+
+
+## Why GitPilot?
+
+Most AI coding tools are a **single model behind a chat box**. GitPilot is fundamentally different: it deploys a **team of four specialized AI agents** that collaborate on every task — just like a real engineering team.
+
+| Agent | Role | What it does |
+|---|---|---|
+| **Explorer** | Context | Reads your full repo, git log, test suite, and dependencies so the plan starts with real knowledge — not guesses |
+| **Planner** | Strategy | Drafts a safe, step-by-step plan with diffs and surfaces risks before any file is touched |
+| **Coder** | Execution | Writes code, runs your tests, and self-corrects on failure — iterating until the suite passes |
+| **Reviewer** | Quality | Validates the output, re-runs the suite, and drafts a commit message and PR summary |
+
+**You control how the agent runs.** Three execution modes — selectable per session from the VS Code compose bar or backend API:
+
+| Mode | Default? | Behavior |
+|---|---|---|
+| **Ask** | Yes | Prompts you before each dangerous action (write, edit, run, commit). You see the diff and click Allow / Deny. |
+| **Auto** | | Executes all tools automatically. Fastest for experienced users who trust the plan. |
+| **Plan** | | Read-only. Generates and displays the plan but blocks all file writes and commands. |
+
+Diffs are shown before they're applied. Tests run before anything is committed. No surprises.
+
+### What else sets GitPilot apart
+
+- 🧭 **Works where you work** — VS Code, web app, and CLI share one login, one history, and one set of approvals.
+- 🧠 **Any LLM, zero lock-in** — OpenAI, Anthropic Claude, IBM Watsonx, Ollama (local & free) or OllaBridge. Switch in settings, no code change.
+- 🔐 **Private by default** — run the entire stack locally with Ollama. No telemetry, no data leaves your machine.
+- 🏢 **Enterprise-ready, Apache 2.0 open source** — 854 passing tests, Docker & Hugging Face deployment recipes, audit the code yourself.
+- 🌍 **Runs anywhere** — laptop, private cloud, air-gapped environments, or managed hosting. Your repo, your rules.
+
+---
+
+## What is GitPilot?
+
+GitPilot is an AI assistant that helps you ship better code, faster — without giving up control. It understands your project, plans changes you can read before they happen, writes the code, runs your tests, and drafts the commit message and pull request for you.
+
+**Works with any language. Runs on any LLM.** Start free and local with Ollama, or bring your own OpenAI, Claude, or Watsonx key.
+
+```
+You: "Add input validation to the login form"
+
+GitPilot:
+ 1. Reading src/auth/login.ts...
+ 2. Planning 3 changes...
+ 3. Editing login.ts → [Apply Patch] [Revert]
+ 4. Running npm test... 3 passed
+ 5. Done — files written to your workspace.
+```
+
+---
+
+## Get Started
+
+### Option 1: VS Code Extension (recommended)
+
+Install the extension, configure your LLM, and start chatting:
+
+```
+1. Open VS Code
+2. Install "GitPilot Workspace" from Extensions
+3. Click the GitPilot icon in the sidebar
+4. Choose your AI provider (OpenAI, Claude, Ollama...)
+5. Start asking questions about your code
+```
+
+### Option 2: Web App
+
+Run the full web interface with Docker:
+
+```bash
+git clone https://github.com/ruslanmv/gitpilot.git
+cd gitpilot
+docker compose up
+```
+
+Open [http://localhost:3000](http://localhost:3000) in your browser.
+
+### Live Demo on Hugging Face
+
+Experience the application in action through our hosted demo environment:
+
+[](https://huggingface.co/spaces/ruslanmv/gitpilot)
+
+🔗 **Access the live demo:**
+[https://huggingface.co/spaces/ruslanmv/gitpilot](https://huggingface.co/spaces/ruslanmv/gitpilot)
+
+### Option 3: Python CLI (fastest)
+
+```bash
+pip install gitcopilot
+gitpilot serve
+```
+
+Open [http://localhost:8000](http://localhost:8000) and you're done.
+
+> **Heads up:** the PyPI package is published as **`gitcopilot`** (the name `gitpilot` was already taken) but the command you run is `gitpilot`. Python **3.11** or **3.12** required.
+
+---
+
+## VS Code Extension
+
+The sidebar panel gives you everything in one place:
+
+| Feature | What it does |
+|---|---|
+| **Chat** | Ask questions, request changes, review code |
+| **Execution Modes** | Bottom bar: `Auto` / `Ask` / `Plan` — controls agent permissions per session |
+| **Plan View** | See the step-by-step plan before changes are made |
+| **Plan Approval** | "Approve & Execute" / "Dismiss" bar — execution waits for your OK |
+| **Tool Approvals** | Per-action Allow / Allow for session / Deny cards (Ask mode) |
+| **Diff Preview** | Review proposed edits in VS Code's native diff viewer |
+| **Apply / Revert** | One click to apply changes, one click to undo |
+| **Quick Actions** | Explain, Review, Fix, Generate Tests, Security Scan |
+| **Smart Commit** | AI-generated commit messages |
+| **Code Lens** | Inline "Explain / Review" hints on functions |
+| **Settings Tab** | Branded settings page (General, Provider, Agent, Editor) |
+| **New Chat** | One click to clear chat and start a fresh session |
+
+### Execution modes
+
+The compose bar includes a mode selector that controls how the multi-agent pipeline runs:
+
+```
+[ Auto | Ask | Plan ] [ Send ] [ New Chat ]
+```
+
+| Mode | VS Code setting | Backend value | What happens |
+|---|---|---|---|
+| **Ask** (default) | `gitpilot.permissionMode: "normal"` | `"normal"` | Each dangerous tool (write, edit, run, commit) shows an approval card |
+| **Auto** | `gitpilot.permissionMode: "auto"` | `"auto"` | Tools execute automatically — no approval prompts |
+| **Plan** | `gitpilot.permissionMode: "plan"` | `"plan"` | Plan is generated and displayed, all writes/commands blocked |
+
+Mode changes are persisted to VS Code settings and synced to the backend via `PUT /api/permissions/mode`.
+
+### How approvals work
+
+```
+You send a request
+ → Explorer reads repo context
+ → Planner drafts step-by-step plan
+ → Plan appears in sidebar (Approve & Execute / Dismiss)
+ → You click Approve
+ → Coder begins execution
+ → Dangerous tool requested (e.g. write_file)
+ → Ask mode: approval card shown (Allow / Allow for session / Deny)
+ → Auto mode: executes immediately
+ → Plan mode: blocked
+ → Tests run, Reviewer validates
+ → Done — Apply Patch or Revert
+```
+
+> **Note:** Simple questions (e.g. "explain this code") may return a direct answer without generating a multi-step plan. This is expected — the planner activates for tasks that require file changes or multi-step execution.
+
+### Code generation and Apply Patch
+
+When you ask GitPilot to create or edit files, the response includes structured `edits` — not just text. The **Apply Patch** button writes them directly to your workspace.
+
+```
+You: "Create a Flask app with app.py, requirements.txt, and README.md"
+
+GitPilot:
+ → LLM generates 3 files with content
+ → Backend extracts structured edits (path + content)
+ → VS Code shows [Apply Patch] [Revert]
+ → You click Apply Patch
+ → 3 files written to disk
+ → Project context refreshes automatically
+ → First file opens in the editor
+```
+
+How it works under the hood:
+- The LLM is instructed to output code blocks with the filename on the fence line (` ```python hello.py`)
+- The backend parses these blocks into `ProposedEdit` objects with file path, kind, and content
+- All paths are sanitized (rejects `../` traversal, absolute paths, drive letters)
+- The extension stores edits in `activeTask.edits` and shows Apply / Revert
+- `PatchApplier` writes files via `vscode.workspace.fs.writeFile`
+- After apply, project context refreshes and the first file opens
+
+> **Note:** For folder-only sessions (no GitHub remote), code generation uses the LLM directly with structured output instructions. For GitHub-connected sessions, the full CrewAI multi-agent pipeline (Explorer → Planner → Coder → Reviewer) handles planning and execution.
+
+### Supported AI Providers
+
+| Provider | Setup | Free? |
+|---|---|---|
+| **Ollama** | Install Ollama, run `ollama pull llama3` | Yes |
+| **OllaBridge** | Works out of the box (cloud Ollama) | Yes |
+| **OpenAI** | Add your API key in settings | Paid |
+| **Claude** | Add your Anthropic API key | Paid |
+| **Watsonx** | Add IBM credentials | Paid |
+
+---
+
+## Web App
+
+The web interface includes:
+
+- Chat with real-time responses
+- GitHub integration (connect your repos)
+- File tree browser
+- Diff viewer with line-by-line changes
+- Pull request creation
+- Session history with checkpoints
+- Multi-repo support
+
+
+
+### Example: File Deletion
+
+
+### Example: Content Generation
+
+
+### Example: File Creation
+
+
+### Example multiple operations
+
+
+### Example of multiagent topologies
+
+
+---
+
+## How It Works
+
+
+
+
+
+
+
+
+GitPilot uses a multi-agent system powered by CrewAI:
+
+1. **Explorer** reads your repo structure, git log, and key files
+2. **Planner** creates a safe step-by-step plan with diffs
+3. **Executor** writes code and runs tests, self-correcting on failure
+4. **Reviewer** validates the output and summarises what changed
+
+In **Ask** mode (default), you approve every change before it's applied. In **Auto** mode, tools execute without prompts. In **Plan** mode, only the plan is generated — no files are touched.
+
+---
+
+## Project Structure
+
+```
+gitpilot/
+ gitpilot/ Python backend (FastAPI)
+ frontend/ React web app
+ extensions/vscode/ VS Code extension
+ docs/ Documentation and assets
+ tests/ Test suite
+```
+
+---
+
+## Configuration
+
+GitPilot works with environment variables or the settings UI.
+
+**Minimal setup** (Ollama, free, local):
+
+```bash
+# .env
+GITPILOT_PROVIDER=ollama
+OLLAMA_BASE_URL=http://localhost:11434
+GITPILOT_OLLAMA_MODEL=llama3
+```
+
+**Cloud setup** (OpenAI):
+
+```bash
+# .env
+GITPILOT_PROVIDER=openai
+OPENAI_API_KEY=sk-...
+GITPILOT_OPENAI_MODEL=gpt-4o-mini
+```
+
+**Cloud setup** (Claude):
+
+```bash
+# .env
+GITPILOT_PROVIDER=claude
+ANTHROPIC_API_KEY=sk-ant-...
+GITPILOT_CLAUDE_MODEL=claude-sonnet-4-5
+```
+
+All settings can also be changed from the VS Code extension or web UI without editing files.
+
+---
+
+## API
+
+GitPilot exposes a REST + WebSocket API:
+
+| Endpoint | What it does |
+|---|---|
+| `GET /api/status` | Server health check |
+| `POST /api/chat/send` | Send a message, get a response |
+| `POST /api/v2/chat/stream` | Stream agent events (SSE) — accepts `permission_mode` |
+| `WS /ws/v2/sessions/{id}` | Real-time WebSocket streaming |
+| `POST /api/chat/plan` | Generate an execution plan |
+| `POST /api/chat/execute` | Execute a plan |
+| `GET /api/repos` | List connected repositories |
+| `GET /api/sessions` | List chat sessions |
+| `GET /api/permissions` | Current permission policy |
+| `PUT /api/permissions/mode` | Set execution mode: `normal` / `auto` / `plan` |
+| `POST /api/v2/approval/respond` | Approve or deny a tool execution request |
+
+Full API docs at `http://localhost:8000/docs` (Swagger UI).
+
+---
+
+## Deployment
+
+### Hugging Face Spaces
+
+GitPilot runs on Hugging Face Spaces with OllaBridge (free):
+
+```
+Runtime: Docker
+Port: 7860
+Provider: OllaBridge (cloud Ollama)
+```
+
+### Docker Compose
+
+```bash
+docker compose up -d
+# Backend: http://localhost:8000
+# Frontend: http://localhost:3000
+```
+
+### Vercel
+
+The frontend deploys to Vercel. Set `VITE_BACKEND_URL` to your backend.
+
+---
+
+## Contributing
+
+```bash
+# Standard install: runtime backend + frontend + MCP stack
+make install
+# WSL note: the Makefile defaults uv to UV_LINK_MODE=copy to avoid
+# hardlink fallback warnings on /mnt/c checkouts. For best install speed,
+# clone the repo inside the native WSL filesystem (for example ~/workspace).
+
+# Developer/test tooling
+make install-dev
+make test
+
+# Frontend only
+cd frontend
+npm ci
+npm run dev
+
+# VS Code Extension
+cd extensions/vscode
+npm install
+make compile
+# Press F5 in VS Code to launch debug host
+```
+
+---
+
+## License
+
+Apache License 2.0. See [LICENSE](LICENSE).
+
+---
+
+
+
+**GitPilot** is made by [Ruslan Magana Vsevolodovna](https://github.com/ruslanmv)
+
+[Star on GitHub](https://github.com/ruslanmv/gitpilot) • [Report a Bug](https://github.com/ruslanmv/gitpilot/issues) • [Request a Feature](https://github.com/ruslanmv/gitpilot/issues)
+
+
+
+---
+**MCP Context Forge integration** — GitPilot ships a default MCP stack (Forge + PostgreSQL / Milvus / Inspector servers) wired into the agents like Claude Code's built-ins; `make run` brings everything up. No Docker? Use `make run-bare` to start GitPilot core without MCP. See [docs/deploy/install-mcp.md](./docs/deploy/install-mcp.md) and [docs/deploy/production-mcp.md](./docs/deploy/production-mcp.md).
+
+---
+
+## What's New
+
+> **Enterprise-ready foundation:** GitPilot now ships with safer defaults and production-grade controls, including thread-safe feature flags, strict typing, CI coverage enforcement, structured error handling, and a fast `gitpilot doctor` health check. All upgrades are additive, flag-gated, and disabled by default, so existing installations remain stable while teams can adopt new capabilities gradually.
+
+> **Performance, onboarding, and release confidence:** GitPilot now improves runtime efficiency with prompt caching, lazy tool loading, context memoisation, SSE streaming, and safe model warmup. First-time setup is easier with `gitpilot init --wizard`, which creates configuration files atomically with rollback protection and no secret exposure. The platform also adds a stable public API, deprecation handling, MkDocs documentation, broken-link checks, SBOM generation, npm auditing, and Sigstore-based release signing.
diff --git a/frontend/.dockerignore b/frontend/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..9da1acab57b3a83f0649dc5deb28b33600fe4ad3
--- /dev/null
+++ b/frontend/.dockerignore
@@ -0,0 +1,39 @@
+# Node
+node_modules/
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+.pnpm-debug.log*
+
+# Build
+dist/
+build/
+
+# Environment
+.env
+.env.local
+.env.development
+.env.test
+.env.production.local
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+*~
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Git
+.git
+.gitignore
+
+# Testing
+coverage/
+.nyc_output/
+
+# Misc
+*.log
diff --git a/frontend/App.jsx b/frontend/App.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..3b599eb6d536a7f44e7670545240584f019c0d21
--- /dev/null
+++ b/frontend/App.jsx
@@ -0,0 +1,1295 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import StartupScreen from "./components/StartupScreen.jsx";
+import LoginPage from "./components/LoginPage.jsx";
+import RepoSelector from "./components/RepoSelector.jsx";
+import ProjectContextPanel from "./components/ProjectContextPanel.jsx";
+import ChatPanel from "./components/ChatPanel.jsx";
+import LlmSettings from "./components/LlmSettings.jsx";
+import FlowViewer from "./components/FlowViewer.jsx";
+import Footer from "./components/Footer.jsx";
+import ProjectSettingsModal from "./components/ProjectSettingsModal.jsx";
+import SessionSidebar from "./components/SessionSidebar.jsx";
+import ContextBar from "./components/ContextBar.jsx";
+import AddRepoModal from "./components/AddRepoModal.jsx";
+import UserMenu from "./components/UserMenu.jsx";
+import AboutModal from "./components/AboutModal.jsx";
+import {
+ WorkspaceModesTab,
+ SecurityTab,
+ IntegrationsTab,
+ MCPServersTab,
+ SkillsTab,
+ SessionsTab,
+ AdvancedTab,
+ SandboxTab,
+} from "./components/AdminTabs";
+import { apiUrl, safeFetchJSON, fetchStatus } from "./utils/api.js";
+import { initApp } from "./utils/appInit.js";
+
+function makeRepoKey(repo) {
+ if (!repo) return null;
+ return repo.full_name || `${repo.owner}/${repo.name}`;
+}
+
+function uniq(arr) {
+ return Array.from(new Set((arr || []).filter(Boolean)));
+}
+
+function getProviderLabel(status) {
+ if (!status) return "Checking...";
+ return (
+ status?.provider?.name ||
+ status?.provider_name ||
+ status?.provider?.provider ||
+ "Checking..."
+ );
+}
+
+function getBackendVersion(status) {
+ if (!status) return "Checking...";
+ return status?.version || status?.app_version || "Checking...";
+}
+
+export default function App() {
+ const frontendVersion = __APP_VERSION__ || "unknown";
+
+ // ---- Multi-repo context state ----
+ const [contextRepos, setContextRepos] = useState([]);
+ // Each entry: { repoKey: "owner/repo", repo: {...}, branch: "main" }
+ const [activeRepoKey, setActiveRepoKey] = useState(null);
+ const [addRepoOpen, setAddRepoOpen] = useState(false);
+
+ const [activePage, setActivePage] = useState("workspace");
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
+ const [userInfo, setUserInfo] = useState(null);
+
+ // Startup / enterprise loader state
+ const [startupPhase, setStartupPhase] = useState("booting");
+ const [startupStatusMessage, setStartupStatusMessage] = useState("Starting application...");
+ const [startupDetailMessage, setStartupDetailMessage] = useState(
+ "Initializing authentication, provider, and workspace context."
+ );
+ const [startupStatusSnapshot, setStartupStatusSnapshot] = useState(null);
+
+ // Repo + Session State Machine
+ const [repoStateByKey, setRepoStateByKey] = useState({});
+ const [toast, setToast] = useState(null);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ const [aboutOpen, setAboutOpen] = useState(false);
+ const [adminTab, setAdminTab] = useState("overview");
+ const [adminStatus, setAdminStatus] = useState(null);
+
+ // Fetch admin status when overview tab is active
+ useEffect(() => {
+ if (activePage === "admin" && adminTab === "overview") {
+ fetchStatus()
+ .then((data) => setAdminStatus(data))
+ .catch(() => setAdminStatus(null));
+ }
+ }, [activePage, adminTab]);
+
+ // Claude-Code-on-Web: Session sidebar + Environment state
+ const [activeSessionId, setActiveSessionId] = useState(null);
+ const [activeEnvId, setActiveEnvId] = useState("default");
+ const [sessionRefreshNonce, setSessionRefreshNonce] = useState(0);
+
+ // Sidebar collapse state (persisted in localStorage)
+ const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
+ try {
+ return localStorage.getItem("gitpilot_sidebar_collapsed") === "true";
+ } catch {
+ return false;
+ }
+ });
+
+ const toggleSidebar = useCallback(() => {
+ setSidebarCollapsed((prev) => {
+ const next = !prev;
+ try {
+ localStorage.setItem("gitpilot_sidebar_collapsed", String(next));
+ } catch {}
+ return next;
+ });
+ }, []);
+
+ // Keyboard shortcut: Cmd/Ctrl + B to toggle sidebar
+ useEffect(() => {
+ const handler = (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "b") {
+ e.preventDefault();
+ toggleSidebar();
+ }
+ };
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, [toggleSidebar]);
+
+ // ---- Derived `repo` — keeps all downstream consumers unchanged ----
+ const repo = useMemo(() => {
+ const entry = contextRepos.find((r) => r.repoKey === activeRepoKey);
+ return entry?.repo || null;
+ }, [contextRepos, activeRepoKey]);
+
+ const repoKey = activeRepoKey;
+
+ // Convenient selectors
+ const currentRepoState = repoKey ? repoStateByKey[repoKey] : null;
+
+ const defaultBranch = currentRepoState?.defaultBranch || repo?.default_branch || "main";
+ const currentBranch = currentRepoState?.currentBranch || defaultBranch;
+ const sessionBranches = currentRepoState?.sessionBranches || [];
+ const lastExecution = currentRepoState?.lastExecution || null;
+ const pulseNonce = currentRepoState?.pulseNonce || 0;
+ const chatByBranch = currentRepoState?.chatByBranch || {};
+
+ // ---------------------------------------------------------------------------
+ // Multi-repo context management
+ // ---------------------------------------------------------------------------
+ const addRepoToContext = useCallback((r) => {
+ const key = makeRepoKey(r);
+ if (!key) return;
+
+ setContextRepos((prev) => {
+ if (prev.some((e) => e.repoKey === key)) {
+ setActiveRepoKey(key);
+ return prev;
+ }
+ const entry = { repoKey: key, repo: r, branch: r.default_branch || "main" };
+ return [...prev, entry];
+ });
+
+ setActiveRepoKey(key);
+ setAddRepoOpen(false);
+ }, []);
+
+ const removeRepoFromContext = useCallback((key) => {
+ setContextRepos((prev) => {
+ const next = prev.filter((e) => e.repoKey !== key);
+ setActiveRepoKey((curActive) => {
+ if (curActive === key) {
+ return next.length > 0 ? next[0].repoKey : null;
+ }
+ return curActive;
+ });
+ return next;
+ });
+ }, []);
+
+ const clearAllContext = useCallback(() => {
+ setContextRepos([]);
+ setActiveRepoKey(null);
+ }, []);
+
+ const handleContextBranchChange = useCallback((targetRepoKey, newBranch) => {
+ setContextRepos((prev) =>
+ prev.map((e) =>
+ e.repoKey === targetRepoKey ? { ...e, branch: newBranch } : e
+ )
+ );
+
+ setRepoStateByKey((prev) => {
+ const cur = prev[targetRepoKey];
+ if (!cur) return prev;
+ return {
+ ...prev,
+ [targetRepoKey]: { ...cur, currentBranch: newBranch },
+ };
+ });
+ }, []);
+
+ // Init / reconcile repo state when active repo changes
+ useEffect(() => {
+ if (!repoKey || !repo) return;
+
+ setRepoStateByKey((prev) => {
+ const existing = prev[repoKey];
+ const d = repo.default_branch || "main";
+
+ if (!existing) {
+ return {
+ ...prev,
+ [repoKey]: {
+ defaultBranch: d,
+ currentBranch: d,
+ sessionBranches: [],
+ lastExecution: null,
+ pulseNonce: 0,
+ chatByBranch: {
+ [d]: { messages: [], plan: null },
+ },
+ },
+ };
+ }
+
+ const next = { ...existing };
+ next.defaultBranch = d;
+
+ if (!next.chatByBranch?.[d]) {
+ next.chatByBranch = {
+ ...(next.chatByBranch || {}),
+ [d]: { messages: [], plan: null },
+ };
+ }
+
+ if (!next.currentBranch) next.currentBranch = d;
+
+ return { ...prev, [repoKey]: next };
+ });
+ }, [repoKey, repo?.id, repo?.default_branch]);
+
+ const showToast = (title, message) => {
+ setToast({ title, message });
+ window.setTimeout(() => setToast(null), 5000);
+ };
+
+ // ---------------------------------------------------------------------------
+ // Session management — every chat is backed by a Session (Claude Code parity)
+ // ---------------------------------------------------------------------------
+
+ const _creatingSessionRef = useRef(false);
+
+ const [chatBySession, setChatBySession] = useState({});
+
+ const ensureSession = useCallback(
+ async (sessionName, seedMessages) => {
+ if (activeSessionId) return activeSessionId;
+ if (!repo) return null;
+ if (_creatingSessionRef.current) return null;
+ _creatingSessionRef.current = true;
+
+ try {
+ const token = localStorage.getItem("github_token");
+ const headers = {
+ "Content-Type": "application/json",
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
+ };
+
+ const res = await fetch("/api/sessions", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ repo_full_name: repoKey,
+ branch: currentBranch,
+ name: sessionName || undefined,
+ repos: contextRepos.map((e) => ({
+ full_name: e.repoKey,
+ branch: e.branch,
+ mode: e.repoKey === activeRepoKey ? "write" : "read",
+ })),
+ active_repo: activeRepoKey,
+ }),
+ });
+
+ if (!res.ok) return null;
+ const data = await res.json();
+ const newId = data.session_id;
+
+ if (seedMessages && seedMessages.length > 0) {
+ setChatBySession((prev) => ({
+ ...prev,
+ [newId]: { messages: seedMessages, plan: null },
+ }));
+ }
+
+ setActiveSessionId(newId);
+ setSessionRefreshNonce((n) => n + 1);
+ return newId;
+ } catch (err) {
+ console.warn("Failed to create session:", err);
+ return null;
+ } finally {
+ _creatingSessionRef.current = false;
+ }
+ },
+ [activeSessionId, repo, repoKey, currentBranch, contextRepos, activeRepoKey]
+ );
+
+ const handleNewSession = async () => {
+ setActiveSessionId(null);
+
+ try {
+ const token = localStorage.getItem("github_token");
+ const headers = {
+ "Content-Type": "application/json",
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
+ };
+
+ const res = await fetch("/api/sessions", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ repo_full_name: repoKey,
+ branch: currentBranch,
+ repos: contextRepos.map((e) => ({
+ full_name: e.repoKey,
+ branch: e.branch,
+ mode: e.repoKey === activeRepoKey ? "write" : "read",
+ })),
+ active_repo: activeRepoKey,
+ }),
+ });
+
+ if (!res.ok) return;
+ const data = await res.json();
+ setActiveSessionId(data.session_id);
+ setSessionRefreshNonce((n) => n + 1);
+ showToast("Session Created", "New session started.");
+ } catch (err) {
+ console.warn("Failed to create session:", err);
+ }
+ };
+
+ /**
+ * Convert a backend Message object to the frontend chat UI shape.
+ * Backend: { role: "user|assistant|system", content: "...", timestamp, metadata }
+ * Frontend: { from: "user|ai", role: "user|assistant|system", content, answer, ... }
+ */
+ const normalizeBackendMessage = (m) => {
+ const role = m.role || "assistant";
+ const content = m.content || "";
+ if (role === "user") {
+ return { from: "user", role: "user", content, text: content };
+ }
+ if (role === "system") {
+ return { from: "ai", role: "system", content };
+ }
+ // assistant
+ return {
+ from: "ai",
+ role: "assistant",
+ content,
+ answer: content,
+ // Preserve any structured metadata the backend stored (plan, diff, etc.)
+ ...(m.metadata && typeof m.metadata === "object" ? m.metadata : {}),
+ };
+ };
+
+ /**
+ * Fetch persisted messages for a session from the backend.
+ * Returns an array of normalized frontend messages (ready for ChatPanel),
+ * or an empty array on failure.
+ */
+ const fetchSessionMessages = useCallback(async (sessionId) => {
+ if (!sessionId) return [];
+ try {
+ const token = localStorage.getItem("github_token");
+ const headers = { "Content-Type": "application/json" };
+ if (token) headers["Authorization"] = `Bearer ${token}`;
+
+ const res = await fetch(apiUrl(`/api/sessions/${sessionId}/messages`), {
+ headers,
+ });
+ if (!res.ok) {
+ console.warn(`[fetchSessionMessages] ${res.status} for ${sessionId}`);
+ return [];
+ }
+ const data = await res.json();
+ const backendMessages = Array.isArray(data.messages) ? data.messages : [];
+ return backendMessages.map(normalizeBackendMessage);
+ } catch (err) {
+ console.warn(`[fetchSessionMessages] Failed to fetch ${sessionId}:`, err);
+ return [];
+ }
+ }, []);
+
+ /**
+ * Handle click on a session in the sidebar.
+ *
+ * Critical ordering: we must hydrate chatBySession BEFORE setting
+ * activeSessionId, because ChatPanel's session-sync useEffect reads
+ * sessionChatState only when sessionId changes (it does NOT depend on
+ * chatBySession to avoid prop/state loops). If we set activeSessionId
+ * first, ChatPanel would see an empty messages array, then our async
+ * hydration would complete but ChatPanel wouldn't re-sync.
+ */
+ // Resolve the branch we should jump to when reopening a session.
+ // Preference order:
+ // 1. session.repos[i].branch for the active_repo (multi-repo)
+ // 2. session.branch (legacy single-repo field)
+ // Returns ``null`` when nothing is recorded.
+ const resolveSessionBranch = (session) => {
+ if (!session) return null;
+ if (Array.isArray(session.repos) && session.repos.length > 0) {
+ const target =
+ session.repos.find(
+ (r) => session.active_repo && r?.full_name === session.active_repo,
+ ) || session.repos[0];
+ if (target?.branch) return target.branch;
+ }
+ return session.branch || null;
+ };
+
+ // Probe whether a branch still exists on GitHub. We deliberately
+ // reuse the existing tree endpoint instead of adding a new one — a
+ // 200 means the ref resolves, anything else (most importantly 404)
+ // means the branch is gone or otherwise unreachable. Failure
+ // degrades to "branch unknown" so a transient network blip falls
+ // back gracefully rather than misleading the user.
+ const probeBranchExists = async (repoFullName, branch) => {
+ if (!repoFullName || !branch) return false;
+ try {
+ const token = localStorage.getItem("github_token");
+ const headers = {};
+ if (token) headers["Authorization"] = `Bearer ${token}`;
+ const res = await fetch(
+ apiUrl(
+ `/api/repos/${repoFullName}/tree?ref=${encodeURIComponent(branch)}`,
+ ),
+ { headers },
+ );
+ return res.ok;
+ } catch {
+ return false;
+ }
+ };
+
+ const handleSelectSession = useCallback(async (session) => {
+ // 1. Fetch persisted messages first
+ const messages = await fetchSessionMessages(session.id);
+
+ // 2. Seed the chat cache (ChatPanel will read this via sessionChatState)
+ setChatBySession((prev) => ({
+ ...prev,
+ [session.id]: {
+ ...(prev[session.id] || { plan: null }),
+ messages,
+ },
+ }));
+
+ // 3. NOW activate the session — ChatPanel's sync effect will read
+ // the hydrated messages from chatBySession[session.id]
+ setActiveSessionId(session.id);
+
+ // 4. Jump to the branch this session last published to, but verify
+ // it still exists on GitHub first. When the branch was deleted
+ // (rebased away, merged-and-pruned, …) fall back to the
+ // repository's default branch and tell the user what happened —
+ // silently landing on the default would mask data loss.
+ const target = resolveSessionBranch(session);
+ if (target && target !== currentBranch) {
+ const repoFullName =
+ session.repo ||
+ (Array.isArray(session.repos) && session.repos[0]?.full_name);
+ const exists = await probeBranchExists(repoFullName, target);
+ if (exists) {
+ handleBranchChange(target);
+ } else {
+ const fallback = defaultBranch || "main";
+ showToast(
+ "Branch not found",
+ `'${target}' was not found on GitHub. Switched to ${fallback}.`,
+ );
+ if (fallback !== currentBranch) handleBranchChange(fallback);
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetchSessionMessages, currentBranch, defaultBranch]);
+
+ const handleDeleteSession = useCallback(
+ (deletedId) => {
+ if (deletedId === activeSessionId) {
+ setActiveSessionId(null);
+
+ setChatBySession((prev) => {
+ const next = { ...prev };
+ delete next[deletedId];
+ return next;
+ });
+
+ if (repoKey) {
+ setRepoStateByKey((prev) => {
+ const cur = prev[repoKey];
+ if (!cur) return prev;
+ const branchKey = cur.currentBranch || cur.defaultBranch || defaultBranch;
+ return {
+ ...prev,
+ [repoKey]: {
+ ...cur,
+ chatByBranch: {
+ ...(cur.chatByBranch || {}),
+ [branchKey]: { messages: [], plan: null },
+ },
+ },
+ };
+ });
+ }
+ }
+ },
+ [activeSessionId, repoKey, defaultBranch]
+ );
+
+ // ---------------------------------------------------------------------------
+ // Chat persistence helpers
+ // ---------------------------------------------------------------------------
+ const updateChatForCurrentBranch = (patch) => {
+ if (!repoKey) return;
+
+ setRepoStateByKey((prev) => {
+ const cur = prev[repoKey];
+ if (!cur) return prev;
+
+ const branchKey = cur.currentBranch || cur.defaultBranch || defaultBranch;
+
+ const existing = cur.chatByBranch?.[branchKey] || {
+ messages: [],
+ plan: null,
+ };
+
+ return {
+ ...prev,
+ [repoKey]: {
+ ...cur,
+ chatByBranch: {
+ ...(cur.chatByBranch || {}),
+ [branchKey]: { ...existing, ...patch },
+ },
+ },
+ };
+ });
+ };
+
+ const currentChatState = useMemo(() => {
+ const b = currentBranch || defaultBranch;
+ return chatByBranch[b] || { messages: [], plan: null };
+ }, [chatByBranch, currentBranch, defaultBranch]);
+
+ const sessionChatState = useMemo(() => {
+ if (!activeSessionId) {
+ return currentChatState;
+ }
+ return chatBySession[activeSessionId] || { messages: [], plan: null };
+ }, [activeSessionId, chatBySession, currentChatState]);
+
+ const updateSessionChat = (patch) => {
+ if (activeSessionId) {
+ setChatBySession((prev) => ({
+ ...prev,
+ [activeSessionId]: {
+ ...(prev[activeSessionId] || { messages: [], plan: null }),
+ ...patch,
+ },
+ }));
+ } else {
+ updateChatForCurrentBranch(patch);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // Branch change (manual — for active repo)
+ // ---------------------------------------------------------------------------
+ const handleBranchChange = (nextBranch) => {
+ if (!repoKey) return;
+ if (!nextBranch || nextBranch === currentBranch) return;
+
+ setRepoStateByKey((prev) => {
+ const cur = prev[repoKey];
+ if (!cur) return prev;
+
+ const nextState = { ...cur, currentBranch: nextBranch };
+
+ if (nextBranch === cur.defaultBranch) {
+ nextState.chatByBranch = {
+ ...nextState.chatByBranch,
+ [nextBranch]: { messages: [], plan: null },
+ };
+ }
+
+ return { ...prev, [repoKey]: nextState };
+ });
+
+ setContextRepos((prev) =>
+ prev.map((e) =>
+ e.repoKey === repoKey ? { ...e, branch: nextBranch } : e
+ )
+ );
+
+ if (nextBranch === defaultBranch) {
+ showToast("New Session", `Switched to ${defaultBranch}. Chat cleared.`);
+ } else {
+ showToast("Context Switched", `Now viewing ${nextBranch}.`);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // Execution complete
+ // ---------------------------------------------------------------------------
+ const handleExecutionComplete = ({
+ branch,
+ mode,
+ commit_url,
+ completionMsg,
+ sourceBranch,
+ }) => {
+ if (!repoKey || !branch) return;
+
+ // Clear the session-keyed chat cache's ``plan`` AND append the
+ // completion message synchronously, before any branch change can
+ // trigger ChatPanel's session-sync effect. Two bugs need to be
+ // fixed in the same write:
+ //
+ // 1. Stale plan: without clearing, the sync effect re-reads the
+ // old approved plan and restores the Approve & execute / Reject
+ // plan buttons, enabling accidental double-execution.
+ //
+ // 2. Wiped completion: in hard-switch mode the sync effect runs
+ // BEFORE the persistence effect (declared earlier in
+ // ChatPanel), so it overwrites local ``messages`` with
+ // ``sessionChatState.messages`` — which doesn't yet contain
+ // completionMsg. The user's "Answer / Execution Log" block
+ // then vanishes from the session view.
+ //
+ // By appending normalizedCompletion here, sessionChatState already
+ // carries the completion when the sync effect reads it. No
+ // duplicate is introduced: local ``messages`` already has the same
+ // entry, so the subsequent persistence pass is a no-op write.
+ if (activeSessionId) {
+ const normalizedCompletion =
+ completionMsg &&
+ (completionMsg.answer || completionMsg.content || completionMsg.executionLog)
+ ? {
+ from: completionMsg.from || "ai",
+ role: completionMsg.role || "assistant",
+ answer: completionMsg.answer,
+ content: completionMsg.content,
+ executionLog: completionMsg.executionLog,
+ diff: completionMsg.diff,
+ }
+ : null;
+ setChatBySession((prev) => {
+ const existing = prev[activeSessionId];
+ if (!existing) return prev;
+ const noPlanChange = existing.plan == null;
+ if (noPlanChange && !normalizedCompletion) return prev;
+ return {
+ ...prev,
+ [activeSessionId]: {
+ ...existing,
+ messages: normalizedCompletion
+ ? [...(existing.messages || []), normalizedCompletion]
+ : existing.messages,
+ plan: null,
+ },
+ };
+ });
+ }
+
+ setRepoStateByKey((prev) => {
+ const cur =
+ prev[repoKey] || {
+ defaultBranch,
+ currentBranch: defaultBranch,
+ sessionBranches: [],
+ lastExecution: null,
+ pulseNonce: 0,
+ chatByBranch: { [defaultBranch]: { messages: [], plan: null } },
+ };
+
+ const next = { ...cur };
+ next.lastExecution = { mode, branch, ts: Date.now() };
+
+ if (!next.chatByBranch) next.chatByBranch = {};
+
+ const prevBranchKey =
+ sourceBranch || cur.currentBranch || cur.defaultBranch || defaultBranch;
+
+ const successSystemMsg = {
+ role: "system",
+ isSuccess: true,
+ link: commit_url,
+ content:
+ mode === "hard-switch"
+ ? `🌱 **Session Started:** Created branch \`${branch}\`.`
+ : `✅ **Update Published:** Commits pushed to \`${branch}\`.`,
+ };
+
+ const normalizedCompletion =
+ completionMsg &&
+ (completionMsg.answer || completionMsg.content || completionMsg.executionLog)
+ ? {
+ from: completionMsg.from || "ai",
+ role: completionMsg.role || "assistant",
+ answer: completionMsg.answer,
+ content: completionMsg.content,
+ executionLog: completionMsg.executionLog,
+ }
+ : null;
+
+ if (mode === "hard-switch") {
+ next.sessionBranches = uniq([...(next.sessionBranches || []), branch]);
+ next.currentBranch = branch;
+ next.pulseNonce = (next.pulseNonce || 0) + 1;
+
+ const existingTargetChat = next.chatByBranch[branch];
+ const isExistingSession =
+ existingTargetChat && (existingTargetChat.messages || []).length > 0;
+
+ if (isExistingSession) {
+ const appended = [
+ ...(existingTargetChat.messages || []),
+ ...(normalizedCompletion ? [normalizedCompletion] : []),
+ successSystemMsg,
+ ];
+
+ next.chatByBranch[branch] = {
+ ...existingTargetChat,
+ messages: appended,
+ plan: null,
+ };
+ } else {
+ const prevChat =
+ (cur.chatByBranch && cur.chatByBranch[prevBranchKey]) || {
+ messages: [],
+ plan: null,
+ };
+
+ next.chatByBranch[branch] = {
+ messages: [
+ ...(prevChat.messages || []),
+ ...(normalizedCompletion ? [normalizedCompletion] : []),
+ successSystemMsg,
+ ],
+ plan: null,
+ };
+ }
+
+ if (!next.chatByBranch[next.defaultBranch]) {
+ next.chatByBranch[next.defaultBranch] = { messages: [], plan: null };
+ }
+ } else if (mode === "sticky") {
+ next.currentBranch = cur.currentBranch || branch;
+
+ const targetChat = next.chatByBranch[branch] || { messages: [], plan: null };
+
+ next.chatByBranch[branch] = {
+ messages: [
+ ...(targetChat.messages || []),
+ ...(normalizedCompletion ? [normalizedCompletion] : []),
+ successSystemMsg,
+ ],
+ plan: null,
+ };
+ }
+
+ return { ...prev, [repoKey]: next };
+ });
+
+ if (mode === "hard-switch") {
+ showToast("Context Switched", `Active on ${branch}.`);
+ } else {
+ showToast("Changes Committed", `Updated ${branch}.`);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // Auth & startup render
+ // ---------------------------------------------------------------------------
+ useEffect(() => {
+ checkAuthentication();
+ }, []);
+
+ const checkAuthentication = async () => {
+ setStartupPhase("booting");
+ setStartupStatusMessage("Starting application...");
+ setStartupDetailMessage(
+ "Initializing authentication, provider, and workspace context."
+ );
+
+ try {
+ setStartupPhase("checking-backend");
+ setStartupStatusMessage("Connecting to backend...");
+ setStartupDetailMessage(
+ "Preparing your workspace. First launch may take a few seconds."
+ );
+
+ // Single-source-of-truth init: combines /api/status + /api/auth/status
+ // in one request. Runs exactly once per page load (StrictMode-safe).
+ const initResult = await initApp();
+ const status = initResult.status;
+ if (status) {
+ setStartupStatusSnapshot(status);
+ setAdminStatus(status);
+ }
+
+ const token = localStorage.getItem("github_token");
+ const user = localStorage.getItem("github_user");
+
+ if (token && user) {
+ setStartupPhase("validating-auth");
+ setStartupStatusMessage("Validating authentication...");
+ setStartupDetailMessage(
+ "Restoring your GitHub session and confirming access."
+ );
+
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/auth/validate"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ access_token: token }),
+ timeout: 20000, // 20s — first-load GitHub API validation can be slow
+ });
+
+ if (data.authenticated) {
+ setStartupPhase("restoring-session");
+ setStartupStatusMessage("Restoring workspace...");
+ setStartupDetailMessage(
+ "Loading user profile, reconnecting provider state, and preparing the workspace."
+ );
+
+ setIsAuthenticated(true);
+ setUserInfo(JSON.parse(user));
+ setIsLoading(false);
+ return;
+ }
+ } catch (err) {
+ console.error(err);
+ }
+
+ localStorage.removeItem("github_token");
+ localStorage.removeItem("github_user");
+ }
+
+ setStartupPhase("ready");
+ setStartupStatusMessage("Preparing sign-in...");
+ setStartupDetailMessage(
+ "GitPilot is ready. Please authenticate to continue."
+ );
+
+ setIsAuthenticated(false);
+ setIsLoading(false);
+ } catch (err) {
+ console.error(err);
+ setStartupPhase("fallback");
+ setStartupStatusMessage("Starting application...");
+ setStartupDetailMessage(
+ "Continuing with basic startup while backend status is still loading."
+ );
+ setIsAuthenticated(false);
+ setIsLoading(false);
+ }
+ };
+
+ const handleAuthenticated = (session) => {
+ setIsAuthenticated(true);
+ setUserInfo(session.user);
+ };
+
+ const handleLogout = () => {
+ localStorage.removeItem("github_token");
+ localStorage.removeItem("github_user");
+ setIsAuthenticated(false);
+ setUserInfo(null);
+ clearAllContext();
+ };
+
+ if (isLoading) {
+ return (
+
+ );
+ }
+
+ if (!isAuthenticated) {
+ return (
+
+ );
+ }
+
+ const hasContext = contextRepos.length > 0;
+
+ return (
+
+
+
+
+
+ {activePage === "admin" && (
+
+
+ {["overview", "providers", "workspace-modes", "integrations", "mcp-servers", "sandbox", "sessions", "skills", "security", "advanced"].map((tab) => (
+ setAdminTab(tab)}
+ style={{
+ padding: "8px 16px",
+ borderRadius: "6px",
+ border: adminTab === tab ? "1px solid #3B82F6" : "1px solid #333",
+ background: adminTab === tab ? "#1e3a5f" : "#1a1b26",
+ color: adminTab === tab ? "#93c5fd" : "#a0a0b0",
+ cursor: "pointer",
+ fontSize: "13px",
+ textTransform: "capitalize",
+ }}
+ >
+ {tab.replace("-", " ")}
+
+ ))}
+
+
+ {adminTab === "overview" && (
+
+
+
Server
+
+ {adminStatus?.server_ready ? "Connected" : "Checking..."}
+
+
127.0.0.1:8000
+
+
+
+
Provider
+
+ {adminStatus?.provider?.name || "Loading..."}
+
+
+ {adminStatus?.provider?.configured
+ ? `${adminStatus.provider.model || "Ready"}`
+ : "Not configured"}
+
+
+
+
+
Workspace Modes
+
+ Folder: {adminStatus?.workspace?.folder_mode_available ? "Yes" : "—"}
+
+
+ Local Git: {adminStatus?.workspace?.local_git_available ? "Yes" : "—"}
+
+
+ GitHub: {adminStatus?.workspace?.github_mode_available ? "Yes" : "Optional"}
+
+
+
+
+
GitHub
+
+ {adminStatus?.github?.connected ? "Connected" : "Optional"}
+
+
+ {adminStatus?.github?.username || "Not linked"}
+
+
+
+
+
+
+
Get Started
+
setAdminTab("providers")}
+ style={{
+ padding: "6px 12px",
+ background: "#3B82F6",
+ color: "#fff",
+ border: "none",
+ borderRadius: "4px",
+ cursor: "pointer",
+ fontSize: "12px",
+ marginRight: "4px",
+ }}
+ >
+ Configure Provider
+
+
+
+ )}
+
+ {adminTab === "providers" && (
+
+
AI Providers
+
+
+ )}
+
+ {adminTab === "workspace-modes" && (
+
{
+ setActiveSessionId(result.session_id);
+ setSessionRefreshNonce((n) => n + 1);
+ setActivePage("workspace");
+ }}
+ />
+ )}
+
+ {adminTab === "integrations" && (
+
+ )}
+
+ {adminTab === "mcp-servers" && (
+
+ )}
+
+ {adminTab === "sandbox" && (
+
+ )}
+
+ {adminTab === "security" && (
+
+ )}
+
+ {adminTab === "sessions" && (
+ {
+ handleSelectSession(s);
+ setActivePage("workspace");
+ }}
+ />
+ )}
+
+ {adminTab === "skills" && }
+
+ {adminTab === "advanced" && (
+ setSettingsOpen(true)}
+ />
+ )}
+
+ )}
+
+ {activePage === "flow" && }
+
+ {activePage === "workspace" &&
+ (repo ? (
+
+
setAddRepoOpen(true)}
+ onBranchChange={handleContextBranchChange}
+ />
+
+
+
+ setSettingsOpen(true)}
+ />
+
+
+
+
+ GitPilot chat
+
+
+
+
+
+
+ ) : (
+
+
🤖
+
Select a repository
+
Select a repo to begin agentic workflow.
+
+ ))}
+
+
+
+
+
+ {repo && (
+
setSettingsOpen(false)}
+ activeEnvId={activeEnvId}
+ onEnvChange={setActiveEnvId}
+ />
+ )}
+
+ setAddRepoOpen(false)}
+ excludeKeys={contextRepos.map((e) => e.repoKey)}
+ />
+
+ setAboutOpen(false)}
+ />
+
+ {toast && (
+
+
{toast.title}
+
{toast.message}
+
+ )}
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/components/AboutModal.jsx b/frontend/components/AboutModal.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..e80dd1a98dd3d6caa062310469b6135ec24800dc
--- /dev/null
+++ b/frontend/components/AboutModal.jsx
@@ -0,0 +1,488 @@
+// frontend/components/AboutModal.jsx
+import React, { useEffect, useCallback, useState } from "react";
+import { apiUrl, safeFetchJSON } from "../utils/api.js";
+
+/**
+ * AboutModal — "About GitPilot" dialog shown from the user menu.
+ *
+ * Enterprise design goals:
+ * - Prominent brand mark matching docs/logo.svg (orange ring + GP monogram)
+ * - Clear identity: name, tagline, version (frontend + backend)
+ * - Credits the creator (Ruslan Magana Vsevolodovna) as a link to GitHub
+ * - Open-source positioning: Apache 2.0 license + GitHub repo link
+ * - Action row: View on GitHub, Report Issue, Documentation
+ * - Accessible: role="dialog", aria-modal, aria-labelledby, Escape to close,
+ * focus trap via initial focus on close button
+ * - Brand palette: #D95C3D accent, #1C1C1F card, #27272A border, #EDEDED text
+ */
+
+const FRONTEND_VERSION =
+ typeof __APP_VERSION__ !== "undefined" ? __APP_VERSION__ : "0.1.5";
+
+export default function AboutModal({ isOpen, onClose }) {
+ const [backendVersion, setBackendVersion] = useState(null);
+
+ // Fetch backend version when opened
+ useEffect(() => {
+ if (!isOpen) return;
+ let cancelled = false;
+ (async () => {
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/ping"), { timeout: 4000 });
+ if (!cancelled) {
+ setBackendVersion(data?.version || null);
+ }
+ } catch {
+ if (!cancelled) setBackendVersion(null);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [isOpen]);
+
+ // Escape to close
+ useEffect(() => {
+ if (!isOpen) return;
+ const handleKey = (e) => {
+ if (e.key === "Escape") onClose?.();
+ };
+ document.addEventListener("keydown", handleKey);
+ return () => document.removeEventListener("keydown", handleKey);
+ }, [isOpen, onClose]);
+
+ // Lock body scroll while open
+ useEffect(() => {
+ if (!isOpen) return;
+ const prev = document.body.style.overflow;
+ document.body.style.overflow = "hidden";
+ return () => {
+ document.body.style.overflow = prev;
+ };
+ }, [isOpen]);
+
+ const handleBackdropClick = useCallback(
+ (e) => {
+ if (e.target === e.currentTarget) onClose?.();
+ },
+ [onClose]
+ );
+
+ if (!isOpen) return null;
+
+ return (
+
+
+ {/* Close button */}
+
{
+ e.currentTarget.style.background = "#27272A";
+ e.currentTarget.style.color = "#EDEDED";
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = "transparent";
+ e.currentTarget.style.color = "#A1A1AA";
+ }}
+ >
+
+
+
+
+
+ {/* Hero: brand mark + name */}
+
+
+
+
+ GitPilot
+
+
+ Enterprise Workspace Copilot
+
+
+
+
+ Open Source · Apache 2.0
+
+
+
+ {/* Body */}
+
+
+ An agentic AI coding companion for your repositories. Ask, plan,
+ code, and ship — with multi-LLM support, security scanning, and
+ VS Code integration.
+
+
+ {/* Meta table */}
+
+
+
+
+
+ (e.currentTarget.style.textDecoration = "underline")
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.textDecoration = "none")
+ }
+ >
+ Ruslan Magana Vsevolodovna
+
+ }
+ isLast
+ />
+
+
+
+ {/* Action row */}
+
+
}
+ label="GitHub"
+ />
+
}
+ label="Docs"
+ />
+
}
+ label="Report"
+ />
+
+
+ {/* Footer */}
+
+ © {new Date().getFullYear()} GitPilot · Made with care for
+ developers everywhere
+
+
+
+
+
+ );
+}
+
+// ── Brand mark (mirrors docs/logo.svg) ──────────────────────────────
+function BrandMark() {
+ return (
+
+ {/* Outer subtle ring */}
+
+ {/* Active arc (top-right, uses conic gradient for smooth arc) */}
+
+ {/* Soft core glow */}
+
+ {/* GP monogram */}
+
+ GP
+
+
+ );
+}
+
+// ── Meta row ────────────────────────────────────────────────────────
+function MetaRow({ label, value, isLast = false }) {
+ return (
+
+ {label}
+
+ {value}
+
+
+ );
+}
+
+// ── Action button ───────────────────────────────────────────────────
+function ActionButton({ href, icon, label }) {
+ return (
+ {
+ e.currentTarget.style.borderColor = "#D95C3D";
+ e.currentTarget.style.background = "rgba(217, 92, 61, 0.08)";
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = "#27272A";
+ e.currentTarget.style.background = "#131316";
+ }}
+ >
+
+ {icon}
+
+ {label}
+
+ );
+}
+
+// ── Icons ───────────────────────────────────────────────────────────
+function GitHubIcon() {
+ return (
+
+
+
+ );
+}
+
+function DocsIcon() {
+ return (
+
+
+
+
+ );
+}
+
+function BugIcon() {
+ return (
+
+
+
+
+ );
+}
diff --git a/frontend/components/AddRepoModal.jsx b/frontend/components/AddRepoModal.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..7832877ed985bac5ec81f1b4c43978e525dd8bd2
--- /dev/null
+++ b/frontend/components/AddRepoModal.jsx
@@ -0,0 +1,256 @@
+import React, { useCallback, useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { authFetch } from "../utils/api.js";
+
+/**
+ * AddRepoModal — lightweight portal modal for adding repos to context.
+ *
+ * Embeds a minimal repo search/list (not the full RepoSelector) to keep
+ * the modal focused. Filters out repos already in context.
+ */
+export default function AddRepoModal({ isOpen, onSelect, onClose, excludeKeys = [] }) {
+ const [query, setQuery] = useState("");
+ const [repos, setRepos] = useState([]);
+ const [loading, setLoading] = useState(false);
+
+ const fetchRepos = useCallback(
+ async (searchQuery) => {
+ setLoading(true);
+ try {
+ const params = new URLSearchParams({ per_page: "50" });
+ if (searchQuery) params.set("query", searchQuery);
+ const res = await authFetch(`/api/repos?${params}`);
+ if (!res.ok) return;
+ const data = await res.json();
+ setRepos(data.repositories || []);
+ } catch (err) {
+ console.warn("AddRepoModal: fetch failed:", err);
+ } finally {
+ setLoading(false);
+ }
+ },
+ []
+ );
+
+ useEffect(() => {
+ if (isOpen) {
+ setQuery("");
+ fetchRepos("");
+ }
+ }, [isOpen, fetchRepos]);
+
+ // Debounced search
+ useEffect(() => {
+ if (!isOpen) return;
+ const t = setTimeout(() => fetchRepos(query), 300);
+ return () => clearTimeout(t);
+ }, [query, isOpen, fetchRepos]);
+
+ const excludeSet = new Set(excludeKeys);
+ const filtered = repos.filter((r) => {
+ const key = r.full_name || `${r.owner}/${r.name}`;
+ return !excludeSet.has(key);
+ });
+
+ if (!isOpen) return null;
+
+ return createPortal(
+ {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ >
+
e.stopPropagation()}>
+
+ Add Repository
+
+ ×
+
+
+
+
+ setQuery(e.target.value)}
+ style={styles.searchInput}
+ autoFocus
+ onKeyDown={(e) => {
+ if (e.key === "Escape") onClose();
+ }}
+ />
+
+
+
+ {loading && filtered.length === 0 && (
+
Loading...
+ )}
+ {!loading && filtered.length === 0 && (
+
+ {excludeKeys.length > 0 && repos.length > 0
+ ? "All matching repos are already in context"
+ : "No repositories found"}
+
+ )}
+ {filtered.map((r) => {
+ const key = r.full_name || `${r.owner}/${r.name}`;
+ return (
+
onSelect(r)}
+ >
+
+ {r.name}
+ {r.owner}
+
+
+ {r.private && Private }
+ {r.default_branch || "main"}
+
+
+ );
+ })}
+ {loading && filtered.length > 0 && (
+
Updating...
+ )}
+
+
+
,
+ document.body
+ );
+}
+
+const styles = {
+ overlay: {
+ position: "fixed",
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: "rgba(0, 0, 0, 0.6)",
+ zIndex: 10000,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ modal: {
+ width: 440,
+ maxHeight: "70vh",
+ backgroundColor: "#131316",
+ border: "1px solid #27272A",
+ borderRadius: 12,
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ boxShadow: "0 12px 40px rgba(0,0,0,0.5)",
+ },
+ header: {
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ padding: "12px 14px",
+ borderBottom: "1px solid #27272A",
+ backgroundColor: "#18181B",
+ },
+ headerTitle: {
+ fontSize: 14,
+ fontWeight: 600,
+ color: "#E4E4E7",
+ },
+ closeBtn: {
+ width: 26,
+ height: 26,
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "transparent",
+ color: "#A1A1AA",
+ fontSize: 16,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ searchBox: {
+ padding: "10px 12px",
+ borderBottom: "1px solid #27272A",
+ },
+ searchInput: {
+ width: "100%",
+ padding: "8px 10px",
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "#18181B",
+ color: "#E4E4E7",
+ fontSize: 13,
+ outline: "none",
+ fontFamily: "monospace",
+ boxSizing: "border-box",
+ },
+ list: {
+ flex: 1,
+ overflowY: "auto",
+ maxHeight: 360,
+ },
+ statusRow: {
+ padding: "16px 12px",
+ textAlign: "center",
+ fontSize: 12,
+ color: "#71717A",
+ },
+ repoRow: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ width: "100%",
+ padding: "10px 14px",
+ border: "none",
+ borderBottom: "1px solid rgba(39, 39, 42, 0.5)",
+ background: "transparent",
+ color: "#E4E4E7",
+ cursor: "pointer",
+ textAlign: "left",
+ transition: "background-color 0.1s",
+ },
+ repoInfo: {
+ display: "flex",
+ flexDirection: "column",
+ gap: 2,
+ minWidth: 0,
+ },
+ repoName: {
+ fontSize: 13,
+ fontWeight: 600,
+ fontFamily: "monospace",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ },
+ repoOwner: {
+ fontSize: 11,
+ color: "#71717A",
+ },
+ repoMeta: {
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ flexShrink: 0,
+ },
+ privateBadge: {
+ fontSize: 9,
+ padding: "1px 5px",
+ borderRadius: 8,
+ backgroundColor: "rgba(239, 68, 68, 0.12)",
+ color: "#F87171",
+ fontWeight: 600,
+ textTransform: "uppercase",
+ },
+ branchHint: {
+ fontSize: 10,
+ color: "#52525B",
+ fontFamily: "monospace",
+ },
+};
diff --git a/frontend/components/AdminTabs/AdvancedTab.jsx b/frontend/components/AdminTabs/AdvancedTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..3d0085dd2f5c794d98d18323d48c388e9855df32
--- /dev/null
+++ b/frontend/components/AdminTabs/AdvancedTab.jsx
@@ -0,0 +1,360 @@
+// frontend/components/AdminTabs/AdvancedTab.jsx
+import React, { useEffect, useState, useCallback } from "react";
+import { apiUrl, safeFetchJSON } from "../../utils/api.js";
+
+/**
+ * Advanced tab — inline toggles for:
+ * - Lite Mode (via /api/settings/topology — sets topology to "lite_mode")
+ * - Permission Mode (normal | auto | plan via /api/permissions/mode)
+ * - Link to full Settings modal for power users
+ *
+ * Best practices applied:
+ * - Optimistic UI with rollback on error
+ * - Each setting has its own loading indicator (no global lock)
+ * - Descriptions explain what each mode does
+ * - ARIA-labeled toggle switches for accessibility
+ */
+
+const PERMISSION_MODES = [
+ {
+ value: "normal",
+ label: "Normal",
+ description:
+ "Ask before writing files or running commands (recommended).",
+ },
+ {
+ value: "auto",
+ label: "Auto",
+ description:
+ "Approve all tool calls automatically. Use only when you trust the agent.",
+ },
+ {
+ value: "plan",
+ label: "Plan Only",
+ description:
+ "Read-only mode. Agent cannot write files or run commands.",
+ },
+];
+
+function ToggleSwitch({ checked, onChange, disabled, ariaLabel }) {
+ return (
+ !disabled && onChange(!checked)}
+ disabled={disabled}
+ style={{
+ position: "relative",
+ width: "44px",
+ height: "24px",
+ borderRadius: "12px",
+ background: checked ? "#3B82F6" : "#374151",
+ border: "none",
+ cursor: disabled ? "not-allowed" : "pointer",
+ transition: "background 150ms ease",
+ padding: 0,
+ opacity: disabled ? 0.5 : 1,
+ }}
+ >
+
+
+ );
+}
+
+export default function AdvancedTab({ showToast, onOpenFullSettings }) {
+ const [liteMode, setLiteMode] = useState(false);
+ const [permissionMode, setPermissionMode] = useState("normal");
+ const [loading, setLoading] = useState(true);
+ const [updatingLite, setUpdatingLite] = useState(false);
+ const [updatingPerm, setUpdatingPerm] = useState(false);
+ const [error, setError] = useState(null);
+
+ // Initial fetch: topology preference + permission mode
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const [topo, perms] = await Promise.all([
+ safeFetchJSON(apiUrl("/api/settings/topology"), { timeout: 5000 })
+ .catch(() => ({ topology: null })),
+ safeFetchJSON(apiUrl("/api/permissions"), { timeout: 5000 })
+ .catch(() => ({ mode: "normal" })),
+ ]);
+ if (cancelled) return;
+ setLiteMode(topo?.topology === "lite_mode");
+ setPermissionMode(perms?.mode || perms?.policy?.mode || "normal");
+ } catch (err) {
+ if (!cancelled) setError(err?.message || "Failed to load settings");
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const handleLiteToggle = useCallback(async (next) => {
+ setUpdatingLite(true);
+ setError(null);
+ const previous = liteMode;
+ setLiteMode(next); // optimistic
+ try {
+ await safeFetchJSON(apiUrl("/api/settings/topology"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ topology: next ? "lite_mode" : null }),
+ timeout: 5000,
+ });
+ showToast?.(
+ "Lite Mode " + (next ? "enabled" : "disabled"),
+ next
+ ? "Single-agent path — better for small local models."
+ : "Multi-agent path — uses full CrewAI orchestration."
+ );
+ } catch (err) {
+ setLiteMode(previous); // rollback
+ setError(err?.message || "Failed to update lite mode");
+ } finally {
+ setUpdatingLite(false);
+ }
+ }, [liteMode, showToast]);
+
+ const handlePermissionChange = useCallback(async (next) => {
+ setUpdatingPerm(true);
+ setError(null);
+ const previous = permissionMode;
+ setPermissionMode(next); // optimistic
+ try {
+ const res = await fetch(apiUrl("/api/permissions/mode"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mode: next }),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.detail || `HTTP ${res.status}`);
+ }
+ showToast?.(
+ "Permission mode updated",
+ `Set to ${next}.`
+ );
+ } catch (err) {
+ setPermissionMode(previous); // rollback
+ setError(err?.message || "Failed to update permission mode");
+ } finally {
+ setUpdatingPerm(false);
+ }
+ }, [permissionMode, showToast]);
+
+ if (loading) {
+ return (
+
+
Advanced
+
+ Loading advanced settings...
+
+
+ );
+ }
+
+ return (
+
+
Advanced
+
+ Fine-tune GitPilot's agent behavior and safety settings.
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ {/* Lite Mode toggle */}
+
+
+
+
Lite Mode
+
+ Use a simplified single-agent prompt instead of the multi-agent
+ CrewAI pipeline. Recommended for small local models
+ (qwen2.5:1.5b, deepseek-r1, phi3:mini) that struggle with the
+ ReAct format.
+
+
+
+
+
+
+ {/* Permission Mode selector */}
+
+
Permission Mode
+
+ Controls when the agent needs your approval before writing files or
+ running commands.
+
+
+
+ {PERMISSION_MODES.map((mode) => {
+ const selected = permissionMode === mode.value;
+ return (
+
+ handlePermissionChange(mode.value)}
+ disabled={updatingPerm}
+ style={{ marginTop: "2px", cursor: "inherit" }}
+ />
+
+
+ {mode.label}
+
+
+ {mode.description}
+
+
+
+ );
+ })}
+
+
+
+ {/* Link to full settings modal */}
+
+
+
+
+ Full Settings
+
+
+ Server URL, telemetry, debug logs, environment variables, and more.
+
+
+
+ Open Settings Modal
+
+
+
+
+ );
+}
diff --git a/frontend/components/AdminTabs/IntegrationsTab.jsx b/frontend/components/AdminTabs/IntegrationsTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..e6c4d252324fdb7ce1fc329f05eb5821b4af4078
--- /dev/null
+++ b/frontend/components/AdminTabs/IntegrationsTab.jsx
@@ -0,0 +1,238 @@
+// frontend/components/AdminTabs/IntegrationsTab.jsx
+import React, { useEffect, useState } from "react";
+import { apiUrl, safeFetchJSON } from "../../utils/api.js";
+
+/**
+ * Integrations tab — shows connection status for GitHub (and future
+ * third-party integrations) with Connect/Disconnect actions.
+ *
+ * Best practices applied:
+ * - Fetch current status on mount via /api/auth/status
+ * - Show connected user info if already authenticated
+ * - "Connect GitHub" button opens /api/auth/url in the same window
+ * (OAuth flow will redirect back with ?code=...)
+ * - Disconnect clears localStorage token and re-fetches status
+ * - Handles both Web OAuth and Device Flow modes
+ */
+
+export default function IntegrationsTab({ userInfo, onDisconnect, showToast }) {
+ const [authStatus, setAuthStatus] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [connecting, setConnecting] = useState(false);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/auth/status"), { timeout: 5000 });
+ if (!cancelled) setAuthStatus(data);
+ } catch (err) {
+ if (!cancelled) setError(err?.message || "Failed to check auth status");
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const handleConnect = async () => {
+ setConnecting(true);
+ setError(null);
+ try {
+ if (authStatus?.mode === "web") {
+ // Web OAuth flow — redirect to GitHub authorization URL
+ const { authorization_url, state } = await safeFetchJSON(
+ apiUrl("/api/auth/url"),
+ { timeout: 5000 }
+ );
+ if (state) {
+ sessionStorage.setItem("gitpilot_oauth_state", state);
+ }
+ // Full page redirect (OAuth providers don't support iframes)
+ window.location.href = authorization_url;
+ } else {
+ // Device flow — the LoginPage already handles this.
+ showToast?.(
+ "Device flow",
+ "GitHub device flow is configured. Sign out and sign in again to reconnect."
+ );
+ }
+ } catch (err) {
+ setError(err?.message || "Failed to start OAuth flow");
+ setConnecting(false);
+ }
+ };
+
+ const handleDisconnect = () => {
+ if (!window.confirm("Disconnect GitHub? You will be signed out.")) return;
+ localStorage.removeItem("github_token");
+ localStorage.removeItem("github_user");
+ onDisconnect?.();
+ showToast?.("Disconnected", "GitHub token removed.");
+ };
+
+ const isConnected = !!(userInfo && userInfo.login);
+
+ return (
+
+
Integrations
+
+ Connect third-party services to unlock additional GitPilot features.
+
+
+ {/* GitHub integration card */}
+
+
+
+
GitHub
+
+ Pull requests, issues, and remote repository workflows.
+
+
+
+ {loading ? "CHECKING..." : isConnected ? "CONNECTED" : "NOT CONNECTED"}
+
+
+
+ {isConnected && userInfo && (
+
+ {userInfo.avatar_url && (
+
+ )}
+
+
+ {userInfo.name || userInfo.login}
+
+
@{userInfo.login}
+
+
+ )}
+
+ {error && (
+
+ {error}
+
+ )}
+
+
+ {isConnected ? (
+
+ Disconnect
+
+ ) : (
+
+ {connecting ? "Connecting..." : "Connect GitHub"}
+
+ )}
+
+
+ {authStatus && !isConnected && (
+
+ Auth mode: {authStatus.mode || "unknown"}
+ {authStatus.oauth_configured && " (Web OAuth)"}
+ {authStatus.pat_configured && " (Personal Access Token)"}
+
+ )}
+
+
+ {/* Placeholder for future integrations */}
+
+
+ More integrations coming soon (GitLab, Bitbucket, Jira, Slack)
+
+
+
+ );
+}
diff --git a/frontend/components/AdminTabs/MCPServersTab.jsx b/frontend/components/AdminTabs/MCPServersTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..da6b21c1600e741350c89da0142161b851970c34
--- /dev/null
+++ b/frontend/components/AdminTabs/MCPServersTab.jsx
@@ -0,0 +1,337 @@
+// frontend/components/AdminTabs/MCPServersTab.jsx
+//
+// Settings tab for managing MCP Context Forge servers.
+//
+// UX layout (mirrors industry-standard plugin/extension managers):
+//
+// ┌─ Header ─ gateway pill, totals, global "MCP enabled" toggle ─┐
+// ├─ Sub-tabs: Installed · Catalog · Custom ────────────────────┤
+// ├─ ServerCard list (Installed) │
+// │ ▸ status / description / tags / tool count │
+// │ ▸ Test · Configure · Disable · Uninstall │
+// │ ▸ Expandable per-tool list with risk badges + toggles │
+// └──────────────────────────────────────────────────────────────┘
+
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { apiUrl, safeFetchJSON } from "../../utils/api.js";
+
+import ServerCard from "./mcp/ServerCard.jsx";
+import CatalogList from "./mcp/CatalogList.jsx";
+import CustomInstallForm from "./mcp/CustomInstallForm.jsx";
+import GatewayHeader from "./mcp/GatewayHeader.jsx";
+import SyncReport from "./mcp/SyncReport.jsx";
+
+const TAB_INSTALLED = "installed";
+const TAB_CATALOG = "catalog";
+const TAB_CUSTOM = "custom";
+
+export default function MCPServersTab({ showToast }) {
+ const [activeSubTab, setActiveSubTab] = useState(TAB_INSTALLED);
+ const [status, setStatus] = useState(null);
+ const [servers, setServers] = useState([]);
+ const [catalog, setCatalog] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [syncing, setSyncing] = useState(false);
+ const [syncReport, setSyncReport] = useState(null);
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const [statusData, serversData, catalogData] = await Promise.all([
+ safeFetchJSON(apiUrl("/api/mcp/status"), { timeout: 5000 }),
+ safeFetchJSON(apiUrl("/api/mcp/servers"), { timeout: 5000 }),
+ safeFetchJSON(apiUrl("/api/mcp/catalog"), { timeout: 5000 }),
+ ]);
+ setStatus(statusData);
+ setServers(serversData?.servers || []);
+ setCatalog(catalogData?.items || []);
+ } catch (err) {
+ setError(err?.message || "Failed to load MCP server state");
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const post = useCallback(
+ async (path, body) => {
+ try {
+ const res = await fetch(apiUrl(path), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ if (!res.ok) {
+ const detail = await res.json().catch(() => ({}));
+ throw new Error(detail?.detail || `HTTP ${res.status}`);
+ }
+ return await res.json();
+ } catch (err) {
+ showToast?.("MCP error", err?.message || String(err));
+ throw err;
+ }
+ },
+ [showToast]
+ );
+
+ // ---- Server actions -----------------------------------------------------
+ const onEnableServer = async (id) => {
+ await post(`/api/mcp/servers/${id}/enable`);
+ showToast?.("Server enabled", id);
+ await refresh();
+ };
+ const onDisableServer = async (id) => {
+ await post(`/api/mcp/servers/${id}/disable`);
+ showToast?.("Server disabled", id);
+ await refresh();
+ };
+ const onUninstallServer = async (id) => {
+ if (
+ !window.confirm(
+ `Uninstall ${id}? GitPilot will stop calling its tools immediately.`
+ )
+ )
+ return;
+ await post(`/api/mcp/servers/${id}/uninstall`);
+ showToast?.("Server uninstalled", id);
+ await refresh();
+ };
+ const onTestServer = async (id) => {
+ const result = await post(`/api/mcp/servers/${id}/test`);
+ if (result?.ok) {
+ showToast?.("Server healthy", id);
+ } else {
+ showToast?.(
+ "Server unreachable",
+ result?.reason || result?.error || "Unknown error"
+ );
+ }
+ return result;
+ };
+ const onSync = useCallback(async () => {
+ setSyncing(true);
+ setSyncReport(null);
+ try {
+ const report = await post("/api/mcp/sync", {});
+ setSyncReport(report);
+ const total =
+ (report.added?.length || 0) +
+ (report.kept?.length || 0) +
+ (report.orphaned?.length || 0);
+ showToast?.(
+ report.forge_unreachable ? "Sync failed" : "Sync complete",
+ report.forge_unreachable
+ ? report.error || "forge unreachable"
+ : `+${report.added?.length || 0} added · ${total} total`
+ );
+ await refresh();
+ } catch {
+ // post() already toasted; nothing more to do.
+ } finally {
+ setSyncing(false);
+ }
+ }, [post, refresh, showToast]);
+
+ const onForgetOrphan = async (id) => {
+ if (
+ !window.confirm(
+ `Forget ${id}? It will be removed from the local list.\n` +
+ "Re-attach it to MCP Context Forge then click Sync to bring it back."
+ )
+ )
+ return;
+ await post(`/api/mcp/servers/${id}/forget`);
+ showToast?.("Server forgotten", id);
+ await refresh();
+ };
+
+ const onToggleTool = async (serverId, toolName, enabled) => {
+ await post(
+ `/api/mcp/servers/${serverId}/tools/${encodeURIComponent(
+ toolName
+ )}/toggle`,
+ { enabled }
+ );
+ await refresh();
+ };
+
+ const onInstallFromCatalog = async (serverId) => {
+ await post("/api/mcp/servers/install", { server_id: serverId });
+ showToast?.("Installed", `${serverId} (disabled until you enable it)`);
+ await refresh();
+ setActiveSubTab(TAB_INSTALLED);
+ };
+
+ const onInstallCustom = async (registerJson) => {
+ await post("/api/mcp/servers/install-custom", {
+ register_json: registerJson,
+ });
+ showToast?.("Custom server added", registerJson.name);
+ await refresh();
+ setActiveSubTab(TAB_INSTALLED);
+ };
+
+ // ---- Derived totals -----------------------------------------------------
+ const installedCount = servers.filter((s) => s.installed).length;
+ const enabledCount = servers.filter((s) => s.installed && s.enabled).length;
+ const totalTools = useMemo(
+ () => servers.reduce((acc, s) => acc + (s.tool_count || 0), 0),
+ [servers]
+ );
+
+ return (
+
+
+
+ {syncReport && (
+
setSyncReport(null)}
+ />
+ )}
+
+ {/* Sub-tab strip */}
+
+ {[
+ { id: TAB_INSTALLED, label: `Installed (${installedCount})` },
+ { id: TAB_CATALOG, label: `Catalog (${catalog.length})` },
+ { id: TAB_CUSTOM, label: "Custom" },
+ ].map((t) => (
+ setActiveSubTab(t.id)}
+ style={{
+ padding: "10px 16px",
+ border: "none",
+ background: "transparent",
+ color: activeSubTab === t.id ? "#93c5fd" : "#a0a0b0",
+ borderBottom:
+ activeSubTab === t.id
+ ? "2px solid #3B82F6"
+ : "2px solid transparent",
+ cursor: "pointer",
+ fontSize: "13px",
+ fontWeight: activeSubTab === t.id ? 600 : 400,
+ }}
+ >
+ {t.label}
+
+ ))}
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ {loading && !servers.length && (
+ Loading…
+ )}
+
+ {activeSubTab === TAB_INSTALLED && !loading && (
+
+ {servers.length === 0 && (
+ setActiveSubTab(TAB_CATALOG)}
+ />
+ )}
+ {servers.map((s) => (
+ onEnableServer(s.id)}
+ onDisable={() => onDisableServer(s.id)}
+ onUninstall={() => onUninstallServer(s.id)}
+ onTest={() => onTestServer(s.id)}
+ onForget={s.orphan ? () => onForgetOrphan(s.id) : undefined}
+ onToggleTool={(tool, enabled) =>
+ onToggleTool(s.id, tool, enabled)
+ }
+ />
+ ))}
+
+ )}
+
+ {activeSubTab === TAB_CATALOG && !loading && (
+
+ )}
+
+ {activeSubTab === TAB_CUSTOM && (
+
+ )}
+
+ );
+}
+
+function EmptyState({ title, hint, actionLabel, onAction }) {
+ return (
+
+
{title}
+
+ {hint}
+
+ {actionLabel && (
+
+ {actionLabel}
+
+ )}
+
+ );
+}
diff --git a/frontend/components/AdminTabs/MatrixLabInstallModal.jsx b/frontend/components/AdminTabs/MatrixLabInstallModal.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..d590f795dd60498d6d4f7f451332d82e1af96e01
--- /dev/null
+++ b/frontend/components/AdminTabs/MatrixLabInstallModal.jsx
@@ -0,0 +1,1013 @@
+// frontend/components/AdminTabs/MatrixLabInstallModal.jsx
+import React, { useCallback, useEffect, useState } from "react";
+import { apiUrl } from "../../utils/api.js";
+
+/**
+ * MatrixLab install modal — the "addon store" experience.
+ *
+ * Drives a single state machine off /api/matrixlab/* so the user sees
+ * one coherent state at a time (not "Unreachable" + "Running" + raw
+ * stack-trace at once). Default view exposes a single primary button;
+ * Runner URL / token / image / network / timeout live behind an
+ * Advanced disclosure.
+ *
+ * Status names mirror the backend MatrixLabStatus enum:
+ * not_installed | installing | starting | stopping | checking |
+ * ready | needs_attention | failed
+ */
+
+// Progress checklists vary by which lifecycle the operator launched.
+// The active "current step" key is set on the busy state so the
+// checklist tracks the user's chosen journey, not a generic install.
+const PROGRESS_STEPS = {
+ install: [
+ { key: "system", label: "Checking system" },
+ { key: "install", label: "Downloading MatrixLab" },
+ { key: "start", label: "Starting runner" },
+ { key: "test", label: "Testing connection" },
+ { key: "activate", label: "Activating MatrixLab" },
+ ],
+ repair: [
+ { key: "system", label: "Checking runner URL" },
+ { key: "repair", label: "Restarting runner" },
+ { key: "test", label: "Testing connection" },
+ { key: "activate", label: "Activating MatrixLab" },
+ ],
+ reinstall: [
+ { key: "system", label: "Stopping current runner" },
+ { key: "remove", label: "Removing old addon" },
+ { key: "install", label: "Downloading fresh version" },
+ { key: "start", label: "Starting runner" },
+ { key: "test", label: "Testing connection" },
+ { key: "activate", label: "Activating MatrixLab" },
+ ],
+};
+
+// Primary action label and the journey it triggers, keyed by the
+// addon's normalised status. Mapping is exhaustive so the modal
+// always has a clear "next thing to do" button.
+const PRIMARY_BY_STATUS = {
+ not_installed: { label: "Install and Start", action: "install" },
+ installing: { label: "Installing…", action: null },
+ starting: { label: "Starting…", action: null },
+ stopping: { label: "Stopping…", action: null },
+ checking: { label: "Checking…", action: null },
+ needs_attention: { label: "Repair connection", action: "repair" },
+ failed: { label: "Retry installation", action: "install" },
+ ready: { label: "Done", action: "done" },
+};
+
+function statusPill(status) {
+ const map = {
+ not_installed: { label: "Not installed", bg: "#374151", fg: "#d1d5db" },
+ installing: { label: "Installing", bg: "#0d3320", fg: "#86efac" },
+ starting: { label: "Starting", bg: "#0d3320", fg: "#86efac" },
+ stopping: { label: "Stopping", bg: "#3d2d11", fg: "#fde68a" },
+ checking: { label: "Checking", bg: "#0d3320", fg: "#86efac" },
+ ready: { label: "Ready", bg: "#0d3320", fg: "#86efac" },
+ needs_attention: { label: "Needs attention", bg: "#3d2d11", fg: "#fde68a" },
+ failed: { label: "Failed", bg: "#3d1111", fg: "#fca5a5" },
+ };
+ return map[status] || map.not_installed;
+}
+
+export default function MatrixLabInstallModal({ onClose, onActivated }) {
+ const [status, setStatus] = useState(null); // MatrixLabStatus from backend
+ const [busy, setBusy] = useState(false);
+ // Which journey is currently in flight ("install" | "repair" |
+ // "reinstall") — drives the progress checklist's stage list.
+ const [journey, setJourney] = useState(null);
+ const [progressStep, setProgressStep] = useState(null);
+ const [showAdvanced, setShowAdvanced] = useState(false);
+ const [showDetails, setShowDetails] = useState(false);
+ const [logs, setLogs] = useState(null);
+ const [showLogs, setShowLogs] = useState(false);
+ // Reinstall confirmation prompt + the destructive "wipe images" opt-in.
+ const [reinstallConfirm, setReinstallConfirm] = useState(false);
+ const [reinstallWipe, setReinstallWipe] = useState(false);
+
+ // Mirror of /api/sandbox/status for the Advanced panel.
+ const [advanced, setAdvanced] = useState(null);
+ const [tokenInput, setTokenInput] = useState("");
+
+ const refresh = useCallback(async () => {
+ try {
+ const r = await fetch(apiUrl("/api/matrixlab/status"));
+ const data = await r.json();
+ setStatus(data);
+ } catch (err) {
+ setStatus({
+ status: "failed",
+ message: "GitPilot backend could not return a MatrixLab status.",
+ errorCode: "BACKEND_UNREACHABLE",
+ technicalDetails: { rawError: err?.message || String(err) },
+ });
+ }
+ }, []);
+
+ const refreshAdvanced = useCallback(async () => {
+ try {
+ const r = await fetch(apiUrl("/api/sandbox/status"));
+ const data = await r.json();
+ setAdvanced(data);
+ } catch (err) {
+ // Non-fatal — Advanced just stays empty.
+ }
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ refreshAdvanced();
+ }, [refresh, refreshAdvanced]);
+
+ // Run a sequence of phased POSTs against /api/matrixlab/* and walk
+ // the progress checklist as each one returns. Used for install,
+ // repair, and reinstall — they differ only in which endpoint kicks
+ // off the journey.
+ const runJourney = useCallback(async (journeyKey, kickoffPath, kickoffBody) => {
+ setBusy(true);
+ setJourney(journeyKey);
+ setShowDetails(false);
+ try {
+ // Phase 1: kickoff (install / repair / reinstall). Each backend
+ // endpoint is itself idempotent and aggregates several docker
+ // commands; the modal walks the checklist on the way.
+ setProgressStep(journeyKey === "reinstall" ? "system" : journeyKey);
+ let r = await fetch(apiUrl(kickoffPath), {
+ method: "POST",
+ headers: kickoffBody ? { "Content-Type": "application/json" } : undefined,
+ body: kickoffBody ? JSON.stringify(kickoffBody) : undefined,
+ });
+ let data = await r.json();
+ setStatus(data);
+ if (data.status === "failed") return;
+
+ // Phase 2: explicit connection test so we never claim "ready"
+ // without a green health probe.
+ setProgressStep("test");
+ r = await fetch(apiUrl("/api/matrixlab/test"), { method: "POST" });
+ data = await r.json();
+ setStatus(data);
+ if (data.status !== "ready") return;
+
+ // Phase 3: activate (always safe to call when ready).
+ setProgressStep("activate");
+ r = await fetch(apiUrl("/api/matrixlab/activate"), { method: "POST" });
+ data = await r.json();
+ setStatus(data);
+ if (data.status === "ready" && data.activeSandbox === "matrixlab") {
+ onActivated?.(data);
+ }
+ } catch (err) {
+ setStatus({
+ status: "failed",
+ message: `MatrixLab ${journeyKey} could not complete.`,
+ errorCode: "NETWORK_ERROR",
+ technicalDetails: { rawError: err?.message || String(err) },
+ });
+ } finally {
+ setBusy(false);
+ setProgressStep(null);
+ setJourney(null);
+ refreshAdvanced();
+ }
+ }, [onActivated, refreshAdvanced]);
+
+ const runInstall = useCallback(() => runJourney("install", "/api/matrixlab/install"), [runJourney]);
+ const runRepair = useCallback(() => runJourney("repair", "/api/matrixlab/repair"), [runJourney]);
+ const runReinstall = useCallback((removeData) => runJourney(
+ "reinstall", "/api/matrixlab/reinstall", { remove_data: !!removeData },
+ ), [runJourney]);
+ // Cheap recovery: persist the discovered URL without restarting the
+ // runner. Most "needs_attention" cases are stale URLs from the
+ // :8000 → :8765 port move, and this resolves them in <1s.
+ const runUrlAutoDetect = useCallback(
+ () => runJourney("repair", "/api/matrixlab/url/auto-detect"),
+ [runJourney],
+ );
+
+ const openLogs = useCallback(async () => {
+ setShowLogs(true);
+ try {
+ const r = await fetch(apiUrl("/api/matrixlab/logs?tail=200"));
+ const data = await r.json();
+ setLogs(data);
+ } catch (err) {
+ setLogs({ ok: false, error: err?.message || String(err), lines: [] });
+ }
+ }, []);
+
+ const onPrimary = () => {
+ if (!status) return;
+ const next = (PRIMARY_BY_STATUS[status.status] || PRIMARY_BY_STATUS.not_installed).action;
+ if (!next) return; // in-flight states have no primary action
+ if (next === "done") return onClose?.();
+ if (next === "install") return runInstall();
+ if (next === "repair") return runRepair();
+ };
+
+ const updateAdvanced = async (patch) => {
+ try {
+ const r = await fetch(apiUrl("/api/sandbox/config"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(patch),
+ });
+ const data = await r.json();
+ if (r.ok) {
+ setAdvanced((prev) => ({ ...(prev || {}), ...data }));
+ if ("matrixlab_token" in patch) setTokenInput("");
+ // Re-probe the addon status — URL / token changes may make us
+ // reachable again.
+ refresh();
+ }
+ } catch (err) {
+ // surfaced through the next refresh
+ }
+ };
+
+ if (!status) {
+ return (
+
+
+
+ Checking MatrixLab status…
+
+
+
+ );
+ }
+
+ const pill = statusPill(status.status);
+
+ return (
+
+
+ {/* Status row */}
+
+
+
+ {pill.label}
+
+
+
{status.message}
+ {status.runnerUrl && status.status !== "ready" && (
+
+ Runner URL: {status.runnerUrl}
+
+ )}
+ {/* Stale-URL recovery: backend probes candidate ports
+ when the configured URL is down. When a live one is
+ found we offer a one-click switch — this fixes the
+ very common "MatrixLab is installed but GitPilot
+ cannot connect" after the :8000 → :8765 port move. */}
+ {status.discoveredUrl && status.discoveredUrl !== status.runnerUrl && (
+
+
+ Found a live runner at{" "}
+
+ {status.discoveredUrl}
+
+
+
+ Use this URL
+
+
+ )}
+
+
+
+ {/* Inline body — copy depends on state */}
+ {status.status === "not_installed" && (
+
+ MatrixLab gives GitPilot an isolated sandbox for running code,
+ testing snippets, and executing agent actions safely. It will be
+ downloaded, started, and connected automatically.
+
+ )}
+
+ {(busy || progressStep) && (
+
+ )}
+
+ {status.status === "ready" && (
+
+ )}
+
+ {/* Lifecycle disabled hint — friendly copy, admin detail under disclosure */}
+ {status.errorCode === "LIFECYCLE_DISABLED" && (
+
+ MatrixLab lifecycle automation is disabled. This GitPilot backend
+ was started with{" "}
+
+ GITPILOT_ENABLE_MATRIXLAB_LIFECYCLE=0
+ {" "}
+ — restart it without that variable (the default is enabled), or
+ use Manual setup under Advanced options.
+
+ )}
+
+ {/* Technical details disclosure — only visible when there's an error */}
+ {status.technicalDetails && (status.status === "needs_attention" || status.status === "failed") && (
+ setShowDetails(e.target.open)}
+ style={{ marginBottom: 12 }}
+ >
+
+ Technical details
+
+
+ {status.technicalDetails.expected &&
+ `Expected: ${status.technicalDetails.expected}\n`}
+ {status.technicalDetails.actual &&
+ `Actual: ${status.technicalDetails.actual}\n`}
+ {status.technicalDetails.rawError &&
+ `\n${status.technicalDetails.rawError}`}
+
+
+ )}
+
+ {/* Action buttons — state-aware. Reinstall is offered as a
+ normal recovery action (not buried in Advanced) once the
+ addon exists in some form; Open logs surfaces only when
+ there's something to diagnose. */}
+ {(() => {
+ const primary = PRIMARY_BY_STATUS[status.status] || PRIMARY_BY_STATUS.not_installed;
+ const canReinstall = status.installed === true ||
+ ["needs_attention", "failed", "ready"].includes(status.status);
+ const canSeeLogs = ["needs_attention", "failed"].includes(status.status);
+ return (
+
+
+ {primary.label}
+
+
+ {canReinstall && (
+ setReinstallConfirm(true)}
+ disabled={busy}
+ style={status.status === "ready" ? btnDanger : btnSecondary}
+ title="Stop, remove, and pull a fresh copy of MatrixLab"
+ >
+ Reinstall addon
+
+ )}
+
+ {canSeeLogs && (
+
+ Open logs
+
+ )}
+
+ {status.status === "ready" && (
+
+ Run test snippet
+
+ )}
+
+ );
+ })()}
+
+ {/* Logs viewer */}
+ {showLogs && (
+
+
+
+ MatrixLab logs
+ {logs?.container && (
+
+ · {logs.container}
+
+ )}
+
+
+ ↻ Refresh
+
+
+
+ {/* Friendly error + hint when the backend can't read logs.
+ We show the hint as an actionable next step (run
+ "make install-matrixlab") and list any matrixlab-
+ shaped containers we found so the user can see whether
+ the runner is up under a different name. */}
+ {logs?.ok === false && (
+
+
{logs.error || "Could not read MatrixLab logs."}
+ {logs.hint && (
+
+ Next step:{" "}
+
+ {logs.hint}
+
+
+ )}
+ {Array.isArray(logs.candidates) && logs.candidates.length > 0 && (
+
+ Found other matrixlab-shaped containers:
+
+ {logs.candidates.map((c, i) => (
+
+ {c}
+
+ ))}
+
+
+ Set GITPILOT_MATRIXLAB_CONTAINER to use one of these,
+ or run Reinstall to recreate the expected container.
+
+
+ )}
+ {logs.rawError && (
+
+
+ docker stderr
+
+
+ {logs.rawError}
+
+
+ )}
+
+ )}
+
+
+ {logs == null
+ ? "Loading logs…"
+ : (logs.lines && logs.lines.length > 0)
+ ? logs.lines.join("\n")
+ : (logs.ok === false ? "(no log output captured)" : "Loading logs…")}
+
+
+ )}
+
+ {/* Advanced options — collapsed by default so first-time
+ users see the install/repair flow, not a wall of knobs.
+ Operators who need runner URL / token / image / network /
+ timeout / manual setup / local clone install / unsafe
+ modes click the disclosure to expand. */}
+ setShowAdvanced(e.target.open)}
+ style={{ marginTop: 14 }}
+ >
+
+ Advanced options
+
+ {
+ setStatus(data);
+ refreshAdvanced();
+ }}
+ />
+
+
+ {reinstallConfirm && (
+ {
+ setReinstallConfirm(false);
+ setReinstallWipe(false);
+ }}
+ onConfirm={() => {
+ const wipe = reinstallWipe;
+ setReinstallConfirm(false);
+ setReinstallWipe(false);
+ runReinstall(wipe);
+ }}
+ />
+ )}
+
+
+ );
+}
+
+function ReinstallConfirm({ wipe, setWipe, onCancel, onConfirm }) {
+ // Modal-in-modal stacked at zIndex 110 (Backdrop is 100). Apes
+ // GitHub's "Are you absolutely sure?" pattern: explicit destructive
+ // checkbox stays off by default so a misclick can't wipe images.
+ return (
+
+
e.stopPropagation()} style={{
+ width: "min(440px, 92vw)", background: "#1a1b26",
+ border: "1px solid #2a2b36", borderRadius: 10, padding: 20,
+ color: "#e6e8ff",
+ }}>
+
Reinstall MatrixLab Addon?
+
+ This will stop MatrixLab, remove the current addon container, download a
+ fresh copy, start it again, and reconnect GitPilot. Your GitPilot
+ settings will be kept.
+
+
+ setWipe(e.target.checked)}
+ style={{ marginTop: 2 }}
+ />
+
+ Also remove local MatrixLab data
+
+ Deletes the cached MatrixLab runner image. Sandbox images and
+ workspace data are preserved.
+
+
+
+
+ Cancel
+
+ {wipe ? "Reinstall and remove data" : "Reinstall MatrixLab"}
+
+
+
+
+ );
+}
+
+function ProgressChecklist({ journey, current }) {
+ // Pick the right stage list for the journey in flight; default to
+ // the install list (the most informative one) when no journey is
+ // active yet. Once ``current`` advances past the kickoff key, the
+ // visited rows render with a ✓.
+ const steps = PROGRESS_STEPS[journey] || PROGRESS_STEPS.install;
+ const phaseIndex = current ? Math.max(0, steps.findIndex(s => s.key === current)) : 0;
+ return (
+
+ {steps.map((s, i) => {
+ const done = i < phaseIndex;
+ const active = i === phaseIndex;
+ return (
+
+
+ {done ? "✓" : active ? "⏳" : "○"}
+
+ {s.label}
+
+ );
+ })}
+
+ );
+}
+
+function Checklist({ items }) {
+ return (
+
+ {items.map(([label, ok]) => (
+
+ {ok ? "✓" : "○"}
+ {label}
+
+ ))}
+
+ );
+}
+
+function LocalCloneSection({ disabled, onStatus }) {
+ const [native, setNative] = useState(null);
+ const [busy, setBusy] = useState(null); // "install" | "start" | "stop"
+
+ const refresh = useCallback(async () => {
+ try {
+ const r = await fetch(apiUrl("/api/matrixlab/native/status"));
+ setNative(await r.json());
+ } catch (err) {
+ // non-fatal — leave section empty
+ }
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const runAction = useCallback(async (action) => {
+ setBusy(action);
+ try {
+ const path = {
+ install: "/api/matrixlab/install_local",
+ start: "/api/matrixlab/start_local",
+ stop: "/api/matrixlab/stop_local",
+ }[action];
+ const r = await fetch(apiUrl(path), { method: "POST" });
+ const data = await r.json();
+ onStatus?.(data);
+ } finally {
+ setBusy(null);
+ refresh();
+ }
+ }, [onStatus, refresh]);
+
+ if (!native) return null;
+
+ return (
+
+
+ Local clone install (no Docker for the runner itself)
+
+
+ Clones MatrixLab into {native.local_dir},
+ creates a dedicated Python virtualenv, and runs uvicorn app.main:app
+ from the runner directory. The Runner still spawns per-language sandboxes
+ via Docker, so the host needs docker{" "}
+ on PATH for code execution.
+
+
+
+
+ {native.running ? "Running (PID " + native.pid + ")"
+ : native.installed ? "Installed · stopped"
+ : "Not installed"}
+
+ {!native.installed && (
+ runAction("install")}
+ style={btnPrimarySmall}
+ >
+ {busy === "install" ? "Cloning + installing…" : "Clone and install"}
+
+ )}
+ {native.installed && !native.running && (
+ runAction("start")}
+ style={btnPrimarySmall}
+ >
+ {busy === "start" ? "Starting…" : "Start runner"}
+
+ )}
+ {native.running && (
+ runAction("stop")}
+ style={btnSecondarySmall}
+ >
+ {busy === "stop" ? "Stopping…" : "Stop runner"}
+
+ )}
+
+ Refresh
+
+
+ {!native.lifecycleEnabled && (
+
+ Local clone install needs lifecycle automation enabled on the GitPilot
+ backend.
+
+ )}
+
+ );
+}
+
+function AdvancedOptions({ advanced, tokenInput, setTokenInput, onUpdate, disabled, onLocalStatus }) {
+ if (!advanced) return null;
+ return (
+
+
+ Advanced options
+
+
+
+
+
+
+
+ Manual setup
+
+ {`# In a MatrixLab checkout:
+docker compose up -d
+
+# Or directly:
+docker run -d --name gitpilot-matrixlab \\
+ -p 8000:8000 \\
+ -v /var/run/docker.sock:/var/run/docker.sock \\
+ ruslanmv/matrixlab-runner:latest`}
+
+
+
+
+ Developer options · Unsafe modes
+
+
+ Pass-through runs code directly on the host without isolation. Use
+ only for local development.
+
+
+
+ );
+}
+
+function Backdrop({ children, onClose }) {
+ return (
+
+
e.stopPropagation()}>{children}
+
+ );
+}
+
+function ModalShell({ title, subtitle, onClose, children }) {
+ return (
+
+
+
{title}
+
+ ✕
+
+
+
{subtitle}
+ {children}
+
+ );
+}
+
+const btnSecondary = {
+ padding: "8px 14px",
+ fontSize: 12,
+ background: "transparent",
+ color: "#c3c5dd",
+ border: "1px solid #2c2d46",
+ borderRadius: 6,
+ cursor: "pointer",
+};
+
+const btnPrimary = {
+ padding: "8px 14px",
+ fontSize: 12,
+ fontWeight: 600,
+ background: "#3B82F6",
+ color: "#fff",
+ border: "none",
+ borderRadius: 6,
+ cursor: "pointer",
+};
+
+// "Reinstall and remove data" is destructive — surface it with a
+// danger tone so the operator pauses before clicking.
+const btnDanger = {
+ padding: "8px 14px",
+ fontSize: 12,
+ fontWeight: 600,
+ background: "#7f1d1d",
+ color: "#fecaca",
+ border: "1px solid #991b1b",
+ borderRadius: 6,
+ cursor: "pointer",
+};
+
+const btnGhost = {
+ padding: "8px 14px",
+ fontSize: 12,
+ background: "transparent",
+ color: "#9092b5",
+ border: "none",
+ cursor: "pointer",
+};
+
+const fieldLabel = { fontSize: 12, color: "#c3c5dd" };
+const fieldInput = {
+ fontSize: 12, padding: "4px 6px",
+ background: "#14152a", color: "#e6e8ff",
+ border: "1px solid #2c2d46", borderRadius: 4,
+};
+
+const btnPrimarySmall = {
+ padding: "4px 10px", fontSize: 11, fontWeight: 600,
+ background: "#3B82F6", color: "#fff",
+ border: "none", borderRadius: 4, cursor: "pointer",
+};
+const btnSecondarySmall = {
+ padding: "4px 10px", fontSize: 11,
+ background: "transparent", color: "#c3c5dd",
+ border: "1px solid #2c2d46", borderRadius: 4, cursor: "pointer",
+};
diff --git a/frontend/components/AdminTabs/SandboxTab.jsx b/frontend/components/AdminTabs/SandboxTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..b006b4b89c3355569240e56d3a27b08c38b7ebde
--- /dev/null
+++ b/frontend/components/AdminTabs/SandboxTab.jsx
@@ -0,0 +1,218 @@
+// frontend/components/AdminTabs/SandboxTab.jsx
+import React, { useCallback, useEffect, useState } from "react";
+import { apiUrl } from "../../utils/api.js";
+import MatrixLabInstallModal from "./MatrixLabInstallModal.jsx";
+
+/**
+ * Sandbox tab — enterprise default view.
+ *
+ * Surfaces a single MatrixLab addon card plus a clean Local-sandbox
+ * card. Implementation knobs (Runner URL, token, image, network,
+ * timeout, pass-through, lifecycle env flag) live behind the install
+ * modal's Advanced disclosure — the primary view never shows them.
+ *
+ * Status pill is driven off /api/matrixlab/status so we never end up
+ * with the "Unreachable + Running" contradiction the legacy panel
+ * produced.
+ */
+
+function StatusPill({ status }) {
+ const map = {
+ not_installed: { label: "Not installed", bg: "#374151", fg: "#d1d5db" },
+ installing: { label: "Installing", bg: "#0d3320", fg: "#86efac" },
+ starting: { label: "Starting", bg: "#0d3320", fg: "#86efac" },
+ stopping: { label: "Stopping", bg: "#3d2d11", fg: "#fde68a" },
+ checking: { label: "Checking", bg: "#0d3320", fg: "#86efac" },
+ ready: { label: "Ready", bg: "#0d3320", fg: "#86efac" },
+ needs_attention: { label: "Needs attention", bg: "#3d2d11", fg: "#fde68a" },
+ failed: { label: "Failed", bg: "#3d1111", fg: "#fca5a5" },
+ };
+ const pill = map[status] || map.not_installed;
+ return (
+
+
+ {pill.label}
+
+ );
+}
+
+export default function SandboxTab({ showToast }) {
+ const [matrixlab, setMatrixlab] = useState(null); // /api/matrixlab/status payload
+ const [sandbox, setSandbox] = useState(null); // /api/sandbox/status payload
+ const [loading, setLoading] = useState(true);
+ const [modalOpen, setModalOpen] = useState(false);
+
+ const load = useCallback(async () => {
+ try {
+ const [ml, sb] = await Promise.all([
+ fetch(apiUrl("/api/matrixlab/status")).then((r) => r.json()).catch(() => null),
+ fetch(apiUrl("/api/sandbox/status")).then((r) => r.json()).catch(() => null),
+ ]);
+ setMatrixlab(ml);
+ setSandbox(sb);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ load();
+ }, [load]);
+
+ const useLocal = useCallback(async () => {
+ try {
+ const r = await fetch(apiUrl("/api/sandbox/config"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ backend: "subprocess" }),
+ });
+ const data = await r.json();
+ if (r.ok) {
+ setSandbox(data);
+ showToast?.("Switched to Local sandbox", "Code runs in a host subprocess with a workspace jail.");
+ }
+ } catch (err) {
+ // surfaced through the next load()
+ }
+ }, [showToast]);
+
+ if (loading) {
+ return (
+
+
Sandbox
+
+ Loading sandbox status…
+
+
+ );
+ }
+
+ const activeBackend = (sandbox?.backend || "subprocess").toLowerCase();
+ const mlStatus = matrixlab?.status || "not_installed";
+
+ return (
+
+
Sandbox
+
+ Pick where GitPilot executes code: the local subprocess sandbox or
+ the MatrixLab Runner. The choice applies to the Run button on chat
+ code blocks and the agent's EXECUTE action.
+
+
+ {/* MatrixLab addon card */}
+
+
+
+
+
MatrixLab Addon
+
+ {activeBackend === "matrixlab" && (
+ ACTIVE
+ )}
+
+
+ Run code safely in isolated, temporary containers. Recommended
+ for enterprise deployments and untrusted code.
+
+ {mlStatus !== "not_installed" && matrixlab?.message && (
+
+ {matrixlab.message}
+
+ )}
+
+
setModalOpen(true)}
+ style={{
+ padding: "8px 16px", fontSize: 12, fontWeight: 600,
+ background: mlStatus === "ready" ? "transparent" : "#3B82F6",
+ color: mlStatus === "ready" ? "#93c5fd" : "#fff",
+ border: mlStatus === "ready" ? "1px solid #3B82F6" : "none",
+ borderRadius: 6, cursor: "pointer",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {mlStatus === "ready" ? "Manage" :
+ mlStatus === "needs_attention" ? "Fix connection" :
+ mlStatus === "failed" ? "Retry install" :
+ "Install and Start"}
+
+
+
+
+ {/* Local sandbox card */}
+
+
+
+
+
Local sandbox
+ {activeBackend === "subprocess" && (
+ ACTIVE
+ )}
+
+
+ Host subprocess with a workspace jail. No Docker required —
+ best for trying simple snippets quickly.
+
+
+
+ {activeBackend === "subprocess" ? "Active" : "Use Local"}
+
+
+
+
+ {modalOpen && (
+
{
+ setModalOpen(false);
+ load();
+ }}
+ onActivated={(data) => {
+ showToast?.("MatrixLab ready", "Code now runs in MatrixLab sandboxes.");
+ // Refresh both panels so the ACTIVE badge moves to the addon card.
+ load();
+ }}
+ />
+ )}
+
+ );
+}
+
+const cardStyle = {
+ background: "#1a1b26",
+ borderRadius: 8,
+ padding: 16,
+ border: "1px solid #2a2b36",
+ marginBottom: 12,
+};
diff --git a/frontend/components/AdminTabs/SecurityTab.jsx b/frontend/components/AdminTabs/SecurityTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..f39161c491b77076489b0fa0163abf5b8d4fe33f
--- /dev/null
+++ b/frontend/components/AdminTabs/SecurityTab.jsx
@@ -0,0 +1,341 @@
+// frontend/components/AdminTabs/SecurityTab.jsx
+import React, { useState } from "react";
+import { scanWorkspace } from "../../utils/api.js";
+
+/**
+ * Security tab — runs a workspace scan via /api/security/scan-workspace
+ * and renders findings grouped by severity.
+ *
+ * Best practices applied:
+ * - Custom path input (defaults to ".")
+ * - Loading spinner while scanning
+ * - Error state with retry
+ * - Empty state ("No findings") with green checkmark
+ * - Findings grouped by severity (critical → info)
+ * - Each finding shows file, line, CWE, recommendation
+ * - Color-coded severity badges
+ */
+
+const SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
+
+const SEVERITY_COLORS = {
+ critical: { bg: "#7f1d1d", text: "#fecaca", border: "#991b1b" },
+ high: { bg: "#9a3412", text: "#fed7aa", border: "#c2410c" },
+ medium: { bg: "#78350f", text: "#fde68a", border: "#a16207" },
+ low: { bg: "#164e63", text: "#a5f3fc", border: "#0e7490" },
+ info: { bg: "#1e3a5f", text: "#93c5fd", border: "#3B82F6" },
+};
+
+function SeverityBadge({ severity }) {
+ const c = SEVERITY_COLORS[severity] || SEVERITY_COLORS.info;
+ return (
+
+ {severity}
+
+ );
+}
+
+export default function SecurityTab({ showToast }) {
+ const [path, setPath] = useState(".");
+ const [scanning, setScanning] = useState(false);
+ const [result, setResult] = useState(null);
+ const [error, setError] = useState(null);
+
+ const handleScan = async () => {
+ setScanning(true);
+ setError(null);
+ setResult(null);
+ try {
+ const data = await scanWorkspace(path.trim() || ".");
+ setResult(data);
+ const findingsCount = data.findings?.length || 0;
+ showToast?.(
+ "Scan complete",
+ findingsCount === 0
+ ? "No security findings."
+ : `Found ${findingsCount} issue${findingsCount !== 1 ? "s" : ""}.`
+ );
+ } catch (err) {
+ setError(err?.message || "Scan failed");
+ } finally {
+ setScanning(false);
+ }
+ };
+
+ // Group findings by severity
+ const grouped = React.useMemo(() => {
+ const out = {};
+ if (result?.findings) {
+ for (const f of result.findings) {
+ const sev = f.severity || "info";
+ if (!out[sev]) out[sev] = [];
+ out[sev].push(f);
+ }
+ }
+ return out;
+ }, [result]);
+
+ const totalFindings = result?.findings?.length || 0;
+
+ return (
+
+
Security Scanning
+
+ Scan your workspace for vulnerabilities, secrets, and insecure patterns (OWASP Top 10).
+
+
+ {/* Scan controls */}
+
+
+
+ Path to scan (relative or absolute)
+
+ setPath(e.target.value)}
+ disabled={scanning}
+ placeholder="."
+ style={{
+ width: "100%",
+ padding: "8px 10px",
+ background: "#0d0e15",
+ border: "1px solid #2a2b36",
+ borderRadius: "4px",
+ color: "#fff",
+ fontSize: "12px",
+ fontFamily: "monospace",
+ }}
+ />
+
+
+ {scanning ? "Scanning..." : "Scan Workspace"}
+
+
+
+ {/* Error state */}
+ {error && (
+
+ Scan failed:
+ {error}
+
+ )}
+
+ {/* Results summary */}
+ {result && (
+
+
+
+
Files Scanned
+
+ {result.files_scanned ?? 0}
+
+
+
+
Total Findings
+
+ {totalFindings}
+
+
+
+
Duration
+
+ {result.scan_duration_ms ?? 0}ms
+
+
+
+
+ )}
+
+ {/* Empty state — no findings */}
+ {result && totalFindings === 0 && (
+
+
✓
+
+ No security issues found
+
+
+ Your workspace passed all {result.files_scanned ?? 0} file checks.
+
+
+ )}
+
+ {/* Findings grouped by severity */}
+ {totalFindings > 0 &&
+ SEVERITY_ORDER.filter((sev) => grouped[sev]?.length > 0).map((sev) => (
+
+
+
+
+ {grouped[sev].length} {sev} issue{grouped[sev].length !== 1 ? "s" : ""}
+
+
+
+ {grouped[sev].map((f, idx) => (
+
+
+
{f.title}
+ {f.cwe_id && (
+
+ {f.cwe_id}
+
+ )}
+
+
+ {f.file_path}:{f.line_number}
+
+ {f.snippet && (
+
+ {f.snippet}
+
+ )}
+ {f.recommendation && (
+
+ Fix:
+ {f.recommendation}
+
+ )}
+
+ ))}
+
+
+ ))}
+
+ );
+}
diff --git a/frontend/components/AdminTabs/SessionsTab.jsx b/frontend/components/AdminTabs/SessionsTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..f55e9ef70ededefa2e89b63a7b9fff01ca00c5f6
--- /dev/null
+++ b/frontend/components/AdminTabs/SessionsTab.jsx
@@ -0,0 +1,362 @@
+// frontend/components/AdminTabs/SessionsTab.jsx
+import React, { useEffect, useMemo, useState, useCallback } from "react";
+import { apiUrl, safeFetchJSON } from "../../utils/api.js";
+
+/**
+ * Sessions tab — admin-level table view of all saved sessions with
+ * search, sort, and delete actions.
+ *
+ * Best practices applied:
+ * - Fetch all sessions on mount
+ * - Client-side search (useMemo for filtered list)
+ * - Confirmation dialog before delete
+ * - Row hover effect
+ * - Empty / loading / error states
+ * - Relative timestamps ("2 hours ago")
+ * - Click row to open in workspace view
+ */
+
+function formatRelativeTime(iso) {
+ if (!iso) return "—";
+ try {
+ const d = new Date(iso);
+ const diff = Date.now() - d.getTime();
+ if (diff < 60_000) return "just now";
+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
+ if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
+ if (diff < 2_592_000_000) return `${Math.floor(diff / 86_400_000)}d ago`;
+ return d.toLocaleDateString();
+ } catch {
+ return "—";
+ }
+}
+
+export default function SessionsTab({ onSelectSession, showToast }) {
+ const [sessions, setSessions] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [query, setQuery] = useState("");
+ const [deletingId, setDeletingId] = useState(null);
+
+ const fetchSessions = useCallback(async () => {
+ setError(null);
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/sessions"), { timeout: 10000 });
+ setSessions(Array.isArray(data.sessions) ? data.sessions : []);
+ } catch (err) {
+ setError(err?.message || "Failed to load sessions");
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ fetchSessions();
+ }, [fetchSessions]);
+
+ const handleDelete = async (session) => {
+ if (
+ !window.confirm(
+ `Delete session "${session.name || session.id?.slice(0, 8)}"? This cannot be undone.`
+ )
+ ) {
+ return;
+ }
+
+ setDeletingId(session.id);
+ try {
+ const res = await fetch(apiUrl(`/api/sessions/${session.id}`), {
+ method: "DELETE",
+ });
+ if (!res.ok) {
+ throw new Error(`Delete failed (${res.status})`);
+ }
+ showToast?.("Session deleted", session.name || session.id);
+ // Optimistic removal
+ setSessions((prev) => prev.filter((s) => s.id !== session.id));
+ } catch (err) {
+ setError(err?.message || "Failed to delete session");
+ } finally {
+ setDeletingId(null);
+ }
+ };
+
+ const filtered = useMemo(() => {
+ if (!query.trim()) return sessions;
+ const q = query.toLowerCase();
+ return sessions.filter((s) => {
+ return (
+ (s.name || "").toLowerCase().includes(q) ||
+ (s.repo || "").toLowerCase().includes(q) ||
+ (s.branch || "").toLowerCase().includes(q) ||
+ (s.id || "").toLowerCase().includes(q)
+ );
+ });
+ }, [sessions, query]);
+
+ return (
+
+
+
+
Sessions
+
+ All saved chat sessions ({sessions.length} total
+ {query ? `, ${filtered.length} matching` : ""}).
+
+
+
+ setQuery(e.target.value)}
+ placeholder="Search sessions..."
+ style={{
+ padding: "6px 10px",
+ background: "#0d0e15",
+ border: "1px solid #2a2b36",
+ borderRadius: "4px",
+ color: "#fff",
+ fontSize: "12px",
+ width: "220px",
+ }}
+ />
+
+ Refresh
+
+
+
+
+ {/* Loading state */}
+ {loading && (
+
+ Loading sessions...
+
+ )}
+
+ {/* Error state */}
+ {error && !loading && (
+
+ Error:
+ {error}
+
+ )}
+
+ {/* Empty state */}
+ {!loading && !error && sessions.length === 0 && (
+
+
💬
+
+ No sessions yet
+
+
+ Start chatting with GitPilot to create your first session.
+
+
+ )}
+
+ {/* Table */}
+ {!loading && filtered.length > 0 && (
+
+
+
+
+ Name
+ Repository
+ Branch
+ Messages
+ Status
+ Updated
+ Actions
+
+
+
+ {filtered.map((s) => (
+
+ (e.currentTarget.style.background = "#22232e")
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.background = "transparent")
+ }
+ onClick={() => onSelectSession?.(s)}
+ >
+
+
+ {s.name || (unnamed) }
+
+
+ {s.id?.slice(0, 12)}
+
+
+
+ {s.repo || — }
+
+
+ {s.branch || — }
+
+ {s.message_count ?? 0}
+
+
+ {s.status || "unknown"}
+
+
+
+ {formatRelativeTime(s.updated_at)}
+
+
+ {
+ e.stopPropagation();
+ handleDelete(s);
+ }}
+ disabled={deletingId === s.id}
+ style={{
+ padding: "4px 10px",
+ background: "transparent",
+ color: "#f87171",
+ border: "1px solid #991b1b",
+ borderRadius: "4px",
+ cursor: deletingId === s.id ? "not-allowed" : "pointer",
+ fontSize: "11px",
+ }}
+ >
+ {deletingId === s.id ? "..." : "Delete"}
+
+
+
+ ))}
+
+
+
+ )}
+
+ {/* No matches for search */}
+ {!loading && sessions.length > 0 && filtered.length === 0 && (
+
+ No sessions match "{query}"
+
+ )}
+
+ );
+}
+
+const thStyle = {
+ padding: "10px 12px",
+ textAlign: "left",
+ fontSize: "11px",
+ fontWeight: 600,
+ textTransform: "uppercase",
+ letterSpacing: "0.5px",
+ opacity: 0.7,
+};
+
+const tdStyle = {
+ padding: "10px 12px",
+ verticalAlign: "middle",
+};
diff --git a/frontend/components/AdminTabs/SkillsTab.jsx b/frontend/components/AdminTabs/SkillsTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..6068f4af61f6d2933f546997260ecc97a65823f3
--- /dev/null
+++ b/frontend/components/AdminTabs/SkillsTab.jsx
@@ -0,0 +1,266 @@
+// frontend/components/AdminTabs/SkillsTab.jsx
+import React, { useEffect, useState, useCallback } from "react";
+import { apiUrl, safeFetchJSON } from "../../utils/api.js";
+
+/**
+ * Skills tab — lists all loaded skills from /api/skills and allows
+ * reloading them from disk via /api/skills/reload.
+ *
+ * Best practices applied:
+ * - Fetch on mount
+ * - Explicit reload button (skills are loaded from .md files on disk)
+ * - Loading / empty / error states
+ * - Auto-trigger indicator badge
+ * - Required tools list per skill
+ * - Source file path for debugging
+ */
+
+export default function SkillsTab({ showToast }) {
+ const [skills, setSkills] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [reloading, setReloading] = useState(false);
+ const [error, setError] = useState(null);
+
+ const fetchSkills = useCallback(async () => {
+ setError(null);
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/skills"), { timeout: 10000 });
+ setSkills(Array.isArray(data.skills) ? data.skills : []);
+ } catch (err) {
+ setError(err?.message || "Failed to load skills");
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ fetchSkills();
+ }, [fetchSkills]);
+
+ const handleReload = async () => {
+ setReloading(true);
+ setError(null);
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/skills/reload"), {
+ method: "POST",
+ timeout: 10000,
+ });
+ showToast?.(
+ "Skills reloaded",
+ `${data.count ?? 0} skill${data.count !== 1 ? "s" : ""} loaded from disk.`
+ );
+ await fetchSkills();
+ } catch (err) {
+ setError(err?.message || "Failed to reload skills");
+ } finally {
+ setReloading(false);
+ }
+ };
+
+ return (
+
+
+
+
Skills
+
+ Reusable prompt templates loaded from{" "}
+ .gitpilot/skills/*.md files.
+
+
+
+ {reloading ? "Reloading..." : "Reload Skills"}
+
+
+
+ {/* Loading state */}
+ {loading && (
+
+ Loading skills...
+
+ )}
+
+ {/* Error state */}
+ {error && !loading && (
+
+ Error:
+ {error}
+
+ )}
+
+ {/* Empty state */}
+ {!loading && !error && skills.length === 0 && (
+
+
📚
+
+ No skills loaded
+
+
+ Create a .gitpilot/skills/my-skill.md file with YAML
+ frontmatter to add custom skills.
+
+
+ )}
+
+ {/* Skills grid */}
+ {!loading && skills.length > 0 && (
+
+ {skills.map((skill) => (
+
+
+
+ {skill.name}
+
+ {skill.auto_trigger && (
+
+ Auto
+
+ )}
+
+
+
+ {skill.description || "No description"}
+
+
+ {Array.isArray(skill.required_tools) && skill.required_tools.length > 0 && (
+
+ {skill.required_tools.map((t) => (
+
+ {t}
+
+ ))}
+
+ )}
+
+ {skill.source && (
+
+ {skill.source}
+
+ )}
+
+ ))}
+
+ )}
+
+ );
+}
diff --git a/frontend/components/AdminTabs/WorkspaceModesTab.jsx b/frontend/components/AdminTabs/WorkspaceModesTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..124373c175c7c6543493487627d48467405b4252
--- /dev/null
+++ b/frontend/components/AdminTabs/WorkspaceModesTab.jsx
@@ -0,0 +1,254 @@
+// frontend/components/AdminTabs/WorkspaceModesTab.jsx
+import React, { useState } from "react";
+import { startSession } from "../../utils/api.js";
+
+/**
+ * Workspace Modes tab — allows the user to start a session in one of
+ * three modes (folder, local_git, github). Calls POST /api/session/start.
+ *
+ * Best practices applied:
+ * - Loading state while the request is in flight
+ * - Per-mode error state (not a global error)
+ * - Disabled card during submission to prevent double-click
+ * - ARIA role="button" + aria-disabled for accessibility
+ * - Toast notification on success
+ * - Success callback so App.jsx can set activeSessionId and switch to workspace view
+ */
+
+const MODES = [
+ {
+ id: "folder",
+ title: "Folder Mode",
+ description: "Work with any local folder. No Git required.",
+ requires: "A local folder path",
+ enables: "Chat, explain, review",
+ promptKey: "folder_path",
+ promptLabel: "Folder path (absolute)",
+ promptPlaceholder: "/home/you/myproject",
+ buildPayload: (value) => ({ mode: "folder", folder_path: value }),
+ },
+ {
+ id: "local_git",
+ title: "Local Git Mode",
+ description: "Full repo + branch context for AI assistance.",
+ requires: "A local Git repository",
+ enables: "All local features (branches, diff, commit)",
+ promptKey: "repo_root",
+ promptLabel: "Repository root (absolute path)",
+ promptPlaceholder: "/home/you/my-git-repo",
+ buildPayload: (value) => ({ mode: "local_git", repo_root: value }),
+ },
+ {
+ id: "github",
+ title: "GitHub Mode",
+ description: "PRs, issues, remote workflows via GitHub API.",
+ requires: "GitHub token (already signed in)",
+ enables: "Full platform features",
+ promptKey: "repo_full_name",
+ promptLabel: "Repository (owner/repo)",
+ promptPlaceholder: "octocat/hello-world",
+ buildPayload: (value) => ({ mode: "github", repo_full_name: value }),
+ },
+];
+
+export default function WorkspaceModesTab({ onSessionStarted, showToast }) {
+ const [activeModeId, setActiveModeId] = useState(null);
+ const [inputValue, setInputValue] = useState("");
+ const [submittingId, setSubmittingId] = useState(null);
+ const [errorByMode, setErrorByMode] = useState({});
+
+ const handleCardClick = (mode) => {
+ if (submittingId) return;
+ setActiveModeId(mode.id);
+ setInputValue("");
+ setErrorByMode((prev) => ({ ...prev, [mode.id]: null }));
+ };
+
+ const handleStart = async (mode) => {
+ const trimmed = inputValue.trim();
+ if (!trimmed) {
+ setErrorByMode((prev) => ({
+ ...prev,
+ [mode.id]: `${mode.promptLabel} is required`,
+ }));
+ return;
+ }
+
+ setSubmittingId(mode.id);
+ setErrorByMode((prev) => ({ ...prev, [mode.id]: null }));
+
+ try {
+ const payload = mode.buildPayload(trimmed);
+ const result = await startSession(payload);
+
+ showToast?.(
+ `${mode.title} started`,
+ `Session ${result.session_id?.slice(0, 8) || ""} is now active.`
+ );
+
+ onSessionStarted?.(result);
+ setActiveModeId(null);
+ setInputValue("");
+ } catch (err) {
+ setErrorByMode((prev) => ({
+ ...prev,
+ [mode.id]: err?.message || "Failed to start session",
+ }));
+ } finally {
+ setSubmittingId(null);
+ }
+ };
+
+ const handleCancel = () => {
+ if (submittingId) return;
+ setActiveModeId(null);
+ setInputValue("");
+ };
+
+ return (
+
+
Workspace Modes
+
+ Choose how you want GitPilot to interact with your code. You can switch modes at any time.
+
+
+
+ {MODES.map((mode) => {
+ const isActive = activeModeId === mode.id;
+ const isSubmitting = submittingId === mode.id;
+ const error = errorByMode[mode.id];
+
+ return (
+
!isActive && handleCardClick(mode)}
+ onKeyDown={(e) => {
+ if ((e.key === "Enter" || e.key === " ") && !isActive) {
+ e.preventDefault();
+ handleCardClick(mode);
+ }
+ }}
+ style={{
+ background: isActive ? "#1e3a5f" : "#1a1b26",
+ borderRadius: "8px",
+ padding: "20px",
+ border: isActive ? "1px solid #3B82F6" : "1px solid #2a2b36",
+ cursor: submittingId && !isSubmitting ? "not-allowed" : "pointer",
+ opacity: submittingId && !isSubmitting ? 0.5 : 1,
+ transition: "all 150ms ease",
+ }}
+ >
+
+ {mode.title}
+
+
+ {mode.description}
+
+
+ Requires:
+ {mode.requires}
+
+
+ Enables:
+ {mode.enables}
+
+
+ {isActive && (
+
e.stopPropagation()} style={{ marginTop: "12px" }}>
+
+ {mode.promptLabel}
+
+
setInputValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleStart(mode);
+ } else if (e.key === "Escape") {
+ handleCancel();
+ }
+ }}
+ placeholder={mode.promptPlaceholder}
+ disabled={isSubmitting}
+ autoFocus
+ style={{
+ width: "100%",
+ padding: "6px 8px",
+ background: "#0d0e15",
+ border: "1px solid #2a2b36",
+ borderRadius: "4px",
+ color: "#fff",
+ fontSize: "12px",
+ fontFamily: "monospace",
+ }}
+ />
+ {error && (
+
+ {error}
+
+ )}
+
+ handleStart(mode)}
+ disabled={isSubmitting || !inputValue.trim()}
+ style={{
+ padding: "6px 12px",
+ background: isSubmitting ? "#555" : "#3B82F6",
+ color: "#fff",
+ border: "none",
+ borderRadius: "4px",
+ cursor: isSubmitting || !inputValue.trim() ? "not-allowed" : "pointer",
+ fontSize: "12px",
+ fontWeight: 600,
+ }}
+ >
+ {isSubmitting ? "Starting..." : "Start Session"}
+
+
+ Cancel
+
+
+
+ )}
+
+ );
+ })}
+
+
+ );
+}
diff --git a/frontend/components/AdminTabs/index.js b/frontend/components/AdminTabs/index.js
new file mode 100644
index 0000000000000000000000000000000000000000..4775db11f65326388bee0c228ccf3363138625ac
--- /dev/null
+++ b/frontend/components/AdminTabs/index.js
@@ -0,0 +1,10 @@
+// frontend/components/AdminTabs/index.js
+// Barrel export — all admin tab components in one place
+export { default as WorkspaceModesTab } from "./WorkspaceModesTab.jsx";
+export { default as SecurityTab } from "./SecurityTab.jsx";
+export { default as IntegrationsTab } from "./IntegrationsTab.jsx";
+export { default as MCPServersTab } from "./MCPServersTab.jsx";
+export { default as SkillsTab } from "./SkillsTab.jsx";
+export { default as SessionsTab } from "./SessionsTab.jsx";
+export { default as AdvancedTab } from "./AdvancedTab.jsx";
+export { default as SandboxTab } from "./SandboxTab.jsx";
diff --git a/frontend/components/AdminTabs/mcp/CatalogList.jsx b/frontend/components/AdminTabs/mcp/CatalogList.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..e1bf6c5930e5102fb65b7eec34a6537d1b22bb43
--- /dev/null
+++ b/frontend/components/AdminTabs/mcp/CatalogList.jsx
@@ -0,0 +1,101 @@
+// frontend/components/AdminTabs/mcp/CatalogList.jsx
+// Browse curated MCP servers shipped with GitPilot. Each item has a
+// one-click "Install" that lands the server in the Installed tab,
+// disabled by default.
+
+import React from "react";
+
+export default function CatalogList({ items, onInstall }) {
+ if (!items?.length) {
+ return (
+
+ No catalog entries shipped with this build.
+
+ );
+ }
+
+ return (
+
+ {items.map((item) => (
+
+
+
+
+ {item.id}
+
+ {item.installed && (
+
+ installed
+
+ )}
+
+
+ {item.description}
+
+
+ {(item.tags || []).map((t) => (
+
+ {t}
+
+ ))}
+
+
+
onInstall(item.id)}
+ disabled={item.installed}
+ style={{
+ padding: "6px 14px",
+ background: item.installed ? "#252634" : "#3B82F6",
+ color: item.installed ? "#7a7d8a" : "#fff",
+ border: "none",
+ borderRadius: "4px",
+ cursor: item.installed ? "not-allowed" : "pointer",
+ fontSize: "12px",
+ fontWeight: 600,
+ }}
+ >
+ {item.installed ? "Installed" : "Install"}
+
+
+ ))}
+
+ );
+}
diff --git a/frontend/components/AdminTabs/mcp/CustomInstallForm.jsx b/frontend/components/AdminTabs/mcp/CustomInstallForm.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..cef9a3fab26f9bb09fcc5ed92ed357c015d7a2ee
--- /dev/null
+++ b/frontend/components/AdminTabs/mcp/CustomInstallForm.jsx
@@ -0,0 +1,134 @@
+// frontend/components/AdminTabs/mcp/CustomInstallForm.jsx
+// Paste-a-register.json form for installing a custom MCP server.
+
+import React, { useState } from "react";
+
+const SAMPLE = `{
+ "name": "mcp-neo4j-server",
+ "endpoint": "http://mcp-neo4j-server:8083/mcp",
+ "description": "Neo4j MCP server for graph schema discovery",
+ "tags": ["graph", "neo4j"],
+ "auth": { "type": "bearer", "env": "MCP_NEO4J_SERVER_TOKEN" }
+}`;
+
+export default function CustomInstallForm({ onSubmit }) {
+ const [text, setText] = useState(SAMPLE);
+ const [err, setErr] = useState(null);
+ const [submitting, setSubmitting] = useState(false);
+
+ const handleSubmit = async () => {
+ setErr(null);
+ let parsed;
+ try {
+ parsed = JSON.parse(text);
+ } catch (e) {
+ setErr("Invalid JSON: " + (e?.message || ""));
+ return;
+ }
+ if (!parsed.name || !parsed.endpoint) {
+ setErr("register.json must include 'name' and 'endpoint'.");
+ return;
+ }
+ setSubmitting(true);
+ try {
+ await onSubmit(parsed);
+ setText(SAMPLE);
+ } catch (e) {
+ setErr(e?.message || "Install failed");
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+
+
Install custom server
+
+ Paste a Context Forge register.json. The server lands
+ disabled — turn it on from the Installed tab once you have set its
+ auth token.
+
+
+ );
+}
diff --git a/frontend/components/AdminTabs/mcp/GatewayHeader.jsx b/frontend/components/AdminTabs/mcp/GatewayHeader.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..902dcfe4c2a7084a83f644d1b9045ae542e3cd9f
--- /dev/null
+++ b/frontend/components/AdminTabs/mcp/GatewayHeader.jsx
@@ -0,0 +1,145 @@
+// frontend/components/AdminTabs/mcp/GatewayHeader.jsx
+// Top strip of the MCP Servers tab: gateway pill + roll-up counters.
+
+import React from "react";
+
+export default function GatewayHeader({
+ status,
+ installedCount,
+ enabledCount,
+ totalTools,
+ onRefresh,
+ onSync,
+ syncing,
+}) {
+ const reachable = status?.gateway_reachable;
+ const dotColor = reachable ? "#10b981" : "#ef4444";
+ const dotLabel = reachable ? "Connected" : "Unreachable";
+ const gatewayUrl = status?.gateway_url || "—";
+
+ return (
+
+
+
+
+
+ MCP Context Forge — {dotLabel}
+
+ {status?.plugin_enabled === false && (
+
+ plugin disabled
+
+ )}
+
+
+ Gateway: {gatewayUrl}
+
+
+
+
+
+
+
+
+ Refresh
+
+ {onSync && (
+
+ {syncing ? "Syncing…" : "Sync"}
+
+ )}
+
+
+ );
+}
+
+function Counter({ label, value }) {
+ return (
+
+
+ {value ?? "—"}
+
+
+ {label}
+
+
+ );
+}
diff --git a/frontend/components/AdminTabs/mcp/ServerCard.jsx b/frontend/components/AdminTabs/mcp/ServerCard.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..6384105dad800883f23f9e843e9f13a35e289343
--- /dev/null
+++ b/frontend/components/AdminTabs/mcp/ServerCard.jsx
@@ -0,0 +1,334 @@
+// frontend/components/AdminTabs/mcp/ServerCard.jsx
+// One installed MCP server. Collapsed shows summary + actions; expanded
+// reveals the per-tool list with risk badges and individual toggles.
+
+import React, { useState } from "react";
+import ToolRow from "./ToolRow.jsx";
+
+const RISK_PALETTE = {
+ low: { bg: "#0f3a26", border: "#1f5a3e", text: "#86efac" },
+ medium: { bg: "#3a2e0f", border: "#5a4a1f", text: "#fcd34d" },
+ high: { bg: "#3a0f0f", border: "#5a1f1f", text: "#fca5a5" },
+};
+
+export default function ServerCard({
+ server,
+ onEnable,
+ onDisable,
+ onUninstall,
+ onTest,
+ onToggleTool,
+ onForget,
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const [testResult, setTestResult] = useState(null);
+ const [testing, setTesting] = useState(false);
+
+ const handleTest = async () => {
+ setTesting(true);
+ try {
+ const result = await onTest();
+ setTestResult(result);
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const statusDot = server.enabled ? "#10b981" : "#6b7280";
+ const statusLabel = server.enabled ? "Enabled" : "Disabled";
+
+ // Risk roll-up shown next to the tool count.
+ const riskCounts = server.tools?.reduce(
+ (acc, t) => ({ ...acc, [t.risk]: (acc[t.risk] || 0) + 1 }),
+ {}
+ ) || {};
+
+ return (
+
+
+
+
+
+
+
+ {server.id}
+
+
+ {statusLabel}
+
+ {!server.is_known && (
+
+ custom
+
+ )}
+ {server.orphan && (
+
+ orphan
+
+ )}
+ {server.source === "forge-sync" && !server.orphan && (
+
+ via sync
+
+ )}
+
+
+ {server.description || "—"}
+
+
+ {server.endpoint || "—"}
+
+
+ {(server.tags || []).map((t) => (
+
+ {t}
+
+ ))}
+
+
+
+
+
+ {server.enabled ? (
+
+ Disable
+
+ ) : (
+
+ Enable
+
+ )}
+
+ {testing ? "Testing…" : "Test"}
+
+ {onForget ? (
+
+ Forget
+
+ ) : (
+
+ Uninstall
+
+ )}
+
+
+ {server.tool_count} tool{server.tool_count === 1 ? "" : "s"}
+ {Object.entries(riskCounts).map(([risk, count]) => (
+
+ {count} {risk}
+
+ ))}
+
+
setExpanded((v) => !v)}
+ style={{
+ padding: "4px 8px",
+ background: "transparent",
+ color: "#93c5fd",
+ border: "none",
+ cursor: "pointer",
+ fontSize: "12px",
+ }}
+ >
+ {expanded ? "Hide tools ▴" : "Show tools ▾"}
+
+
+
+
+ {testResult && (
+
+ {testResult.ok
+ ? "Healthy. Inspector confirmed the server is reachable and advertises its expected tools."
+ : `Failed: ${testResult.reason || testResult.error || "unknown error"}`}
+
+ )}
+
+
+ {expanded && (
+
+ {server.tools?.length ? (
+ server.tools.map((t) => (
+
onToggleTool(t.name, enabled)}
+ />
+ ))
+ ) : (
+
+ No tools advertised by this server.
+
+ )}
+
+ )}
+
+ );
+}
+
+function Btn({ children, variant = "default", ...props }) {
+ const palettes = {
+ default: { bg: "#252634", color: "#e0e0e7", border: "#3a3b4a" },
+ primary: { bg: "#3B82F6", color: "#fff", border: "#3B82F6" },
+ ghost: { bg: "transparent", color: "#cdd0d8", border: "#3a3b4a" },
+ danger: { bg: "transparent", color: "#fca5a5", border: "#5a1f1f" },
+ };
+ const p = palettes[variant];
+ return (
+
+ {children}
+
+ );
+}
diff --git a/frontend/components/AdminTabs/mcp/SyncReport.jsx b/frontend/components/AdminTabs/mcp/SyncReport.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..25f72e8c268a3cb51c769e0dc289516fd71b7e31
--- /dev/null
+++ b/frontend/components/AdminTabs/mcp/SyncReport.jsx
@@ -0,0 +1,152 @@
+// frontend/components/AdminTabs/mcp/SyncReport.jsx
+// Renders the SyncReport returned by POST /api/mcp/sync as a compact
+// dismissible banner. Best practices: structured + colour-coded counts,
+// truncated id lists with a "View" toggle, single primary "Dismiss"
+// action, ARIA "status" so a screen reader announces the result once.
+
+import React, { useState } from "react";
+
+export default function SyncReport({ report, onDismiss }) {
+ const [open, setOpen] = useState(false);
+ if (!report) return null;
+
+ const { added = [], kept = [], orphaned = [], forge_unreachable, error } = report;
+
+ if (forge_unreachable) {
+ return (
+
+ );
+ }
+
+ const noChanges = added.length === 0 && orphaned.length === 0;
+
+ return (
+ setOpen((v) => !v)}
+ style={{
+ background: "transparent",
+ border: "none",
+ color: "#93c5fd",
+ cursor: "pointer",
+ fontSize: 12,
+ padding: 0,
+ }}
+ >
+ {open ? "Hide details ▴" : "View details ▾"}
+
+ }
+ >
+ {open && (
+
+ {added.length > 0 && (
+
+ )}
+ {kept.length > 0 && (
+
+ )}
+ {orphaned.length > 0 && (
+
+ )}
+ {report.correlation_id && (
+
+ correlation_id: {report.correlation_id}
+
+ )}
+
+ )}
+
+ );
+}
+
+function Banner({ kind, title, body, footer, onDismiss, children }) {
+ const palette = {
+ ok: { bg: "#0f3a26", border: "#1f5a3e", text: "#86efac" },
+ info: { bg: "#1e3a5f", border: "#3B82F6", text: "#93c5fd" },
+ warn: { bg: "#3a2e0f", border: "#5a4a1f", text: "#fcd34d" },
+ bad: { bg: "#3a0f0f", border: "#5a1f1f", text: "#fca5a5" },
+ }[kind] || { bg: "#1a1b26", border: "#2a2b36", text: "#cdd0d8" };
+
+ return (
+
+
+ {title}
+
+ ×
+
+
+ {body &&
{body}
}
+ {children}
+ {footer &&
{footer}
}
+
+ );
+}
+
+function Detail({ label, items, colour, hint }) {
+ return (
+
+
{label}: {" "}
+
+ {items.slice(0, 6).join(", ")}
+ {items.length > 6 ? ` … (+${items.length - 6} more)` : ""}
+
+ {hint && (
+
{hint}
+ )}
+
+ );
+}
diff --git a/frontend/components/AdminTabs/mcp/ToolRow.jsx b/frontend/components/AdminTabs/mcp/ToolRow.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..82b020416391154cab3e2e73e4b04d105fbf4b0b
--- /dev/null
+++ b/frontend/components/AdminTabs/mcp/ToolRow.jsx
@@ -0,0 +1,149 @@
+// frontend/components/AdminTabs/mcp/ToolRow.jsx
+// One row inside an expanded ServerCard. Tool name, risk badge,
+// "used by" agent chips, and a per-tool enable toggle.
+
+import React from "react";
+
+const RISK_PALETTE = {
+ low: { bg: "#0f3a26", text: "#86efac", label: "low" },
+ medium: { bg: "#3a2e0f", text: "#fcd34d", label: "med" },
+ high: { bg: "#3a0f0f", text: "#fca5a5", label: "high" },
+};
+
+export default function ToolRow({ tool, disabled, onToggle }) {
+ const risk = RISK_PALETTE[tool.risk] || RISK_PALETTE.low;
+
+ // Destructive tools cannot be toggled on by the UI; the backend's
+ // PolicyEngine will reject a toggle PUT anyway, but disabling the
+ // control surfaces the constraint up front.
+ const lockEnable = tool.destructive;
+
+ return (
+
+
+
+
+ {tool.name}
+
+
+ {risk.label}
+
+
+
+ {(tool.used_by || []).length > 0 && used by }
+ {(tool.used_by || []).map((agent) => (
+
+ {agent}
+
+ ))}
+
+
+
+
onToggle(checked)}
+ />
+
+ );
+}
+
+function Toggle({ checked, disabled, title, onChange }) {
+ return (
+
+ onChange(e.target.checked)}
+ style={{ position: "absolute", opacity: 0, pointerEvents: "none" }}
+ aria-label={title}
+ />
+
+
+
+
+ );
+}
diff --git a/frontend/components/AssistantMessage.jsx b/frontend/components/AssistantMessage.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..9a1996571358f2942269c37c03dae7af31ab3b92
--- /dev/null
+++ b/frontend/components/AssistantMessage.jsx
@@ -0,0 +1,429 @@
+import React, { useState } from "react";
+import PlanView from "./PlanView.jsx";
+import RunnableCodeBlock, { splitFences } from "./RunnableCodeBlock.jsx";
+import ExecutionPlanCard from "./ExecutionPlanCard.jsx";
+
+export default function AssistantMessage({
+ answer,
+ plan,
+ executionLog,
+ planStatus,
+ owner,
+ repo,
+ onApproveExecution,
+ nextActions,
+ relatedPlan,
+ diff,
+ branch,
+}) {
+ // Approval-first sandbox: when the planner returns an execution_plan,
+ // render the green ExecutionPlanCard instead of the orange Action Plan.
+ const executionPlan = plan?.execution_plan || null;
+ const [runResult, setRunResult] = useState(null);
+ const [runError, setRunError] = useState(null);
+ const [runBusy, setRunBusy] = useState(false);
+
+ const approveExecution = async (ep) => {
+ if (onApproveExecution) {
+ onApproveExecution(ep, plan);
+ return;
+ }
+ setRunBusy(true);
+ setRunError(null);
+ setRunResult(null);
+ try {
+ const body = ep.file
+ ? { language: ep.language, code: null }
+ : { language: ep.language, code: ep.inline_code, timeout_sec: ep.timeout_sec };
+ const res = await fetch("/api/sandbox/run", {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json();
+ if (!res.ok) setRunError(data.detail || `HTTP ${res.status}`);
+ else setRunResult(data);
+ } catch (e) { setRunError(e.message); }
+ finally { setRunBusy(false); }
+ };
+
+ const hasFileActions = plan?.steps?.some((s) => s.files?.length > 0);
+ const answerText = typeof answer === "string" ? answer.trim() : "";
+ // Suppress the answer prose when it would just duplicate what the
+ // plan card or success receipt already says.
+ const showAnswerProse =
+ answerText &&
+ !executionLog &&
+ !(plan && hasFileActions && !executionPlan && answerText === plan.summary);
+
+ return (
+
+ {/* Free-form answer prose. Rendered without a section header so
+ short answers feel like a chat reply, not a debug log. */}
+ {showAnswerProse && (
+
+ {splitFences(answerText).map((seg, i) =>
+ seg.type === "code" ? (
+
+ ) : (
+
+ {seg.value}
+
+ ),
+ )}
+
+ )}
+
+ {/* Sandbox approval card. */}
+ {executionPlan && (
+
+
{ /* no-op */ }}
+ />
+ {runError && (
+ Run error: {runError}
+ )}
+ {runResult && (
+
+ {runResult.stdout || runResult.stderr || "(no output)"}
+
+ )}
+
+ )}
+
+ {/* Proposed execution plan — only when there are file changes
+ and no execution log is present yet. */}
+ {plan && hasFileActions && !executionPlan && !executionLog && (
+
+ )}
+
+ {/* Completed execution receipt. */}
+ {executionLog && (
+
+ )}
+
+ {/* Next actions when there is no execution log (e.g. simple answers). */}
+ {!executionLog && Array.isArray(nextActions) && nextActions.length > 0 && (
+
+ {nextActions.map((a, i) => (
+
+ ))}
+
+ )}
+
+ );
+}
+
+function NextActionButton({ action }) {
+ const onClick = () => {
+ if (action.kind === "run_file" && action.payload?.file) {
+ window.dispatchEvent(
+ new CustomEvent("gitpilot:run-file", {
+ detail: { path: action.payload.file },
+ }),
+ );
+ } else if (action.kind === "open_workspace" && action.payload?.file) {
+ window.dispatchEvent(
+ new CustomEvent("gitpilot:open-workspace", {
+ detail: { path: action.payload.file },
+ }),
+ );
+ } else if (action.kind === "open_in_canvas" && action.payload?.file) {
+ window.dispatchEvent(
+ new CustomEvent("gitpilot:open-in-canvas", {
+ detail: { path: action.payload.file },
+ }),
+ );
+ }
+ };
+
+ const isPrimary = action.kind === "run_file";
+ return (
+
+
+ {action.kind === "run_file"
+ ? "▶"
+ : action.kind === "open_workspace"
+ ? "📂"
+ : "⊞"}
+
+ {action.label}
+
+ );
+}
+
+function SuccessReceipt({
+ executionLog,
+ relatedPlan,
+ owner,
+ repo,
+ branch,
+ diff,
+ nextActions,
+}) {
+ const steps = executionLog?.steps || [];
+ const totalSteps = steps.length;
+
+ // Aggregate every file action across steps so "Files changed (N)" can
+ // be a single top-level section instead of per-step duplication.
+ const allFiles = [];
+ if (relatedPlan?.steps?.length) {
+ for (const s of relatedPlan.steps) {
+ for (const f of s.files || []) {
+ if (f.action !== "INDEX") allFiles.push(f);
+ }
+ }
+ }
+ const totalDuration = steps.reduce((acc, s) => {
+ return acc + (s.executions || []).reduce(
+ (a, ex) => a + (typeof ex.duration_ms === "number" ? ex.duration_ms : 0),
+ 0,
+ );
+ }, 0);
+
+ // Short headline outcome lines (max 2): "Created X", "Modified Y".
+ const headlines = [];
+ for (const action of ["CREATE", "MODIFY", "DELETE"]) {
+ for (const f of allFiles) {
+ if (f.action === action && headlines.length < 2) {
+ headlines.push({ verb: verbFor(action), path: f.path });
+ }
+ }
+ }
+
+ // The bottom-bar already owns Create PR. Only show a pointer text here
+ // when there is a meaningful PR path (branch + file changes).
+ const hasPRPath = Boolean(branch && allFiles.length > 0);
+
+ // Filter out create-PR-style next-actions (handled by bottom bar);
+ // keep ▶ run / 📂 open as inline buttons.
+ const inlineNextActions = (nextActions || []).filter(
+ (a) => a && a.kind && a.kind !== "create_pr",
+ );
+
+ const hasTechLog =
+ totalDuration > 0 ||
+ steps.some((s) => s.summary || (s.executions || []).length > 0);
+
+ return (
+
+
+
+
+
Execution completed
+
+ Successfully executed {totalSteps} step{totalSteps === 1 ? "" : "s"}
+ ·
+ Just now
+
+
+
+
+
+
+ Executed
+
+
+
+ {headlines.length > 0 && (
+
+ {headlines.map((h, i) => (
+
+ {h.verb}
+ {h.path}
+
+ ))}
+
+ )}
+
+ {(owner || branch) && (
+
+ {owner && repo && (
+
+ Repository
+ {owner}/{repo}
+
+ )}
+ {branch && (
+
+ Branch
+
+ {branch}
+
+
+ )}
+
+ )}
+
+ {allFiles.length > 0 && (
+
+
+ Files changed ({allFiles.length})
+
+
+ {allFiles.map((f, i) => (
+
+ ✓
+
+ {f.action}
+
+ {f.path}
+
+ {actionMeta(f.action)}
+
+
+ ))}
+
+
+ )}
+
+ {inlineNextActions.length > 0 && (
+
+ {inlineNextActions.map((a, i) => (
+
+ ))}
+
+ )}
+
+ {hasTechLog && (
+
+
+ View execution log
+ {totalDuration > 0 && (
+
+ · {(totalDuration / 1000).toFixed(1)}s
+
+ )}
+
+ {steps.map((s) => (
+
+
+ Step {s.step_number}
+ {totalSteps > 1 ? ` of ${totalSteps}` : ""}
+
+ {s.summary && (
+
{s.summary}
+ )}
+ {Array.isArray(s.executions) && s.executions.map((ex, i) => (
+
+ ))}
+
+ ))}
+
+ )}
+
+ {hasPRPath && (
+
+ Next: Create a pull request when ready.
+
+ )}
+
+ );
+}
+
+function actionMeta(action) {
+ switch (action) {
+ case "READ": return "Read-only";
+ case "CREATE": return "Created";
+ case "MODIFY": return "Modified";
+ case "DELETE": return "Deleted";
+ case "INDEX": return "Indexed";
+ default: return "";
+ }
+}
+
+function verbFor(action) {
+ switch (action) {
+ case "CREATE": return "Created";
+ case "MODIFY": return "Modified";
+ case "DELETE": return "Deleted";
+ default: return action;
+ }
+}
+
+function ExecutionCard({ ex }) {
+ const status = ex.status || "pending";
+ const statusClass =
+ status === "completed" ? "exec-card-inner--ok" :
+ status === "failed" ? "exec-card-inner--bad" :
+ status === "skipped" ? "exec-card-inner--warn" :
+ "exec-card-inner--info";
+ return (
+
+
+
+ {ex.path}
+ {ex.sandbox && (
+ · {ex.sandbox}
+ )}
+
+
+ {status === "completed" && `Exit ${ex.exit_code} · ${ex.duration_ms} ms`}
+ {status === "failed" && (typeof ex.exit_code === "number"
+ ? `Failed · exit ${ex.exit_code}` : "Failed")}
+ {status === "skipped" && "Skipped"}
+ {status === "pending" && "Running…"}
+
+
+ {ex.command && (
+
$ {ex.command}
+ )}
+ {ex.stdout && (
+
+ stdout
+ {ex.stdout}
+
+ )}
+ {ex.stderr && (
+
+ stderr
+
+ {ex.stderr}
+
+
+ )}
+ {ex.error && !ex.stderr && (
+
{ex.error}
+ )}
+ {ex.reason && (
+
{ex.reason}
+ )}
+
+ );
+}
diff --git a/frontend/components/BranchPicker.jsx b/frontend/components/BranchPicker.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..e04e04d77dbda1a8532b26c9c2d3fc92fb7d2616
--- /dev/null
+++ b/frontend/components/BranchPicker.jsx
@@ -0,0 +1,398 @@
+import React, { useCallback, useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+
+/**
+ * BranchPicker — Claude-Code-on-Web parity branch selector.
+ *
+ * Fetches branches from the new /api/repos/{owner}/{repo}/branches endpoint.
+ * Shows search, default branch badge, AI session branch highlighting.
+ *
+ * Fixes applied:
+ * - Dropdown portaled to document.body (avoids overflow:hidden clipping)
+ * - Branches cached per repo (no "No branches found" flash)
+ * - Shows "Loading..." only on first fetch, keeps stale data otherwise
+ */
+
+// Simple per-repo branch cache so reopening the dropdown is instant
+const branchCache = {};
+
+/**
+ * Props:
+ * repo, currentBranch, defaultBranch, sessionBranches, onBranchChange
+ * — standard branch-picker props
+ *
+ * externalAnchorRef (optional) — a React ref pointing to an external DOM
+ * element to anchor the dropdown to. When provided:
+ * - BranchPicker skips rendering its own trigger button
+ * - the dropdown opens immediately on mount
+ * - closing the dropdown calls onClose()
+ *
+ * onClose (optional) — called when the dropdown is dismissed (outside
+ * click or Escape). Only meaningful with externalAnchorRef.
+ */
+export default function BranchPicker({
+ repo,
+ currentBranch,
+ defaultBranch,
+ sessionBranches = [],
+ onBranchChange,
+ externalAnchorRef,
+ onClose,
+}) {
+ const isExternalMode = !!externalAnchorRef;
+ const [open, setOpen] = useState(isExternalMode);
+ const [query, setQuery] = useState("");
+ const [branches, setBranches] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+ const triggerRef = useRef(null);
+ const dropdownRef = useRef(null);
+ const inputRef = useRef(null);
+
+ const branch = currentBranch || defaultBranch || "main";
+ const isAiSession = sessionBranches.includes(branch) && branch !== defaultBranch;
+
+ // The element used for dropdown positioning
+ const anchorRef = isExternalMode ? externalAnchorRef : triggerRef;
+
+ const cacheKey = repo ? `${repo.owner}/${repo.name}` : null;
+
+ // Seed from cache on mount / repo change
+ useEffect(() => {
+ if (cacheKey && branchCache[cacheKey]) {
+ setBranches(branchCache[cacheKey]);
+ }
+ }, [cacheKey]);
+
+ // Fetch branches from GitHub via backend
+ const fetchBranches = useCallback(async (searchQuery) => {
+ if (!repo) return;
+ setLoading(true);
+ setError(null);
+ try {
+ const token = localStorage.getItem("github_token");
+ const headers = token ? { Authorization: `Bearer ${token}` } : {};
+ const params = new URLSearchParams({ per_page: "100" });
+ if (searchQuery) params.set("query", searchQuery);
+
+ const res = await fetch(
+ `/api/repos/${repo.owner}/${repo.name}/branches?${params}`,
+ { headers, cache: "no-cache" }
+ );
+ if (!res.ok) {
+ const errData = await res.json().catch(() => ({}));
+ const detail = errData.detail || `HTTP ${res.status}`;
+ console.warn("BranchPicker: fetch failed:", detail);
+ setError(detail);
+ return;
+ }
+ const data = await res.json();
+ const fetched = data.branches || [];
+ setBranches(fetched);
+
+ // Only cache the unfiltered result
+ if (!searchQuery && cacheKey) {
+ branchCache[cacheKey] = fetched;
+ }
+ } catch (err) {
+ console.warn("Failed to fetch branches:", err);
+ } finally {
+ setLoading(false);
+ }
+ }, [repo, cacheKey]);
+
+ // Fetch + focus when opened
+ useEffect(() => {
+ if (open) {
+ fetchBranches(query);
+ setTimeout(() => inputRef.current?.focus(), 50);
+ }
+ }, [open]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Debounced search
+ useEffect(() => {
+ if (!open) return;
+ const t = setTimeout(() => fetchBranches(query), 300);
+ return () => clearTimeout(t);
+ }, [query, open, fetchBranches]);
+
+ // Close on outside click
+ useEffect(() => {
+ if (!open) return;
+ const handler = (e) => {
+ const inAnchor = anchorRef.current && anchorRef.current.contains(e.target);
+ const inDropdown = dropdownRef.current && dropdownRef.current.contains(e.target);
+ if (!inAnchor && !inDropdown) {
+ handleClose();
+ }
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [open]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const handleClose = useCallback(() => {
+ setOpen(false);
+ setQuery("");
+ onClose?.();
+ }, [onClose]);
+
+ const handleSelect = (branchName) => {
+ handleClose();
+ if (branchName !== branch) {
+ onBranchChange?.(branchName);
+ }
+ };
+
+ // Merge API branches with session branches (AI branches might not show in GitHub API)
+ const allBranches = [...branches];
+ for (const sb of sessionBranches) {
+ if (!allBranches.find((b) => b.name === sb)) {
+ allBranches.push({ name: sb, is_default: false, protected: false });
+ }
+ }
+
+ // Calculate portal position from anchor element
+ const getDropdownPosition = () => {
+ if (!anchorRef.current) return { top: 0, left: 0 };
+ const rect = anchorRef.current.getBoundingClientRect();
+ return {
+ top: rect.bottom + 4,
+ left: rect.left,
+ };
+ };
+
+ const pos = open ? getDropdownPosition() : { top: 0, left: 0 };
+
+ return (
+
+ {/* Trigger button — hidden when using external anchor */}
+ {!isExternalMode && (
+
setOpen((v) => !v)}
+ >
+
+
+
+
+
+
+ {branch}
+
+
+
+
+ )}
+
+ {/* Dropdown — portaled to document.body to escape overflow:hidden */}
+ {open && createPortal(
+
+ {/* Search input */}
+
+ setQuery(e.target.value)}
+ style={styles.searchInput}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ handleClose();
+ }
+ }}
+ />
+
+
+ {/* Branch list */}
+
+ {loading && allBranches.length === 0 && (
+
Loading...
+ )}
+
+ {!loading && error && (
+
{error}
+ )}
+
+ {!loading && !error && allBranches.length === 0 && (
+
No branches found
+ )}
+
+ {allBranches.map((b) => {
+ const isDefault = b.is_default || b.name === defaultBranch;
+ const isAi = sessionBranches.includes(b.name);
+ const isCurrent = b.name === branch;
+
+ return (
+
handleSelect(b.name)}
+ >
+
+ ✓
+
+
+ {b.name}
+
+ {isDefault && (
+
default
+ )}
+ {isAi && !isDefault && (
+
AI
+ )}
+ {b.protected && (
+
+
+
+
+
+ )}
+
+ );
+ })}
+
+ {/* Subtle loading indicator when refreshing with cached data visible */}
+ {loading && allBranches.length > 0 && (
+
Updating...
+ )}
+
+
,
+ document.body
+ )}
+
+ );
+}
+
+const styles = {
+ container: {
+ position: "relative",
+ },
+ trigger: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "4px 8px",
+ borderRadius: 4,
+ border: "1px solid #3F3F46",
+ background: "transparent",
+ fontSize: 13,
+ cursor: "pointer",
+ fontFamily: "monospace",
+ maxWidth: 200,
+ },
+ branchName: {
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ maxWidth: 140,
+ },
+ dropdown: {
+ position: "fixed",
+ width: 280,
+ backgroundColor: "#1F1F23",
+ border: "1px solid #27272A",
+ borderRadius: 8,
+ boxShadow: "0 8px 24px rgba(0,0,0,0.6)",
+ zIndex: 9999,
+ overflow: "hidden",
+ },
+ searchBox: {
+ padding: "8px 10px",
+ borderBottom: "1px solid #27272A",
+ },
+ searchInput: {
+ width: "100%",
+ padding: "6px 8px",
+ borderRadius: 4,
+ border: "1px solid #3F3F46",
+ background: "#131316",
+ color: "#E4E4E7",
+ fontSize: 12,
+ outline: "none",
+ fontFamily: "monospace",
+ boxSizing: "border-box",
+ },
+ branchList: {
+ maxHeight: 260,
+ overflowY: "auto",
+ },
+ branchRow: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "7px 10px",
+ cursor: "pointer",
+ transition: "background-color 0.1s",
+ borderBottom: "1px solid rgba(39, 39, 42, 0.5)",
+ },
+ loadingRow: {
+ padding: "12px 10px",
+ textAlign: "center",
+ fontSize: 12,
+ color: "#71717A",
+ },
+ errorRow: {
+ padding: "12px 10px",
+ textAlign: "center",
+ fontSize: 11,
+ color: "#F59E0B",
+ },
+ defaultBadge: {
+ fontSize: 9,
+ padding: "1px 5px",
+ borderRadius: 8,
+ backgroundColor: "rgba(16, 185, 129, 0.15)",
+ color: "#10B981",
+ fontWeight: 600,
+ textTransform: "uppercase",
+ letterSpacing: "0.04em",
+ flexShrink: 0,
+ },
+ aiBadge: {
+ fontSize: 9,
+ padding: "1px 5px",
+ borderRadius: 8,
+ backgroundColor: "rgba(59, 130, 246, 0.15)",
+ color: "#60a5fa",
+ fontWeight: 700,
+ flexShrink: 0,
+ },
+ protectedBadge: {
+ color: "#F59E0B",
+ flexShrink: 0,
+ display: "flex",
+ alignItems: "center",
+ },
+};
diff --git a/frontend/components/ChatPanel.jsx b/frontend/components/ChatPanel.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..6f0f6bc6af59b409abdd84d69c9368e5ba9e14e5
--- /dev/null
+++ b/frontend/components/ChatPanel.jsx
@@ -0,0 +1,1370 @@
+// frontend/components/ChatPanel.jsx
+import React, { useEffect, useRef, useState } from "react";
+import AssistantMessage from "./AssistantMessage.jsx";
+import ThinkingIndicator from "./ThinkingIndicator.jsx";
+import ContextMeter from "./ContextMeter.jsx";
+import TasksPanel from "./TasksPanel.jsx";
+import DiffStats from "./DiffStats.jsx";
+import DiffViewer from "./DiffViewer.jsx";
+import CreatePRButton from "./CreatePRButton.jsx";
+import StreamingMessage from "./StreamingMessage.jsx";
+import SandboxCanvas from "./SandboxCanvas.jsx";
+import FilePreviewPanel from "./FilePreviewPanel.jsx";
+import { SessionWebSocket } from "../utils/ws.js";
+
+// Map a file extension to the canonical sandbox language tag. Used
+// when "Open in Canvas" needs to seed SandboxCanvas with the right
+// language hint pulled straight from a repo file path.
+const _LANG_FROM_EXT = {
+ py: "python", js: "javascript", mjs: "javascript", cjs: "javascript",
+ sh: "bash", bash: "bash",
+};
+function languageFromPath(path) {
+ if (!path || !path.includes(".")) return "python";
+ return _LANG_FROM_EXT[path.split(".").pop().toLowerCase()] || "python";
+}
+
+// Helper to get headers (inline safety if utility is missing)
+const getHeaders = () => ({
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${localStorage.getItem("github_token") || ""}`,
+});
+
+export default function ChatPanel({
+ repo,
+ defaultBranch = "main",
+ currentBranch, // do NOT default here; parent must pass the real one
+ onExecutionComplete,
+ sessionChatState,
+ onSessionChatStateChange,
+ sessionId,
+ onEnsureSession,
+ canChat = true, // readiness gate: false disables composer and shows blocker
+ chatBlocker = null, // { message: string, cta?: string, onCta?: () => void }
+}) {
+ // Initialize state from props or defaults
+ const [messages, setMessages] = useState(sessionChatState?.messages || []);
+ const [goal, setGoal] = useState("");
+ const [plan, setPlan] = useState(sessionChatState?.plan || null);
+
+ const [loadingPlan, setLoadingPlan] = useState(false);
+ const [executing, setExecuting] = useState(false);
+ const [status, setStatus] = useState("");
+ // Batch B9 — populated when a plan whose first step was INDEX is
+ // rejected. Lets us render a small "Run with grep instead?" prompt
+ // so the user doesn't have to retype the goal.
+ const [retryAfterIndexReject, setRetryAfterIndexReject] = useState(null);
+
+ // Claude-Code-on-Web: WebSocket streaming + diff + PR
+ const [wsConnected, setWsConnected] = useState(false);
+ const [streamingEvents, setStreamingEvents] = useState([]);
+ const [diffData, setDiffData] = useState(null);
+ const [showDiffViewer, setShowDiffViewer] = useState(false);
+ // SandboxCanvas state — opened by the "Open in Canvas" CTA on
+ // post-CREATE next_actions and ExecutionCard footers. ``canvasSpec``
+ // is { filename, language, code } or null when closed.
+ const [canvasSpec, setCanvasSpec] = useState(null);
+ const [canvasError, setCanvasError] = useState(null);
+ // FilePreviewPanel state — opened by clicking a file row in the
+ // sidebar (gitpilot:open-file). Read-first surface; users can pick
+ // "Prepare Run" / "Open Workspace" / "Ask GitPilot" from there.
+ const [previewPath, setPreviewPath] = useState(null);
+ const [previewContent, setPreviewContent] = useState(null);
+ const [previewLoading, setPreviewLoading] = useState(false);
+ const [previewError, setPreviewError] = useState(null);
+ const [previewErrorCode, setPreviewErrorCode] = useState(null);
+ // "preview" (narrow drawer) or "workspace" (wide editor).
+ const [previewMode, setPreviewMode] = useState("preview");
+ const wsRef = useRef(null);
+
+ // Ref mirrors streamingEvents so WS callbacks avoid stale closures
+ const streamingEventsRef = useRef([]);
+ useEffect(() => { streamingEventsRef.current = streamingEvents; }, [streamingEvents]);
+
+ // Tracks files that were just CREATE'd / MODIFY'd by a fresh execution.
+ // Used to (a) auto-retry once on 404 (GitHub contents API has brief
+ // eventual-consistency lag) and (b) classify the file viewer's empty
+ // state as "still syncing" instead of a generic 404.
+ const fileWasJustCreatedRef = useRef(new Set());
+ const fileWasJustDeletedRef = useRef(new Set());
+
+ // Skip the session-sync useEffect reset when we just created a session
+ // (the parent already seeded the messages into chatBySession)
+ const skipNextSyncRef = useRef(false);
+
+ const messagesEndRef = useRef(null);
+ const prevMsgCountRef = useRef((sessionChatState?.messages || []).length);
+
+ // ---------------------------------------------------------------------------
+ // WebSocket connection management
+ // ---------------------------------------------------------------------------
+ useEffect(() => {
+ // Clean up previous connection
+ if (wsRef.current) {
+ wsRef.current.close();
+ wsRef.current = null;
+ setWsConnected(false);
+ }
+
+ if (!sessionId) return;
+
+ // Wait for backend to be reachable before opening WebSocket.
+ // Without this, the WS connects immediately on session creation
+ // and fails repeatedly with "closed before established" when the
+ // backend is still starting up (common on WSL cold start).
+ let cancelled = false;
+ const backendUrl = import.meta.env.VITE_BACKEND_URL || '';
+ const pingUrl = backendUrl ? `${backendUrl}/api/ping` : '/api/ping';
+ const waitForBackend = async () => {
+ for (let i = 0; i < 10 && !cancelled; i++) {
+ try {
+ const res = await fetch(pingUrl, { method: 'GET', signal: AbortSignal.timeout(2000) });
+ if (res.ok) return true;
+ } catch { /* retry */ }
+ await new Promise(r => setTimeout(r, 1500));
+ }
+ return false;
+ };
+
+ waitForBackend().then((ok) => {
+ if (cancelled || !ok) return;
+ connectWs();
+ });
+
+ function connectWs() {
+ const ws = new SessionWebSocket(sessionId, {
+ onConnect: () => setWsConnected(true),
+ onDisconnect: () => setWsConnected(false),
+ onMessage: (data) => {
+ if (data.type === "agent_message") {
+ setStreamingEvents((prev) => [...prev, data]);
+ } else if (data.type === "tool_use" || data.type === "tool_result") {
+ setStreamingEvents((prev) => [...prev, data]);
+ } else if (data.type === "diff_update") {
+ setDiffData(data.stats || data);
+ } else if (data.type === "session_restored") {
+ // Session loaded
+ }
+ },
+ onStatusChange: (newStatus) => {
+ if (newStatus === "waiting") {
+ // Always clear loading state when agent finishes
+ setLoadingPlan(false);
+
+ // Consolidate streaming events into a chat message (use ref to
+ // avoid stale closure — streamingEvents state would be stale here).
+ //
+ // We also commit the FINAL consolidated text to the backend session
+ // here. Previously this branch never called persistMessage, so the
+ // assistant turn looked correct in the live view but vanished on the
+ // next session reload — the canonical "streaming truncation" symptom.
+ const events = streamingEventsRef.current;
+ if (events.length > 0) {
+ const textParts = events
+ .filter((e) => e.type === "agent_message")
+ .map((e) => e.content);
+ if (textParts.length > 0) {
+ const consolidated = {
+ from: "ai",
+ role: "assistant",
+ answer: textParts.join(""),
+ content: textParts.join(""),
+ };
+ setMessages((prev) => [...prev, consolidated]);
+ persistMessage(sessionId, "assistant", consolidated.content);
+ }
+ setStreamingEvents([]);
+ }
+ }
+ },
+ onError: (err) => {
+ console.warn("[ws] Error:", err);
+ setLoadingPlan(false);
+ },
+ });
+
+ ws.connect();
+ wsRef.current = ws;
+ } // end connectWs
+
+ return () => {
+ cancelled = true;
+ if (wsRef.current) wsRef.current.close();
+ };
+ }, [sessionId]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // ---------------------------------------------------------------------------
+ // 1) SESSION SYNC: Restore chat when branch, repo, OR session changes
+ // IMPORTANT: Do NOT depend on sessionChatState here (prevents prop/state loop)
+ // ---------------------------------------------------------------------------
+ useEffect(() => {
+ // When send() just created a session, the parent seeded the messages
+ // into chatBySession already. Skip the reset so we don't wipe
+ // the optimistic user message that was already rendered.
+ if (skipNextSyncRef.current) {
+ skipNextSyncRef.current = false;
+ return;
+ }
+
+ const nextMessages = sessionChatState?.messages || [];
+ const nextPlan = sessionChatState?.plan || null;
+
+ setMessages(nextMessages);
+ setPlan(nextPlan);
+
+ // Reset transient UI state on branch/repo/session switch
+ setGoal("");
+ setStatus("");
+ setLoadingPlan(false);
+ setExecuting(false);
+ setStreamingEvents([]);
+ setDiffData(null);
+
+ // Update msg count tracker so auto-scroll doesn't "jump" on switch
+ prevMsgCountRef.current = nextMessages.length;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [currentBranch, repo?.full_name, sessionId]);
+
+ // ---------------------------------------------------------------------------
+ // 1b) FILE ▶ RUN: listen for run-file events from the sidebar.
+ // ---------------------------------------------------------------------------
+ //
+ // FileTree dispatches ``gitpilot:run-file`` with the clicked file's
+ // path. We turn that into a normal chat message ("run ")
+ // which goes through /api/chat/plan, hits the deterministic
+ // short-circuit, and renders an ExecutionPlanCard — exactly the
+ // same flow as typing the command. One handler, one approval surface,
+ // zero duplicated logic.
+ useEffect(() => {
+ const onRunFile = (e) => {
+ const path = e?.detail?.path;
+ if (!path || !repo) return;
+ send({ goal: `run ${path}` });
+ };
+ // "Open in Canvas" handler — fetches the file's content from the
+ // active branch and opens SandboxCanvas seeded with it. Logs a
+ // friendly error banner when the fetch fails so a misconfigured
+ // token / wrong branch doesn't silently swallow the click.
+ const onOpenInCanvas = async (e) => {
+ const path = e?.detail?.path;
+ if (!path || !repo) return;
+ setCanvasError(null);
+ const branch = currentBranch || "HEAD";
+ try {
+ const url = `/api/repos/${repo.owner}/${repo.name}/file`
+ + `?path=${encodeURIComponent(path)}`
+ + `&ref=${encodeURIComponent(branch)}`;
+ const res = await fetch(url, { headers: getHeaders() });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ setCanvasError(data.detail || `Could not load ${path} (HTTP ${res.status})`);
+ // Still open the canvas with empty content so the user can
+ // paste something — better than nothing happening on click.
+ setCanvasSpec({
+ filename: path, language: languageFromPath(path), code: "",
+ });
+ return;
+ }
+ setCanvasSpec({
+ filename: path,
+ language: languageFromPath(path),
+ code: data.content || "",
+ });
+ } catch (err) {
+ setCanvasError(err?.message || "Could not load file for Canvas");
+ setCanvasSpec({
+ filename: path, language: languageFromPath(path), code: "",
+ });
+ }
+ };
+ // "Open file" — clicking a file row in the sidebar mounts the
+ // read-first FilePreviewPanel. Calmer than dropping straight
+ // into Canvas: the user sees the file, can pick "Prepare Run"
+ // when they're ready (or "Open Workspace" for a wider editing
+ // surface). The ``mode`` detail toggles the panel's geometry:
+ // "preview" ── narrow right drawer for a quick look
+ // "workspace" ── wide right-side editor for serious review
+ const openFile = async (path, mode = "preview") => {
+ if (!path || !repo) return;
+ setPreviewPath(path);
+ setPreviewMode(mode);
+ setPreviewContent(null);
+ setPreviewError(null);
+ setPreviewErrorCode(null);
+ setPreviewLoading(true);
+ // Tell the sidebar which file is currently focused so it can
+ // light up the row with the ◄ marker.
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:file-opened", { detail: { path } }));
+ } catch (_e) { /* old browser */ }
+ const branch = currentBranch || "HEAD";
+ const fetchOnce = async () => {
+ const url = `/api/repos/${repo.owner}/${repo.name}/file`
+ + `?path=${encodeURIComponent(path)}`
+ + `&ref=${encodeURIComponent(branch)}`;
+ const res = await fetch(url, { headers: getHeaders() });
+ const data = await res.json().catch(() => ({}));
+ return { res, data };
+ };
+ try {
+ let { res, data } = await fetchOnce();
+ // Auto-retry once on 404 for recently created files — GitHub
+ // contents API has brief eventual-consistency lag after a
+ // freshly published commit.
+ if (res.status === 404 && fileWasJustCreatedRef.current?.has(path)) {
+ await new Promise((r) => setTimeout(r, 900));
+ ({ res, data } = await fetchOnce());
+ }
+ if (!res.ok) {
+ setPreviewError(data.detail || `HTTP ${res.status}`);
+ setPreviewErrorCode(res.status);
+ } else {
+ setPreviewContent(data.content || "");
+ }
+ } catch (err) {
+ setPreviewError(err?.message || "Could not load file");
+ setPreviewErrorCode(null);
+ } finally {
+ setPreviewLoading(false);
+ }
+ };
+ const onOpenFile = (e) => openFile(e?.detail?.path, "preview");
+ const onOpenWorkspace = (e) => openFile(e?.detail?.path, "workspace");
+ // "Ask GitPilot" — seed the chat input with a contextual question
+ // about the clicked file. Pure additive: focuses the input and
+ // pre-fills it; the user can edit or send as-is.
+ const onAskAboutFile = (e) => {
+ const path = e?.detail?.path;
+ if (!path) return;
+ setGoal(`Tell me about ${path}.`);
+ const ta = document.querySelector(".chat-input");
+ if (ta) { ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }
+ };
+ window.addEventListener("gitpilot:run-file", onRunFile);
+ window.addEventListener("gitpilot:open-in-canvas", onOpenInCanvas);
+ window.addEventListener("gitpilot:open-file", onOpenFile);
+ window.addEventListener("gitpilot:open-workspace", onOpenWorkspace);
+ window.addEventListener("gitpilot:ask-about-file", onAskAboutFile);
+ return () => {
+ window.removeEventListener("gitpilot:run-file", onRunFile);
+ window.removeEventListener("gitpilot:open-in-canvas", onOpenInCanvas);
+ window.removeEventListener("gitpilot:open-file", onOpenFile);
+ window.removeEventListener("gitpilot:open-workspace", onOpenWorkspace);
+ window.removeEventListener("gitpilot:ask-about-file", onAskAboutFile);
+ };
+ // ``send`` is stable enough across renders for this use case —
+ // we don't want to re-bind on every keystroke.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [repo?.full_name, currentBranch, sessionId]);
+
+ // ---------------------------------------------------------------------------
+ // 2) PERSISTENCE: Save chat to Parent (no loop now because sync only on branch)
+ // ---------------------------------------------------------------------------
+ useEffect(() => {
+ if (typeof onSessionChatStateChange === "function") {
+ // Avoid wiping parent state on mount
+ if (messages.length > 0 || plan) {
+ onSessionChatStateChange({ messages, plan });
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [messages, plan]);
+
+ // ---------------------------------------------------------------------------
+ // 3) AUTO-SCROLL: Only scroll when a message is appended (reduces flicker)
+ // ---------------------------------------------------------------------------
+ useEffect(() => {
+ const curCount = messages.length + streamingEvents.length;
+ const prevCount = prevMsgCountRef.current;
+
+ // Only scroll when new messages are added
+ if (curCount > prevCount) {
+ prevMsgCountRef.current = curCount;
+ requestAnimationFrame(() => {
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
+ });
+ } else {
+ prevMsgCountRef.current = curCount;
+ }
+ }, [messages.length, streamingEvents.length]);
+
+ // ---------------------------------------------------------------------------
+ // HANDLERS
+ // ---------------------------------------------------------------------------
+ // ---------------------------------------------------------------------------
+ // Persist a message to the backend session (fire-and-forget).
+ //
+ // The fourth argument carries the *structured* payload of the assistant
+ // response — the Action Plan, the Execution Log, diff stats, etc. The
+ // backend stores it on Message.metadata; on session reload App.jsx
+ // spreads metadata back into the local message via normalizeBackendMessage,
+ // so the same AssistantMessage renderer can re-draw the Plan / Steps /
+ // Create buttons identically to the live view.
+ //
+ // Before this fix the structured payload was dropped at persist time —
+ // the session reloaded as raw text, and the UI degraded to a plain
+ // paragraph. This is the canonical "state loss during hydration" bug.
+ // ---------------------------------------------------------------------------
+ const persistMessage = (sid, role, content, metadata = null) => {
+ if (!sid) return;
+ const body = { role, content };
+ if (metadata && typeof metadata === "object" && Object.keys(metadata).length > 0) {
+ body.metadata = metadata;
+ }
+ fetch(`/api/sessions/${sid}/message`, {
+ method: "POST",
+ headers: getHeaders(),
+ body: JSON.stringify(body),
+ }).catch(() => {}); // best-effort
+ };
+
+ // Pick the structured fields a message can carry across a reload.
+ // Keep this in one place so every call-site stores the same shape and
+ // the renderer never has to guess.
+ const pickAssistantMetadata = (m) => {
+ if (!m || typeof m !== "object") return null;
+ const meta = {};
+ if (m.plan) meta.plan = m.plan;
+ if (m.executionLog) meta.executionLog = m.executionLog;
+ if (m.diff) meta.diff = m.diff;
+ if (m.actions) meta.actions = m.actions;
+ if (m.nextActions) meta.nextActions = m.nextActions;
+ if (m.branch) meta.branch = m.branch;
+ // Informational plans (READ-only answers to "what does X do?" style
+ // questions) carry no Approve/Reject controls — pin the flag so the
+ // session reload re-renders the same shape.
+ if (m.informational) meta.informational = true;
+ return Object.keys(meta).length > 0 ? meta : null;
+ };
+
+ const send = async (overrides = {}) => {
+ if (!repo) return;
+ // Allow callers (e.g. the "Retry with grep" button on a rejected
+ // INDEX plan) to drive send() with a fixed goal and a router flag.
+ const overrideGoal = overrides.goal;
+ const force_no_rag = Boolean(overrides.force_no_rag);
+ const sourceText = overrideGoal != null ? overrideGoal : goal;
+ if (!sourceText || !sourceText.trim()) return;
+
+ const text = sourceText.trim();
+
+ // Clear input immediately (Claude Code behavior) — but only when
+ // the user typed; programmatic retries leave the input alone.
+ if (overrideGoal == null) setGoal("");
+ // Reset textarea height
+ const ta = document.querySelector(".chat-input");
+ if (ta) ta.style.height = "40px";
+
+ // Optimistic update (user bubble appears immediately)
+ const userMsg = { from: "user", role: "user", text, content: text };
+ setMessages((prev) => [...prev, userMsg]);
+
+ setLoadingPlan(true);
+ setStatus("");
+ setPlan(null);
+ setStreamingEvents([]);
+
+ // ------- Implicit session creation (Claude Code parity) -------
+ // Every chat must be backed by a session. If none exists yet,
+ // create one on-demand before sending the plan request.
+ let sid = sessionId;
+ if (!sid && typeof onEnsureSession === "function") {
+ // Derive a short title from the first message
+ const sessionName = text.length > 60 ? text.slice(0, 57) + "..." : text;
+
+ // Tell the sync useEffect to skip the reset that would otherwise
+ // wipe the optimistic user message when activeSessionId changes.
+ skipNextSyncRef.current = true;
+
+ sid = await onEnsureSession(sessionName, [userMsg]);
+ if (!sid) {
+ // Session creation failed — continue without session
+ skipNextSyncRef.current = false;
+ }
+ }
+
+ // Persist user message to backend session
+ persistMessage(sid, "user", text);
+
+ // Always use HTTP for plan generation (the original reliable flow).
+ // WebSocket is only used for real-time streaming feedback display.
+ const effectiveBranch = currentBranch || defaultBranch || "HEAD";
+
+ try {
+ // Timeout after 5 minutes (CrewAI agent can be slow with small models)
+ const planController = new AbortController();
+ const planTimer = setTimeout(() => planController.abort(), 300000);
+
+ let res;
+ try {
+ res = await fetch("/api/chat/plan", {
+ method: "POST",
+ headers: getHeaders(),
+ body: JSON.stringify({
+ repo_owner: repo.owner,
+ repo_name: repo.name,
+ goal: text,
+ branch_name: effectiveBranch,
+ // Lets the backend record this plan as a Task on the
+ // session so the right-sidebar Tasks panel can trace it.
+ session_id: sid,
+ // Batch B9 — set on the "Retry with grep" path after the
+ // user rejects an INDEX-plan. Tells the router to
+ // suppress RAG / INDEX recommendations.
+ force_no_rag,
+ }),
+ signal: planController.signal,
+ });
+ } catch (fetchErr) {
+ if (fetchErr.name === "AbortError") {
+ throw new Error("Request timed out after 5 minutes. The LLM may be too slow. Try a faster model.");
+ }
+ throw fetchErr;
+ } finally {
+ clearTimeout(planTimer);
+ }
+
+ let data;
+ try {
+ data = await res.json();
+ } catch {
+ throw new Error(`Server error (${res.status}). The LLM may have returned an invalid response. Try a different model or enable Lite Mode in Settings.`);
+ }
+ if (!res.ok) {
+ const detail = data?.detail || data?.error || data?.message || "";
+ // Friendly message for common LLM failures
+ if (detail.includes("None or empty") || detail.includes("Invalid response from LLM")) {
+ throw new Error(
+ "The LLM returned an empty response. This often happens with small models (deepseek, qwen 0.5b). " +
+ "Try a larger model (llama3, qwen2.5:7b) or enable Lite Mode in Settings."
+ );
+ }
+ throw new Error(detail || "Failed to generate plan");
+ }
+
+ // Classify the plan into one of three kinds so we can render the
+ // right shape — not just "valid or banner":
+ //
+ // * executable — at least one CREATE/MODIFY/DELETE → plan card
+ // with Approve & execute / Reject controls.
+ // * informational — every file is READ (or no files at all on a
+ // step that still has a meaningful description)
+ // AND the summary is a real answer, not the
+ // placeholder. This is what happens when the
+ // user asks "what do you think about this
+ // project?" — the planner correctly READs the
+ // relevant files and the summary IS the answer.
+ // Render the summary as a normal assistant
+ // message; do not show plan controls.
+ // * empty — no steps OR no actionable signal at all →
+ // honest failure banner.
+ //
+ // Before this classifier the second case was treated as the
+ // third, surfacing "I couldn't produce a plan" on perfectly
+ // valid READ-only plans.
+ const planSteps = Array.isArray(data?.steps)
+ ? data.steps
+ : Array.isArray(data?.plan?.steps)
+ ? data.plan.steps
+ : [];
+ const PLACEHOLDER_SUMMARY = "Here is the proposed plan for your request.";
+ const summary =
+ data.plan?.summary || data.summary || data.message || PLACEHOLDER_SUMMARY;
+ const hasExecutable = planSteps.some(
+ (s) =>
+ Array.isArray(s?.files) &&
+ s.files.some((f) => ["CREATE", "MODIFY", "DELETE"].includes(f?.action)),
+ );
+ const isReadOnly =
+ planSteps.length > 0 &&
+ !hasExecutable &&
+ planSteps.every(
+ (s) =>
+ !Array.isArray(s?.files) ||
+ s.files.length === 0 ||
+ s.files.every((f) => f?.action === "READ"),
+ );
+ const hasRealSummary = Boolean(summary) && summary !== PLACEHOLDER_SUMMARY;
+ const planKind = hasExecutable
+ ? "executable"
+ : isReadOnly && hasRealSummary
+ ? "informational"
+ : "empty";
+
+ if (planKind === "executable") {
+ setPlan(data);
+ const assistantMsg = {
+ from: "ai",
+ role: "assistant",
+ answer: summary,
+ content: summary,
+ plan: data,
+ };
+ setMessages((prev) => [...prev, assistantMsg]);
+ persistMessage(sid, "assistant", summary, pickAssistantMetadata(assistantMsg));
+ } else if (planKind === "informational") {
+ // The summary is the answer. No plan card, no Approve/Reject —
+ // there is nothing to execute. We deliberately do NOT attach
+ // ``plan: data`` here so AssistantMessage renders this turn
+ // exactly like a chat reply.
+ setPlan(null);
+ const assistantMsg = {
+ from: "ai",
+ role: "assistant",
+ answer: summary,
+ content: summary,
+ informational: true,
+ };
+ setMessages((prev) => [...prev, assistantMsg]);
+ persistMessage(sid, "assistant", summary, pickAssistantMetadata(assistantMsg));
+ } else {
+ // empty — be honest about what we know. The earlier wording
+ // ("got stuck reading the same file twice") was a guess from
+ // an older bug; for the cases that actually still hit this
+ // branch the real signal is just "no actionable steps".
+ setPlan(null);
+ const failureText =
+ "The model returned an empty plan. Try rephrasing more concretely, " +
+ "or pick a stronger model in Settings → Provider.";
+ const failureMsg = {
+ from: "ai",
+ role: "system",
+ content: failureText,
+ };
+ setMessages((prev) => [...prev, failureMsg]);
+ persistMessage(sid, "system", failureText);
+ setStatus("No actionable plan produced.");
+ return;
+ }
+ } catch (err) {
+ const msg = String(err?.message || err);
+ console.error(err);
+ setStatus(msg);
+ setMessages((prev) => [
+ ...prev,
+ { from: "ai", role: "system", content: `Error: ${msg}` },
+ ]);
+ } finally {
+ setLoadingPlan(false);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // Reject the active plan — minimal first cut.
+ //
+ // Industry rule we follow from the start: never write to disk on a path the
+ // user did not approve. Rejecting is the cheapest expression of that —
+ // discard the proposed plan locally, leave the workspace untouched, record
+ // the rejection in chat history so the user sees it after a session reload.
+ //
+ // No backend endpoint is needed yet because plans are not persisted as
+ // first-class objects today; they ride along on the assistant message's
+ // metadata. When we later add per-plan state tracking, this handler will
+ // also POST /api/chat/plan/{id}/reject — leaving that for a follow-up.
+ // ---------------------------------------------------------------------------
+ const rejectPlan = () => {
+ if (!plan || executing) return;
+
+ // Batch B9 — if the rejected plan contained an INDEX step, the
+ // user is implicitly saying "I don't want to build the semantic
+ // index right now". Stash the original goal so we can offer a
+ // one-click "retry with grep" path on the next render.
+ const hadIndexStep = Array.isArray(plan?.steps) &&
+ plan.steps.some((s) =>
+ Array.isArray(s?.files) && s.files.some((f) => f?.action === "INDEX"),
+ );
+ const rejectedGoal = plan?.goal || "";
+
+ setPlan(null);
+ setStatus("Plan rejected. No files were changed.");
+
+ const rejectionMsg = {
+ from: "ai",
+ role: "system",
+ content: "Plan rejected. No files were changed.",
+ };
+ setMessages((prev) => [...prev, rejectionMsg]);
+
+ if (sessionId) {
+ persistMessage(sessionId, "system", rejectionMsg.content);
+ }
+
+ if (hadIndexStep && rejectedGoal) {
+ setRetryAfterIndexReject({ goal: rejectedGoal });
+ } else {
+ setRetryAfterIndexReject(null);
+ }
+ };
+
+ const execute = async () => {
+ if (!repo || !plan) return;
+
+ setExecuting(true);
+ setStatus("");
+
+ try {
+ // Guard: currentBranch might be missing if parent didn't pass it yet
+ const safeCurrent = currentBranch || defaultBranch || "HEAD";
+ const safeDefault = defaultBranch || "main";
+
+ // Sticky vs Hard Switch:
+ // - If on default branch -> undefined (backend creates new branch)
+ // - If already on AI branch -> currentBranch (backend updates existing)
+ const branch_name = safeCurrent === safeDefault ? undefined : safeCurrent;
+
+ const res = await fetch("/api/chat/execute", {
+ method: "POST",
+ headers: getHeaders(),
+ body: JSON.stringify({
+ repo_owner: repo.owner,
+ repo_name: repo.name,
+ plan,
+ branch_name,
+ // Lets the backend persist the new branch on the session
+ // record so reopening this session lands on the published
+ // branch, not the one it was created on.
+ session_id: sessionId,
+ }),
+ });
+
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.detail || "Execution failed");
+
+ setStatus(data.message || "Execution completed.");
+
+ // Track files touched by this execution so the file viewer can
+ // give "still syncing" / "deleted" classifications and so the
+ // sidebar refreshes off the freshly-pushed branch tree.
+ if (plan?.steps) {
+ for (const step of plan.steps) {
+ for (const f of step.files || []) {
+ if (f.action === "CREATE" || f.action === "MODIFY") {
+ fileWasJustCreatedRef.current.add(f.path);
+ } else if (f.action === "DELETE") {
+ fileWasJustDeletedRef.current.add(f.path);
+ }
+ }
+ }
+ }
+ // Forget the marker after 30 s so older "syncing" badges don't
+ // stick around forever.
+ window.setTimeout(() => {
+ fileWasJustCreatedRef.current.clear();
+ fileWasJustDeletedRef.current.clear();
+ }, 30000);
+
+ // Ask the sidebar's file tree to refetch off the newly-published
+ // branch. Fires after a small delay so GitHub's contents API has
+ // a chance to catch up.
+ window.setTimeout(() => {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:refresh-tree"));
+ } catch (_e) { /* old browser */ }
+ }, 600);
+
+ const completionMsg = {
+ from: "ai",
+ role: "assistant",
+ answer: data.message || "Execution completed.",
+ content: data.message || "Execution completed.",
+ executionLog: data.executionLog,
+ diff: data.diff,
+ // Backend-suggested follow-ups (e.g. "Run demo.py" after CREATE
+ // of a runnable file). Rendered as a button row in the
+ // completion message — one click, no typing.
+ nextActions: data.next_actions,
+ branch: data.branch || data.branch_name,
+ };
+
+ // Show completion immediately (keeps old "Execution Log" section)
+ setMessages((prev) => [...prev, completionMsg]);
+
+ // Persist the execution log + diff alongside the message text so
+ // the History view re-renders the green "Execution Log" panel and
+ // the "View diff" affordance. Without this, reloading the session
+ // shows just the one-line "Execution completed." summary.
+ persistMessage(
+ sessionId,
+ "assistant",
+ completionMsg.content,
+ pickAssistantMetadata(completionMsg),
+ );
+
+ // Clear active plan UI
+ setPlan(null);
+
+ // Pass completionMsg upward for seeding branch history
+ if (typeof onExecutionComplete === "function") {
+ onExecutionComplete({
+ branch: data.branch || data.branch_name,
+ mode: data.mode,
+ commit_url: data.commit_url || data.html_url,
+ message: data.message,
+ completionMsg,
+ sourceBranch: safeCurrent,
+ });
+ }
+ } catch (err) {
+ console.error(err);
+ setStatus(String(err?.message || err));
+ } finally {
+ setExecuting(false);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // RENDER
+ // ---------------------------------------------------------------------------
+ const isOnSessionBranch = currentBranch && currentBranch !== defaultBranch;
+
+ return (
+
+
+
+
+ {messages.map((m, idx) => {
+ // Success message (App.jsx injected)
+ if (m.isSuccess) {
+ return (
+
+ );
+ }
+
+ // User message
+ if (m.from === "user" || m.role === "user") {
+ return (
+
+ {m.text || m.content}
+
+ );
+ }
+
+ // Assistant message (Answer / Plan / Execution Log).
+ //
+ // Lifecycle audit signal: if this message carries a plan, look
+ // ahead in the timeline for any subsequent message that
+ // records an execution log (=> the plan was approved+executed)
+ // or a system "Plan rejected" entry (=> the plan was
+ // rejected). The status is rendered as a small green/grey
+ // badge next to the Action Plan header so users can tell at a
+ // glance — in history — whether a previous plan was acted on.
+ let planStatus = null;
+ if (m.plan) {
+ const after = messages.slice(idx + 1);
+ if (after.some((later) => later.executionLog)) {
+ planStatus = "executed";
+ } else if (
+ after.some(
+ (later) =>
+ later.role === "system" &&
+ typeof later.content === "string" &&
+ later.content.includes("Plan rejected"),
+ )
+ ) {
+ planStatus = "rejected";
+ }
+ }
+
+ // Find the plan that was approved for this completion, so the
+ // success receipt can label actions (READ/CREATE/...) instead of
+ // showing only an opaque execution dump.
+ let linkedPlan = null;
+ if (m.executionLog) {
+ for (let i = idx - 1; i >= 0; i--) {
+ if (messages[i].plan?.steps) {
+ linkedPlan = messages[i].plan;
+ break;
+ }
+ }
+ }
+
+ return (
+
+
execute()}
+ nextActions={m.nextActions}
+ relatedPlan={linkedPlan}
+ diff={m.diff}
+ branch={m.branch || currentBranch}
+ />
+ {/* Diff stats indicator (Claude-Code-on-Web parity) */}
+ {m.diff && (
+ {
+ setDiffData(m.diff);
+ setShowDiffViewer(true);
+ }} />
+ )}
+
+ );
+ })}
+
+ {/* Streaming events (real-time agent output) */}
+ {streamingEvents.length > 0 && (
+
+
+
+ )}
+
+ {/* Enterprise Pulse — agentic thinking state shown after the user
+ hits Send and before the first streamed/planned chunk arrives.
+ Falls back gracefully to nothing once streamingEvents start
+ flowing in (StreamingMessage takes over the live feedback). */}
+ {loadingPlan && streamingEvents.length === 0 && (
+
+ )}
+
+ {/* Live execution status — visible in the chat timeline while
+ ``executing`` is true, sits between the Action Plan card and
+ where the Execution Log (green panel in AssistantMessage)
+ will land once the backend returns. Removes the "did the
+ app freeze?" feeling caused by only the bottom button
+ saying "Executing…".
+
+ Reuses the ThinkingIndicator with execution-specific labels.
+ When the executor finishes, ``setExecuting(false)`` removes
+ this bubble and the completionMsg lands in the timeline as
+ a normal assistant message with its green Execution Log
+ block — already rendered by AssistantMessage today. */}
+ {executing && (
+
+ )}
+
+ {!messages.length && !plan && !loadingPlan && streamingEvents.length === 0 && (
+
+
💬
+
Tell GitPilot what you want to do with this repository.
+
+ It will propose a safe step-by-step plan before any execution.
+
+
+ )}
+
+
+
+
+ {/* Batch B9 — post-Reject "retry with grep" prompt. Renders
+ only when the user rejected a plan whose first step was an
+ INDEX action. One click re-issues the same goal with
+ force_no_rag so the router falls back to grep. */}
+ {retryAfterIndexReject && !loadingPlan && (
+
+
+ Index skipped. Run the same goal with grep instead?
+
+
+ {
+ const g = retryAfterIndexReject.goal;
+ setRetryAfterIndexReject(null);
+ send({ goal: g, force_no_rag: true });
+ }}
+ >
+ Yes, use grep
+
+ setRetryAfterIndexReject(null)}
+ style={{
+ color: "#9CA3AF",
+ borderColor: "rgba(156, 163, 175, 0.35)",
+ background: "transparent",
+ }}
+ >
+ No, dismiss
+
+
+
+ )}
+
+ {/* Diff stats bar (when agent has made changes) */}
+ {diffData && (
+
+ setShowDiffViewer(true)} />
+
+ )}
+
+
+ {/* Readiness blocker banner */}
+ {!canChat && chatBlocker && (
+
+ {chatBlocker.message || "Chat is not ready yet."}
+ {chatBlocker.cta && chatBlocker.onCta && (
+
+ {chatBlocker.cta}
+
+ )}
+
+ )}
+ {status && (
+
+ {status}
+
+ )}
+
+
+
+
+ {/* WebSocket connection indicator + context-window meter */}
+
+
+ {sessionId && (
+
+
+ {wsConnected ? "Live" : "Connecting..."}
+
+ )}
+
+
+
+
+
+
+
+
+ {/* Diff Viewer overlay */}
+ {showDiffViewer && (
+
setShowDiffViewer(false)}
+ />
+ )}
+
+ {/* FilePreviewPanel — read-first viewer. Opens on a file row
+ click in the sidebar. Header carries Prepare Run (runnable
+ only), Open Workspace, and an overflow menu. */}
+ {previewPath && (
+ {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:refresh-tree"));
+ } catch (_e) { /* old browser */ }
+ }}
+ onRetry={() => {
+ const p = previewPath;
+ const m = previewMode;
+ setPreviewPath(null);
+ // Fire the same window event we listened to — keeps the
+ // retry path identical to the original load and lets any
+ // future side-effects (e.g. analytics) see one event class.
+ setTimeout(() => window.dispatchEvent(new CustomEvent(
+ m === "workspace" ? "gitpilot:open-workspace" : "gitpilot:open-file",
+ { detail: { path: p } },
+ )), 0);
+ }}
+ onClose={() => {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:file-closed"));
+ } catch (_e) {/* old browser */}
+ setPreviewPath(null);
+ setPreviewContent(null);
+ setPreviewError(null);
+ setPreviewErrorCode(null);
+ }}
+ />
+ )}
+
+ {/* SandboxCanvas overlay — opened by "Open in Canvas" next_action
+ buttons and ExecutionCard footers via the
+ gitpilot:open-in-canvas window event. */}
+ {canvasSpec && (
+ { setCanvasSpec(null); setCanvasError(null); }}
+ />
+ )}
+ {canvasError && canvasSpec && (
+
+ {canvasError}
+
+ )}
+
+ );
+}
diff --git a/frontend/components/ContextBar.jsx b/frontend/components/ContextBar.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..be13192a04dbea56e257044078db9e1398a44db8
--- /dev/null
+++ b/frontend/components/ContextBar.jsx
@@ -0,0 +1,156 @@
+import React, { useCallback, useRef, useState } from "react";
+import BranchPicker from "./BranchPicker.jsx";
+
+/**
+ * ContextBar — horizontal repo chip bar for multi-repo workspace context.
+ *
+ * Uses CSS classes for hover-reveal X (Claude-style: subtle by default,
+ * visible on chip hover, red on X hover). Each chip owns its own remove
+ * button — removing one repo never affects the others.
+ */
+export default function ContextBar({
+ contextRepos,
+ activeRepoKey,
+ repoStateByKey,
+ onActivate,
+ onRemove,
+ onAdd,
+ onBranchChange,
+ mode, // workspace mode: "github", "local-git", "folder" (optional)
+}) {
+ if (!contextRepos || contextRepos.length === 0) return null;
+
+ return (
+
+ {/* Workspace mode indicator */}
+ {mode && (
+
+ {mode === "github" ? "GH" : mode === "local-git" ? "Git" : "Dir"}
+
+ )}
+
+ {contextRepos.map((entry) => {
+ const isActive = entry.repoKey === activeRepoKey;
+ return (
+ onActivate(entry.repoKey)}
+ onRemove={() => onRemove(entry.repoKey)}
+ onBranchChange={(newBranch) =>
+ onBranchChange(entry.repoKey, newBranch)
+ }
+ />
+ );
+ })}
+
+
+
+
+
+
+
+
+
+
+ {contextRepos.length} {contextRepos.length === 1 ? "repo" : "repos"}
+
+
+ );
+}
+
+function RepoChip({ entry, isActive, repoState, onActivate, onRemove, onBranchChange }) {
+ const [branchOpen, setBranchOpen] = useState(false);
+ const [hovered, setHovered] = useState(false);
+ const branchBtnRef = useRef(null);
+ const repo = entry.repo;
+ const branch = repoState?.currentBranch || entry.branch || repo?.default_branch || "main";
+ const defaultBranch = repoState?.defaultBranch || repo?.default_branch || "main";
+ const sessionBranches = repoState?.sessionBranches || [];
+ const displayName = repo?.name || entry.repoKey?.split("/")[1] || entry.repoKey;
+
+ const handleChipClick = useCallback(
+ (e) => {
+ if (e.target.closest("[data-chip-action]")) return;
+ onActivate();
+ },
+ [onActivate]
+ );
+
+ return (
+ setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ title={isActive ? `Active (write): ${entry.repoKey}` : `Click to activate ${entry.repoKey}`}
+ >
+ {/* Active indicator bar */}
+ {isActive &&
}
+
+ {/* Repo name */}
+
{displayName}
+
+ {/* Separator dot */}
+
+
+ {/* Branch name — single click opens GitHub branch list */}
+
{
+ e.stopPropagation();
+ setBranchOpen((v) => !v);
+ }}
+ >
+ {branch}
+
+
+ {/* Write badge for active repo */}
+ {isActive &&
write }
+
+ {/* Remove button: hidden by default, revealed on hover */}
+
{
+ e.stopPropagation();
+ onRemove();
+ }}
+ title={`Remove ${displayName} from context`}
+ >
+
+
+
+
+
+
+ {/* BranchPicker in external-anchor mode: dropdown opens immediately,
+ positioned from the branch button, fetches all branches from GitHub */}
+ {branchOpen && (
+
{
+ onBranchChange(newBranch);
+ setBranchOpen(false);
+ }}
+ onClose={() => setBranchOpen(false)}
+ />
+ )}
+
+ );
+}
diff --git a/frontend/components/ContextMeter.jsx b/frontend/components/ContextMeter.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..acd60eacba7cd48472354f9a60da54c2d7080fde
--- /dev/null
+++ b/frontend/components/ContextMeter.jsx
@@ -0,0 +1,410 @@
+// frontend/components/ContextMeter.jsx
+//
+// Small bottom-right control that shows the active LLM's context-window
+// utilisation. Collapsed: a single ⓘ icon (no number — keeps the UI
+// quiet during normal use). Expanded: a compact popover with the
+// breakdown, topology line, and a manual refresh button.
+//
+// Refresh model: lazy — fetched only when the popover opens, plus the
+// explicit ↻ button. Zero idle traffic.
+//
+// Token-count estimate flag: when the backend reports is_estimate=true
+// (Ollama / OllaBridge — no real tokenizer available) every number is
+// prefixed with ≈ so the imprecision is visible.
+//
+// Colours: GitPilot orange #D95C3D for ≥60% (warning), red #B91C1C for
+// ≥85% (saturated). No new dependencies; inline styles + a scoped
+//
+
+ = 60 && percent < 85 ? "1" : "0"}
+ data-sat={data && percent >= 85 ? "1" : "0"}
+ onClick={() => setOpen((v) => !v)}
+ title="Context window usage"
+ >
+ {"ⓘ"}
+
+
+ {open && (
+
+
Context window
+
+ {loading && !data && (
+
Loading…
+ )}
+ {error && error !== "disabled" && (
+
+ Couldn't load: {error}
+
+ )}
+
+ {data && (
+ <>
+
+ Provider
+ {data.provider}
+ Model
+ {data.model || "—"}
+ Topology
+ {data.topology}
+
+
+
+
+
+ {prefix}
+ {fmt(data.used)} / {fmt(data.context_window)}{" "}
+ ({percent.toFixed(1)}%)
+
+
+
+
|
+
|
+
|
+
|
+
|
+
+
+
+
|
+
+ {percent >= 85 && (
+
= 95 ? "1" : "0"}>
+ Context near saturation. Consider:
+
+ Resetting the conversation
+ Switching to a larger-context model
+ Reducing repository scope
+
+
+ )}
+
+
+ {estimate ? "Token counts are estimated" : "Token counts via tiktoken"}
+
+ {loading ? "…" : "↻ refresh"}
+
+
+ >
+ )}
+
+ )}
+
+ );
+}
diff --git a/frontend/components/CreatePRButton.jsx b/frontend/components/CreatePRButton.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..559eb9c277ceed34cb8a455eea1347189f52cf56
--- /dev/null
+++ b/frontend/components/CreatePRButton.jsx
@@ -0,0 +1,159 @@
+import React, { useState } from "react";
+
+/**
+ * CreatePRButton — Claude-Code-on-Web parity PR creation action.
+ *
+ * When clicked, pushes session changes to a new branch and opens a PR.
+ * Shows loading state and links to the created PR on GitHub.
+ */
+export default function CreatePRButton({
+ repo,
+ sessionId,
+ branch,
+ defaultBranch,
+ disabled,
+ onPRCreated,
+}) {
+ const [creating, setCreating] = useState(false);
+ const [prUrl, setPrUrl] = useState(null);
+ const [error, setError] = useState(null);
+
+ const handleCreate = async () => {
+ if (!repo || !branch || branch === defaultBranch) return;
+
+ setCreating(true);
+ setError(null);
+
+ try {
+ const token = localStorage.getItem("github_token");
+ const headers = {
+ "Content-Type": "application/json",
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
+ };
+
+ const owner = repo.full_name?.split("/")[0] || repo.owner;
+ const name = repo.full_name?.split("/")[1] || repo.name;
+
+ const res = await fetch(`/api/repos/${owner}/${name}/pulls`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ title: `[GitPilot] Changes from session ${sessionId ? sessionId.slice(0, 8) : branch}`,
+ head: branch,
+ base: defaultBranch || "main",
+ body: [
+ "## Summary",
+ "",
+ `Changes created by GitPilot AI assistant on branch \`${branch}\`.`,
+ "",
+ sessionId ? `Session ID: \`${sessionId}\`` : "",
+ "",
+ "---",
+ "*This PR was generated by [GitPilot](https://github.com/ruslanmv/gitpilot).*",
+ ]
+ .filter(Boolean)
+ .join("\n"),
+ }),
+ });
+
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.detail || "Failed to create PR");
+
+ const url = data.html_url || data.url;
+ setPrUrl(url);
+ onPRCreated?.({ pr_url: url, pr_number: data.number, branch });
+ } catch (err) {
+ setError(err.message);
+ } finally {
+ setCreating(false);
+ }
+ };
+
+ if (prUrl) {
+ return (
+
+
+
+
+
+
+
+ View PR on GitHub →
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+
+
+ {creating ? "Creating PR..." : "Create PR"}
+
+ {error && (
+
{error}
+ )}
+
+ );
+}
+
+const styles = {
+ btn: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ height: 38,
+ padding: "0 14px",
+ borderRadius: 8,
+ border: "1px solid rgba(16, 185, 129, 0.3)",
+ background: "rgba(16, 185, 129, 0.08)",
+ color: "#10B981",
+ fontSize: 13,
+ fontWeight: 600,
+ cursor: "pointer",
+ whiteSpace: "nowrap",
+ transition: "background-color 0.15s",
+ },
+ prLink: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ height: 38,
+ padding: "0 14px",
+ borderRadius: 8,
+ background: "rgba(16, 185, 129, 0.10)",
+ color: "#10B981",
+ fontSize: 13,
+ fontWeight: 600,
+ textDecoration: "none",
+ whiteSpace: "nowrap",
+ },
+ error: {
+ fontSize: 11,
+ color: "#EF4444",
+ marginTop: 4,
+ },
+};
diff --git a/frontend/components/DiffStats.jsx b/frontend/components/DiffStats.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..2460e6ef496ccc5e95b2159c698afda556a99734
--- /dev/null
+++ b/frontend/components/DiffStats.jsx
@@ -0,0 +1,59 @@
+import React from "react";
+
+/**
+ * DiffStats — Claude-Code-on-Web parity inline diff indicator.
+ *
+ * Clickable "+N -N in M files" badge that appears in agent messages.
+ * Clicking opens the DiffViewer overlay.
+ */
+export default function DiffStats({ diff, onClick }) {
+ if (!diff || (!diff.additions && !diff.deletions && !diff.files_changed)) {
+ return null;
+ }
+
+ return (
+
+
+
+
+
+ +{diff.additions || 0}
+ -{diff.deletions || 0}
+
+ in {diff.files_changed || (diff.files || []).length} file{(diff.files_changed || (diff.files || []).length) !== 1 ? "s" : ""}
+
+
+
+
+
+ );
+}
+
+const styles = {
+ container: {
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "5px 10px",
+ borderRadius: 6,
+ border: "1px solid #27272A",
+ backgroundColor: "rgba(24, 24, 27, 0.8)",
+ cursor: "pointer",
+ fontSize: 12,
+ fontFamily: "monospace",
+ color: "#A1A1AA",
+ transition: "border-color 0.15s, background-color 0.15s",
+ marginTop: 8,
+ },
+ additions: {
+ color: "#10B981",
+ fontWeight: 600,
+ },
+ deletions: {
+ color: "#EF4444",
+ fontWeight: 600,
+ },
+ files: {
+ color: "#71717A",
+ },
+};
diff --git a/frontend/components/DiffViewer.jsx b/frontend/components/DiffViewer.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..b1a05fbc9d3f4c52b40ab4cd075d42db99522663
--- /dev/null
+++ b/frontend/components/DiffViewer.jsx
@@ -0,0 +1,263 @@
+import React, { useState } from "react";
+
+/**
+ * DiffViewer — Claude-Code-on-Web parity diff overlay.
+ *
+ * Shows a file list on the left and unified diff on the right.
+ * Green = additions, red = deletions. Additive component.
+ */
+export default function DiffViewer({ diff, onClose }) {
+ const [selectedFile, setSelectedFile] = useState(0);
+
+ if (!diff || !diff.files || diff.files.length === 0) {
+ return (
+
+
+
+ Diff Viewer
+
+ ×
+
+
+
No changes to display.
+
+
+ );
+ }
+
+ const files = diff.files || [];
+ const currentFile = files[selectedFile] || files[0];
+
+ return (
+
+
+ {/* Header */}
+
+
+ Diff Viewer
+
+ +{diff.additions || 0}
+ {" "}
+ -{diff.deletions || 0}
+ {" in "}
+ {diff.files_changed || files.length} files
+
+
+
+ ×
+
+
+
+ {/* Body */}
+
+ {/* File list */}
+
+ {files.map((f, idx) => (
+
setSelectedFile(idx)}
+ >
+ {f.path}
+
+ +{f.additions || 0}
+ {" "}
+ -{f.deletions || 0}
+
+
+ ))}
+
+
+ {/* Diff content */}
+
+
{currentFile.path}
+
+ {(currentFile.hunks || []).map((hunk, hi) => (
+
+
{hunk.header || `@@ hunk ${hi + 1} @@`}
+ {(hunk.lines || []).map((line, li) => {
+ let bg = "transparent";
+ let color = "#D4D4D8";
+ if (line.startsWith("+")) {
+ bg = "rgba(16, 185, 129, 0.10)";
+ color = "#6EE7B7";
+ } else if (line.startsWith("-")) {
+ bg = "rgba(239, 68, 68, 0.10)";
+ color = "#FCA5A5";
+ }
+ return (
+
+ {line}
+
+ );
+ })}
+
+ ))}
+
+ {(!currentFile.hunks || currentFile.hunks.length === 0) && (
+
+ Diff content will appear here when the agent modifies files.
+
+ )}
+
+
+
+
+
+ );
+}
+
+const styles = {
+ overlay: {
+ position: "fixed",
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: "rgba(0, 0, 0, 0.7)",
+ zIndex: 200,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ panel: {
+ width: "90vw",
+ maxWidth: 1100,
+ height: "80vh",
+ backgroundColor: "#131316",
+ border: "1px solid #27272A",
+ borderRadius: 12,
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ },
+ header: {
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ padding: "12px 16px",
+ borderBottom: "1px solid #27272A",
+ backgroundColor: "#18181B",
+ },
+ headerLeft: {
+ display: "flex",
+ alignItems: "center",
+ gap: 12,
+ },
+ headerTitle: {
+ fontSize: 14,
+ fontWeight: 600,
+ color: "#E4E4E7",
+ },
+ statBadge: {
+ fontSize: 12,
+ color: "#A1A1AA",
+ },
+ closeBtn: {
+ width: 28,
+ height: 28,
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "transparent",
+ color: "#A1A1AA",
+ fontSize: 18,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ body: {
+ flex: 1,
+ display: "flex",
+ overflow: "hidden",
+ },
+ fileList: {
+ width: 240,
+ borderRight: "1px solid #27272A",
+ overflowY: "auto",
+ flexShrink: 0,
+ },
+ fileItem: {
+ padding: "8px 10px",
+ cursor: "pointer",
+ borderBottom: "1px solid rgba(39, 39, 42, 0.5)",
+ transition: "background-color 0.1s",
+ },
+ fileName: {
+ display: "block",
+ fontSize: 12,
+ fontFamily: "monospace",
+ color: "#E4E4E7",
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ },
+ fileStats: {
+ display: "block",
+ fontSize: 10,
+ marginTop: 2,
+ },
+ diffContent: {
+ flex: 1,
+ overflow: "auto",
+ display: "flex",
+ flexDirection: "column",
+ },
+ diffPath: {
+ padding: "8px 12px",
+ fontSize: 12,
+ fontFamily: "monospace",
+ color: "#A1A1AA",
+ borderBottom: "1px solid #27272A",
+ backgroundColor: "#18181B",
+ position: "sticky",
+ top: 0,
+ zIndex: 1,
+ },
+ diffCode: {
+ padding: "4px 0",
+ fontFamily: "monospace",
+ fontSize: 12,
+ lineHeight: 1.6,
+ },
+ hunkHeader: {
+ padding: "4px 12px",
+ color: "#6B7280",
+ backgroundColor: "rgba(59, 130, 246, 0.05)",
+ fontSize: 11,
+ fontStyle: "italic",
+ },
+ diffLine: {
+ padding: "0 12px",
+ whiteSpace: "pre",
+ },
+ diffPlaceholder: {
+ padding: 20,
+ textAlign: "center",
+ color: "#52525B",
+ fontSize: 13,
+ },
+ emptyState: {
+ flex: 1,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#52525B",
+ fontSize: 14,
+ },
+};
diff --git a/frontend/components/EnvironmentEditor.jsx b/frontend/components/EnvironmentEditor.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..eb0740eebff0280f3155f478ac7a2f437f251681
--- /dev/null
+++ b/frontend/components/EnvironmentEditor.jsx
@@ -0,0 +1,278 @@
+import React, { useState } from "react";
+import { createPortal } from "react-dom";
+
+/**
+ * EnvironmentEditor — Claude-Code-on-Web parity environment config modal.
+ *
+ * Allows setting name, network access level, and environment variables.
+ */
+export default function EnvironmentEditor({ environment, onSave, onDelete, onClose }) {
+ const [name, setName] = useState(environment?.name || "");
+ const [networkAccess, setNetworkAccess] = useState(environment?.network_access || "limited");
+ const [envVarsText, setEnvVarsText] = useState(
+ environment?.env_vars
+ ? Object.entries(environment.env_vars)
+ .map(([k, v]) => `${k}=${v}`)
+ .join("\n")
+ : ""
+ );
+
+ const handleSave = () => {
+ const envVars = {};
+ envVarsText
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line && line.includes("="))
+ .forEach((line) => {
+ const idx = line.indexOf("=");
+ const key = line.slice(0, idx).trim();
+ const val = line.slice(idx + 1).trim();
+ if (key) envVars[key] = val;
+ });
+
+ onSave({
+ id: environment?.id || null,
+ name: name.trim() || "Default",
+ network_access: networkAccess,
+ env_vars: envVars,
+ });
+ };
+
+ return createPortal(
+ { if (e.target === e.currentTarget) onClose(); }}>
+
e.stopPropagation()}>
+
+
+ {environment?.id ? "Edit Environment" : "New Environment"}
+
+
+ ×
+
+
+
+
+ {/* Name */}
+
Environment Name
+
setName(e.target.value)}
+ placeholder="e.g. Development, Staging, Production"
+ style={styles.input}
+ />
+
+ {/* Network Access */}
+
Network Access
+
+ {[
+ { value: "limited", label: "Limited", desc: "Allowlisted domains only (package managers, APIs)" },
+ { value: "full", label: "Full", desc: "Unrestricted internet access" },
+ { value: "none", label: "None", desc: "Air-gapped — no external network" },
+ ].map((opt) => (
+
+ setNetworkAccess(e.target.value)}
+ style={{ display: "none" }}
+ />
+
+
+ {opt.label}
+
+
+ {opt.desc}
+
+
+
+ ))}
+
+
+ {/* Environment Variables */}
+
Environment Variables
+
+
+
+ {onDelete && (
+
+ Delete
+
+ )}
+
+
+ Cancel
+
+
+ Save
+
+
+
+
,
+ document.body
+ );
+}
+
+const styles = {
+ overlay: {
+ position: "fixed",
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: "rgba(0, 0, 0, 0.6)",
+ zIndex: 10000,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ modal: {
+ width: 480,
+ maxHeight: "80vh",
+ backgroundColor: "#131316",
+ border: "1px solid #27272A",
+ borderRadius: 12,
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ },
+ header: {
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ padding: "14px 16px",
+ borderBottom: "1px solid #27272A",
+ backgroundColor: "#18181B",
+ },
+ headerTitle: {
+ fontSize: 14,
+ fontWeight: 600,
+ color: "#E4E4E7",
+ },
+ closeBtn: {
+ width: 26,
+ height: 26,
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "transparent",
+ color: "#A1A1AA",
+ fontSize: 16,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ body: {
+ padding: "16px",
+ overflowY: "auto",
+ flex: 1,
+ },
+ label: {
+ display: "block",
+ fontSize: 12,
+ fontWeight: 600,
+ color: "#A1A1AA",
+ marginBottom: 6,
+ marginTop: 14,
+ },
+ input: {
+ width: "100%",
+ padding: "8px 10px",
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "#18181B",
+ color: "#E4E4E7",
+ fontSize: 13,
+ outline: "none",
+ boxSizing: "border-box",
+ },
+ radioGroup: {
+ display: "flex",
+ flexDirection: "column",
+ gap: 6,
+ },
+ radioItem: {
+ display: "flex",
+ alignItems: "flex-start",
+ gap: 10,
+ padding: "8px 10px",
+ borderRadius: 6,
+ border: "1px solid #27272A",
+ cursor: "pointer",
+ transition: "border-color 0.15s, background-color 0.15s",
+ },
+ textarea: {
+ width: "100%",
+ padding: "8px 10px",
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "#18181B",
+ color: "#E4E4E7",
+ fontSize: 12,
+ fontFamily: "monospace",
+ outline: "none",
+ resize: "vertical",
+ boxSizing: "border-box",
+ },
+ footer: {
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "12px 16px",
+ borderTop: "1px solid #27272A",
+ },
+ cancelBtn: {
+ padding: "6px 14px",
+ borderRadius: 6,
+ border: "1px solid #3F3F46",
+ background: "transparent",
+ color: "#A1A1AA",
+ fontSize: 12,
+ cursor: "pointer",
+ },
+ saveBtn: {
+ padding: "6px 14px",
+ borderRadius: 6,
+ border: "none",
+ background: "#3B82F6",
+ color: "#fff",
+ fontSize: 12,
+ fontWeight: 600,
+ cursor: "pointer",
+ },
+ deleteBtn: {
+ padding: "6px 14px",
+ borderRadius: 6,
+ border: "1px solid rgba(239, 68, 68, 0.3)",
+ background: "transparent",
+ color: "#EF4444",
+ fontSize: 12,
+ cursor: "pointer",
+ },
+};
diff --git a/frontend/components/EnvironmentSelector.jsx b/frontend/components/EnvironmentSelector.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..c54e475a0c5715cc34ee1523aab9a2dc53bbe889
--- /dev/null
+++ b/frontend/components/EnvironmentSelector.jsx
@@ -0,0 +1,199 @@
+import React, { useEffect, useState } from "react";
+import EnvironmentEditor from "./EnvironmentEditor.jsx";
+
+/**
+ * EnvironmentSelector — Claude-Code-on-Web parity environment dropdown.
+ *
+ * Shows current environment name + gear icon. Gear opens the editor modal.
+ * Fetches environments from /api/environments.
+ */
+export default function EnvironmentSelector({ activeEnvId, onEnvChange }) {
+ const [envs, setEnvs] = useState([]);
+ const [editorOpen, setEditorOpen] = useState(false);
+ const [editingEnv, setEditingEnv] = useState(null);
+
+ const fetchEnvs = async () => {
+ try {
+ const res = await fetch("/api/environments", { cache: "no-cache" });
+ if (!res.ok) return;
+ const data = await res.json();
+ setEnvs(data.environments || []);
+ } catch (err) {
+ console.warn("Failed to fetch environments:", err);
+ }
+ };
+
+ useEffect(() => {
+ fetchEnvs();
+ }, []);
+
+ const activeEnv =
+ envs.find((e) => e.id === activeEnvId) || envs[0] || { name: "Default", id: "default" };
+
+ const handleSave = async (config) => {
+ try {
+ const method = config.id ? "PUT" : "POST";
+ const url = config.id ? `/api/environments/${config.id}` : "/api/environments";
+ await fetch(url, {
+ method,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(config),
+ });
+ await fetchEnvs();
+ setEditorOpen(false);
+ setEditingEnv(null);
+ } catch (err) {
+ console.warn("Failed to save environment:", err);
+ }
+ };
+
+ const handleDelete = async (envId) => {
+ try {
+ await fetch(`/api/environments/${envId}`, { method: "DELETE" });
+ await fetchEnvs();
+ if (activeEnvId === envId) {
+ onEnvChange?.(null);
+ }
+ } catch (err) {
+ console.warn("Failed to delete environment:", err);
+ }
+ };
+
+ return (
+
+
ENVIRONMENT
+
+
+ {/* Env selector */}
+ onEnvChange?.(e.target.value)}
+ style={styles.select}
+ >
+ {envs.map((env) => (
+
+ {env.name}
+
+ ))}
+
+
+ {/* Network badge */}
+
+ {activeEnv.network_access || "limited"}
+
+
+
+ {/* Gear icon */}
+
{
+ setEditingEnv(activeEnv);
+ setEditorOpen(true);
+ }}
+ title="Configure environment"
+ >
+
+
+
+
+
+
+ {/* Add new */}
+
{
+ setEditingEnv(null);
+ setEditorOpen(true);
+ }}
+ title="Add environment"
+ >
+ +
+
+
+
+ {/* Editor modal */}
+ {editorOpen && (
+
handleDelete(editingEnv.id) : null}
+ onClose={() => {
+ setEditorOpen(false);
+ setEditingEnv(null);
+ }}
+ />
+ )}
+
+ );
+}
+
+const styles = {
+ container: {
+ padding: "10px 14px",
+ },
+ label: {
+ fontSize: 10,
+ fontWeight: 700,
+ letterSpacing: "0.08em",
+ color: "#71717A",
+ textTransform: "uppercase",
+ marginBottom: 6,
+ },
+ row: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ },
+ envCard: {
+ flex: 1,
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "4px 8px",
+ borderRadius: 6,
+ border: "1px solid #27272A",
+ backgroundColor: "#18181B",
+ minWidth: 0,
+ },
+ select: {
+ flex: 1,
+ background: "transparent",
+ border: "none",
+ color: "#E4E4E7",
+ fontSize: 12,
+ fontWeight: 500,
+ outline: "none",
+ cursor: "pointer",
+ minWidth: 0,
+ },
+ networkBadge: {
+ fontSize: 9,
+ fontWeight: 600,
+ textTransform: "uppercase",
+ letterSpacing: "0.04em",
+ flexShrink: 0,
+ },
+ gearBtn: {
+ width: 28,
+ height: 28,
+ borderRadius: 6,
+ border: "1px solid #27272A",
+ background: "transparent",
+ color: "#71717A",
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ fontSize: 14,
+ flexShrink: 0,
+ },
+};
diff --git a/frontend/components/ExecutionPlanCard.jsx b/frontend/components/ExecutionPlanCard.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..e7f5cf9cf22f4ff54d82dee304b831e9c3a8ade4
--- /dev/null
+++ b/frontend/components/ExecutionPlanCard.jsx
@@ -0,0 +1,275 @@
+// frontend/components/ExecutionPlanCard.jsx
+//
+// The approval-first surface for sandbox runs. Renders a
+// deterministic ExecutionPlan returned by POST /api/sandbox/plan
+// and gates the actual run on an explicit user click.
+//
+// Two visual variants, same component:
+//
+// variant = "full" — used in chat for file-run and chat-command
+// plans. Big card, every safety check / warning
+// visible, primary CTA "Run in Sandbox".
+// variant = "compact" — used as a popover above a code-block ▶ click.
+// Same info, less chrome.
+//
+// The component is stateless about the run itself: it produces an
+// approval event (onApprove with the plan object) and lets the
+// parent decide how to execute. This keeps the streaming/state
+// machine work for Batch 3 — here we only render and consent.
+
+import React from "react";
+
+const SEVERITY_STYLE = {
+ high: { bg: "#3d1111", fg: "#fca5a5", border: "#7f1d1d", icon: "⛔" },
+ medium: { bg: "#3d2d11", fg: "#fde68a", border: "#854d0e", icon: "⚠" },
+ low: { bg: "#1f2937", fg: "#a5b4fc", border: "#3730a3", icon: "ⓘ" },
+};
+
+const BACKEND_LABELS = {
+ subprocess: "Local",
+ matrixlab: "MatrixLab",
+ off: "Pass-through",
+};
+
+export default function ExecutionPlanCard({
+ plan,
+ variant = "full",
+ busy = false,
+ onApprove,
+ onCancel,
+ onOpenFile,
+}) {
+ if (!plan) return null;
+ const isCompact = variant === "compact";
+ const styles = isCompact ? compactStyles : fullStyles;
+
+ const commandStr = Array.isArray(plan.command)
+ ? plan.command.join(" ")
+ : String(plan.command || "");
+
+ return (
+
+
+ EXECUTION PLAN
+ {plan.goal || "Run in sandbox"}
+
+
+
+ {plan.file && (
+ {plan.file}} />
+ )}
+ {commandStr}} />
+
+
+
+ {plan.workdir && plan.workdir !== "." && (
+ {plan.workdir}} />
+ )}
+
+
+ {/* Safety checks — always green, no opinion */}
+ {Array.isArray(plan.safety?.checks) && plan.safety.checks.length > 0 && (
+
+ {plan.safety.checks.map((c, i) => (
+
+ ✓
+ {c.label}
+
+ ))}
+
+ )}
+
+ {/* Warnings — non-blocking, sorted high → low by the backend */}
+ {Array.isArray(plan.safety?.warnings) && plan.safety.warnings.length > 0 && (
+
+ {plan.safety.warnings.map((w, i) => {
+ const st = SEVERITY_STYLE[w.severity] || SEVERITY_STYLE.low;
+ return (
+
+ {st.icon}
+
+ {w.label}
+ {w.detail && — {w.detail} }
+
+
+ );
+ })}
+
+ )}
+
+ {plan.inline_code && (
+
+
+ Snippet to run ({plan.inline_code.length} chars)
+
+ {plan.inline_code}
+
+ )}
+
+
+ onApprove?.(plan)}
+ disabled={busy}
+ autoFocus
+ >
+ {busy ? "Starting…" : "▶ Run in Sandbox"}
+
+ {plan.file && onOpenFile && (
+ onOpenFile(plan.file)}>
+ Open {plan.file.split("/").pop()}
+
+ )}
+ onCancel?.(plan)}
+ disabled={busy}
+ >
+ Cancel
+
+
+
+ );
+}
+
+function Field({ label, value }) {
+ return (
+ <>
+ {label}
+ {value}
+ >
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Approve helper — single source of truth so chat, codeblock, canvas
+// all build the plan the same way. Returns the plan object or throws.
+// ---------------------------------------------------------------------------
+
+export async function fetchExecutionPlan(payload) {
+ const res = await fetch("/api/sandbox/plan", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(data.detail || `Plan failed (HTTP ${res.status})`);
+ }
+ return data.plan;
+}
+
+// ---------------------------------------------------------------------------
+// Styles
+// ---------------------------------------------------------------------------
+
+const dtStyle = {
+ fontSize: 11, color: "#9092b5", textTransform: "uppercase",
+ letterSpacing: "0.05em", margin: 0,
+};
+const ddStyle = { margin: "0 0 6px", fontSize: 13, color: "#e4e4e7" };
+
+const fullStyles = {
+ card: {
+ margin: "8px 0",
+ background: "#0d1117",
+ border: "1px solid #1f2937",
+ borderLeft: "3px solid #10B981",
+ borderRadius: 10,
+ padding: 16,
+ color: "#e4e4e7",
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
+ },
+ header: { display: "flex", alignItems: "center", gap: 10, marginBottom: 10 },
+ badge: {
+ fontSize: 10, fontWeight: 700, letterSpacing: "0.06em",
+ padding: "2px 8px", borderRadius: 4,
+ background: "#0d3320", color: "#86efac", textTransform: "uppercase",
+ },
+ title: { margin: 0, fontSize: 15, fontWeight: 600 },
+ fields: {
+ display: "grid", gridTemplateColumns: "120px 1fr",
+ rowGap: 4, columnGap: 12, margin: "10px 0",
+ },
+ checks: {
+ listStyle: "none", padding: 0, margin: "8px 0",
+ display: "flex", flexWrap: "wrap", gap: 6,
+ },
+ check: {
+ fontSize: 11, color: "#86efac",
+ background: "rgba(16,185,129,0.08)",
+ border: "1px solid rgba(16,185,129,0.25)",
+ borderRadius: 4, padding: "2px 8px",
+ },
+ checkIcon: { marginRight: 4 },
+ warnings: { listStyle: "none", padding: 0, margin: "10px 0 4px" },
+ warning: {
+ fontSize: 12,
+ padding: "6px 10px", borderRadius: 4, border: "1px solid",
+ marginBottom: 4, display: "flex", gap: 8, alignItems: "flex-start",
+ },
+ warnIcon: { fontSize: 14, lineHeight: 1 },
+ warnDetail: { opacity: 0.8 },
+ snippetWrap: {
+ margin: "8px 0",
+ border: "1px solid #1f2937", borderRadius: 6, padding: "6px 10px",
+ },
+ snippetLabel: { fontSize: 11, color: "#9092b5", cursor: "pointer" },
+ snippet: {
+ margin: "6px 0 0", padding: 8, fontSize: 12,
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
+ background: "#000", color: "#d4d4d8", borderRadius: 4,
+ maxHeight: 240, overflow: "auto", whiteSpace: "pre-wrap",
+ },
+ footer: { display: "flex", gap: 8, marginTop: 12 },
+ primary: {
+ background: "#10B981", color: "#052e1c", border: "0",
+ borderRadius: 6, padding: "8px 16px", fontSize: 13, fontWeight: 600,
+ cursor: "pointer",
+ },
+ secondary: {
+ background: "transparent", color: "#a1a1aa",
+ border: "1px solid #3F3F46", borderRadius: 6,
+ padding: "7px 14px", fontSize: 13, cursor: "pointer",
+ },
+ tertiary: {
+ background: "transparent", color: "#71717a",
+ border: "1px solid #27272a", borderRadius: 6,
+ padding: "7px 14px", fontSize: 13, cursor: "pointer",
+ marginLeft: "auto",
+ },
+};
+
+// Compact variant — same structure, denser padding, no inline snippet
+// expander. Used for code-block Run confirmation popovers.
+const compactStyles = {
+ ...fullStyles,
+ card: {
+ ...fullStyles.card,
+ padding: 10,
+ margin: "6px 0",
+ borderRadius: 8,
+ },
+ title: { margin: 0, fontSize: 13, fontWeight: 600 },
+ fields: {
+ ...fullStyles.fields,
+ gridTemplateColumns: "90px 1fr",
+ rowGap: 2,
+ margin: "6px 0",
+ },
+ primary: { ...fullStyles.primary, padding: "6px 12px", fontSize: 12 },
+ secondary: { ...fullStyles.secondary, padding: "5px 10px", fontSize: 12 },
+ tertiary: { ...fullStyles.tertiary, padding: "5px 10px", fontSize: 12 },
+};
diff --git a/frontend/components/FilePreviewPanel.jsx b/frontend/components/FilePreviewPanel.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..6dd06d222cce882c28090f0df76d1c061476ad79
--- /dev/null
+++ b/frontend/components/FilePreviewPanel.jsx
@@ -0,0 +1,463 @@
+// frontend/components/FilePreviewPanel.jsx
+//
+// Read-first file viewer with two density modes.
+//
+// mode="preview" Narrow right-side drawer for a quick look.
+// ~520px wide, primary CTA "Prepare Run".
+// mode="workspace" Wide right-side editor for serious review.
+// ~85vw, same actions, much more reading room.
+//
+// Header vocabulary follows the enterprise verbs the design review
+// nailed down:
+//
+// [▶ Prepare Run] only on runnable files (hidden on README etc.)
+// [Open Workspace] upgrades preview → workspace (or back)
+// [⋯] overflow: Ask GitPilot · Open Canvas ·
+// Copy path · Copy contents
+//
+// "Prepare Run" never runs anything directly — it dispatches the
+// gitpilot:run-file event which lands on the green ExecutionPlanCard
+// in chat, where the user approves before the sandbox starts.
+//
+// Error state: when the file content fetch fails we hide every action
+// that depends on having content (Prepare Run / Canvas / Ask). Only
+// safe actions remain (Retry / Copy path).
+
+import React, { useEffect, useMemo, useRef, useState } from "react";
+
+const RUNNABLE_FILE_EXTS = new Set(["py", "js", "mjs", "cjs", "sh", "bash"]);
+
+const LANG_LABEL = {
+ py: "Python", js: "JavaScript", mjs: "JavaScript", cjs: "JavaScript",
+ sh: "Shell", bash: "Shell",
+ md: "Markdown", json: "JSON", yml: "YAML", yaml: "YAML", toml: "TOML",
+ html: "HTML", css: "CSS", ts: "TypeScript", tsx: "TypeScript",
+ rs: "Rust", go: "Go", java: "Java", c: "C", cpp: "C++", h: "C/C++",
+};
+
+function extOf(path) {
+ if (!path || !path.includes(".")) return "";
+ return path.split(".").pop().toLowerCase();
+}
+
+function bytesPretty(n) {
+ if (n == null) return "";
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / 1024 / 1024).toFixed(2)} MB`;
+}
+
+// ---------------------------------------------------------------------------
+// Overflow menu — secondary actions live here so the header stays calm.
+// ---------------------------------------------------------------------------
+
+function OverflowMenu({ path, content, runnable, onClose }) {
+ useEffect(() => {
+ const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
+ const onDown = () => onClose?.();
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("mousedown", onDown);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("mousedown", onDown);
+ };
+ }, [onClose]);
+
+ const copy = (text) => {
+ if (navigator?.clipboard && text != null) navigator.clipboard.writeText(text).catch(() => {});
+ };
+ const items = [
+ { label: "Ask GitPilot",
+ onClick: () => window.dispatchEvent(new CustomEvent("gitpilot:ask-about-file", { detail: { path } })) },
+ { label: "Open in Canvas", runnable: true,
+ onClick: () => window.dispatchEvent(new CustomEvent("gitpilot:open-in-canvas", { detail: { path } })) },
+ { divider: true },
+ { label: "Copy path", onClick: () => copy(path) },
+ { label: "Copy contents", onClick: () => copy(content), disabled: !content },
+ ];
+
+ return (
+ e.stopPropagation()}
+ style={{
+ position: "absolute", right: 6, top: 36, zIndex: 50,
+ minWidth: 200,
+ background: "#18181B", border: "1px solid #3F3F46",
+ borderRadius: 6, padding: "4px 0",
+ boxShadow: "0 8px 20px rgba(0,0,0,0.45)",
+ }}>
+ {items.map((it, i) => {
+ if (it.divider) return
;
+ if (it.runnable && !runnable) return null;
+ return (
+
{ e.stopPropagation(); it.onClick(); onClose?.(); }}
+ style={{
+ width: "100%", textAlign: "left",
+ background: "transparent",
+ color: it.disabled ? "#52525B" : "#E4E4E7",
+ border: "none",
+ padding: "6px 12px", fontSize: 12,
+ cursor: it.disabled ? "not-allowed" : "pointer",
+ }}
+ onMouseEnter={(e) => { if (!it.disabled) e.currentTarget.style.background = "#27272A"; }}
+ onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
+ >
+ {it.label}
+
+ );
+ })}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Main panel
+// ---------------------------------------------------------------------------
+
+export default function FilePreviewPanel({
+ path,
+ content,
+ loading,
+ error,
+ errorCode, // numeric HTTP status when known (e.g. 404)
+ notFoundKind, // "deleted" | "syncing" | "unavailable"
+ mode = "preview", // "preview" | "workspace"
+ branch,
+ onModeChange,
+ onClose,
+ onRetry,
+ onRefreshTree,
+}) {
+ const ext = extOf(path);
+ const lang = LANG_LABEL[ext] || ext.toUpperCase() || "Text";
+ const runnable = RUNNABLE_FILE_EXTS.has(ext);
+ const size = content ? new Blob([content]).size : null;
+ const filename = path ? path.split("/").pop() : "";
+ const [menuOpen, setMenuOpen] = useState(false);
+ const menuBtnRef = useRef(null);
+
+ // Esc closes — keyboard contract every modal/drawer in GitPilot uses.
+ useEffect(() => {
+ const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [onClose]);
+
+ const prepareRun = () => {
+ window.dispatchEvent(new CustomEvent("gitpilot:run-file", { detail: { path } }));
+ onClose?.();
+ };
+ const toggleWorkspace = () => {
+ if (onModeChange) onModeChange(mode === "workspace" ? "preview" : "workspace");
+ };
+
+ const lines = useMemo(() => (content || "").split("\n"), [content]);
+
+ // Width contract: preview = peek, workspace = serious reading.
+ const widthCss = mode === "workspace"
+ ? "min(1280px, 86vw)"
+ : "min(520px, 44vw)";
+
+ // Decide which actions to show. Two rules:
+ // 1. While loading, secondary actions exist but disabled.
+ // 2. On error, hide every action that requires content; we show
+ // Retry + Copy path only.
+ const showActions = !error;
+
+ return (
+
+
+
+
+
{filename || "Untitled"}
+
+ Path: {path}
+ {branch && (
+ <>
+ ·
+ Branch: {branch}
+ >
+ )}
+
+
+
+ {lang}
+ {size != null && {bytesPretty(size)} }
+
+ ✕
+
+
+
+
+
+ {showActions && runnable && (
+
+ ▶ Prepare Run
+
+ )}
+ {showActions && (
+
+ {mode === "workspace" ? "Collapse" : "Open Workspace"}
+
+ )}
+ {/* Error-only actions */}
+ {error && (
+
+ Retry
+
+ )}
+ {error && (
+
{
+ if (navigator?.clipboard && path) navigator.clipboard.writeText(path).catch(() => {});
+ }}
+ >
+ Copy path
+
+ )}
+
+ {/* Overflow menu — only on the happy path; on error we
+ already trimmed the safe-only action set above. */}
+ {showActions && (
+
+ e.stopPropagation()}
+ onClick={() => setMenuOpen((v) => !v)}
+ title="More actions"
+ >
+ ⋯
+
+ {menuOpen && (
+ setMenuOpen(false)}
+ />
+ )}
+
+ )}
+
+
+
+
+ {loading &&
Loading {path}…
}
+
+ {error && !loading && (
+
+ )}
+
+ {!loading && !error && (
+
+ {lines.map((line, i) => (
+
+ {i + 1}
+ {line || " "}
+
+ ))}
+
+ )}
+
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Calm empty state — replaces the harsh red "Couldn't load this file"
+// box. Same component, classifies the situation into one of:
+// deleted → execution removed the file from this branch
+// syncing → execution created the file but content isn't ready yet
+// unavailable → file simply isn't on this branch
+// ---------------------------------------------------------------------------
+
+function NotAvailableCard({ path, branch, error, errorCode, kind, onRetry, onRefreshTree }) {
+ const isNotFound =
+ errorCode === 404 ||
+ /not\s*found/i.test(String(error || "")) ||
+ /HTTP\s*404/i.test(String(error || ""));
+
+ const effectiveKind = isNotFound ? (kind || "unavailable") : "error";
+
+ const copy = {
+ deleted: {
+ icon: "🗑",
+ title: "File deleted",
+ body: `${path ? path.split("/").pop() : "This file"} was removed by the latest execution. View the execution summary for details.`,
+ tone: "muted",
+ },
+ syncing: {
+ icon: "↻",
+ title: "File still syncing",
+ body: "GitPilot just created this file. Its content is being published to the active branch — try again in a moment.",
+ tone: "info",
+ },
+ unavailable: {
+ icon: "○",
+ title: "File unavailable",
+ body: "This file isn't available on the current branch. It may have been moved, renamed, or never committed here.",
+ tone: "muted",
+ },
+ error: {
+ icon: "!",
+ title: "Couldn't load this file",
+ body: "Something went wrong fetching the file content. Try again, or refresh the file tree.",
+ tone: "warn",
+ },
+ }[effectiveKind];
+
+ return (
+
+
{copy.icon}
+
{copy.title}
+
{copy.body}
+
+
+ Path
+ {path}
+ {branch && (
+ <>
+ Branch
+ {branch}
+ >
+ )}
+
+
+
+
+ Retry
+
+ {onRefreshTree && (
+
+ Refresh files
+
+ )}
+ {
+ if (navigator?.clipboard && path) {
+ navigator.clipboard.writeText(path).catch(() => {});
+ }
+ }}
+ >
+ Copy path
+
+
+
+ {effectiveKind === "error" && error && (
+
+ Technical details
+ {String(error)}
+
+ )}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Styles
+// ---------------------------------------------------------------------------
+
+const s = {
+ shell: {
+ position: "fixed",
+ top: 0, right: 0, bottom: 0,
+ // ``width`` is set per-mode in the component.
+ background: "#0d0e17",
+ borderLeft: "1px solid #2a2b36",
+ display: "flex", flexDirection: "column",
+ zIndex: 90,
+ color: "#e4e4e7",
+ fontFamily: "system-ui, sans-serif",
+ boxShadow: "-12px 0 32px rgba(0,0,0,0.45)",
+ transition: "width 0.15s ease",
+ },
+ header: {
+ padding: "12px 16px 10px",
+ borderBottom: "1px solid #2a2b36",
+ background: "#14152a",
+ },
+ titleRow: { display: "flex", justifyContent: "space-between", gap: 12 },
+ filename: {
+ fontSize: 16, fontWeight: 600,
+ fontFamily: "ui-monospace, monospace",
+ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
+ },
+ subpath: {
+ fontSize: 11, color: "#9092b5", marginTop: 2,
+ fontFamily: "ui-monospace, monospace",
+ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
+ },
+ dot: { margin: "0 6px", color: "#52525B" },
+ metaPills: { display: "flex", alignItems: "flex-start", gap: 6, flexShrink: 0 },
+ pill: {
+ fontSize: 11, padding: "2px 8px", borderRadius: 4,
+ background: "#1e3a5f", color: "#93c5fd",
+ border: "1px solid #3B82F6",
+ },
+ pillDim: {
+ fontSize: 11, padding: "2px 8px", borderRadius: 4,
+ background: "#0d0e17", color: "#9092b5",
+ border: "1px solid #2c2d46",
+ },
+ actions: { display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap", alignItems: "center" },
+ btnPrimary: {
+ padding: "6px 14px", fontSize: 12, fontWeight: 600,
+ background: "#10B981", color: "#052e1c",
+ border: "0", borderRadius: 6, cursor: "pointer",
+ },
+ btnSecondary: {
+ padding: "6px 12px", fontSize: 12,
+ background: "transparent", color: "#c3c5dd",
+ border: "1px solid #2c2d46", borderRadius: 6, cursor: "pointer",
+ },
+ btnClose: {
+ marginLeft: 6,
+ padding: "2px 8px", fontSize: 14,
+ background: "transparent", color: "#9092b5",
+ border: "1px solid #2c2d46", borderRadius: 6, cursor: "pointer",
+ },
+ body: { flex: 1, overflow: "auto", padding: "12px 0" },
+ empty: { padding: 30, textAlign: "center", color: "#9092b5", fontSize: 13 },
+ code: {
+ margin: 0, padding: 0,
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
+ fontSize: 12.5, lineHeight: 1.55,
+ color: "#D4D4D8",
+ background: "transparent",
+ whiteSpace: "pre",
+ },
+ lineRow: { display: "grid", gridTemplateColumns: "48px 1fr", gap: 12, padding: "0 18px" },
+ lineNo: {
+ color: "#52525B", textAlign: "right",
+ userSelect: "none",
+ fontVariantNumeric: "tabular-nums",
+ },
+ lineCode: { whiteSpace: "pre-wrap", wordBreak: "break-word" },
+};
diff --git a/frontend/components/FileTree.jsx b/frontend/components/FileTree.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..bc5cb67284f109179bd154a5bac0d77ca15b61e5
--- /dev/null
+++ b/frontend/components/FileTree.jsx
@@ -0,0 +1,569 @@
+import React, { useState, useEffect } from "react";
+
+/**
+ * Simple recursive file tree viewer with refresh support
+ * Fetches tree data directly using the API.
+ */
+export default function FileTree({ repo, refreshTrigger, branch }) {
+ const [tree, setTree] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const [isSwitchingBranch, setIsSwitchingBranch] = useState(false);
+ const [error, setError] = useState(null);
+ const [localRefresh, setLocalRefresh] = useState(0);
+ // Search query for the in-sidebar filter. Empty string == no filter.
+ // Filter runs case-insensitively on path basenames *and* full paths
+ // so users can pinpoint a file even in deeply nested folders.
+ const [query, setQuery] = useState("");
+ // Which file is currently focused in the preview panel — populated
+ // by the ``gitpilot:file-opened`` event ChatPanel emits when the
+ // preview finishes loading. Drives the ◄ marker + active row tint.
+ const [selectedPath, setSelectedPath] = useState(null);
+
+ useEffect(() => {
+ const onOpened = (e) => setSelectedPath(e?.detail?.path || null);
+ const onClosed = () => setSelectedPath(null);
+ const onRefresh = () => setLocalRefresh((n) => n + 1);
+ window.addEventListener("gitpilot:file-opened", onOpened);
+ window.addEventListener("gitpilot:file-closed", onClosed);
+ window.addEventListener("gitpilot:refresh-tree", onRefresh);
+ return () => {
+ window.removeEventListener("gitpilot:file-opened", onOpened);
+ window.removeEventListener("gitpilot:file-closed", onClosed);
+ window.removeEventListener("gitpilot:refresh-tree", onRefresh);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!repo) return;
+
+ // Determine if this is a branch switch (we already have data)
+ const hasExistingData = tree.length > 0;
+ if (hasExistingData) {
+ setIsSwitchingBranch(true);
+ } else {
+ setLoading(true);
+ }
+ setError(null);
+
+ // Construct headers manually
+ let headers = {};
+ try {
+ const token = localStorage.getItem("github_token");
+ if (token) {
+ headers = { Authorization: `Bearer ${token}` };
+ }
+ } catch (e) {
+ console.warn("Unable to read github_token", e);
+ }
+
+ // Add cache busting + selected branch ref
+ const refParam = branch ? `&ref=${encodeURIComponent(branch)}` : "";
+ const cacheBuster = `?_t=${Date.now()}${refParam}`;
+
+ let cancelled = false;
+
+ fetch(`/api/repos/${repo.owner}/${repo.name}/tree${cacheBuster}`, { headers })
+ .then(async (res) => {
+ if (!res.ok) {
+ const errData = await res.json().catch(() => ({}));
+ throw new Error(errData.detail || "Failed to load files");
+ }
+ return res.json();
+ })
+ .then((data) => {
+ if (cancelled) return;
+ if (data.files && Array.isArray(data.files)) {
+ setTree(buildTree(data.files));
+ setError(null);
+ } else {
+ setError("No files found in repository");
+ }
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ setError(err.message);
+ console.error("FileTree error:", err);
+ })
+ .finally(() => {
+ if (cancelled) return;
+ setIsSwitchingBranch(false);
+ setLoading(false);
+ });
+
+ return () => { cancelled = true; };
+ }, [repo, branch, refreshTrigger, localRefresh]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const handleRefresh = () => {
+ setLocalRefresh(prev => prev + 1);
+ };
+
+ // Theme matching parent component
+ const theme = {
+ border: "#27272A",
+ textPrimary: "#EDEDED",
+ textSecondary: "#A1A1AA",
+ accent: "#D95C3D",
+ warningText: "#F59E0B",
+ warningBg: "rgba(245, 158, 11, 0.1)",
+ warningBorder: "rgba(245, 158, 11, 0.2)",
+ };
+
+ const styles = {
+ header: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "8px 20px 8px 10px",
+ marginBottom: "8px",
+ borderBottom: `1px solid ${theme.border}`,
+ },
+ headerTitle: {
+ fontSize: "12px",
+ fontWeight: "600",
+ color: theme.textSecondary,
+ textTransform: "uppercase",
+ letterSpacing: "0.5px",
+ },
+ refreshButton: {
+ backgroundColor: "transparent",
+ border: `1px solid ${theme.border}`,
+ color: theme.textSecondary,
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ cursor: loading ? "not-allowed" : "pointer",
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ transition: "all 0.2s",
+ opacity: loading ? 0.5 : 1,
+ },
+ switchingBar: {
+ padding: "6px 20px",
+ fontSize: "11px",
+ color: theme.textSecondary,
+ backgroundColor: "rgba(59, 130, 246, 0.06)",
+ borderBottom: `1px solid ${theme.border}`,
+ },
+ loadingText: {
+ padding: "0 20px",
+ color: theme.textSecondary,
+ fontSize: "13px",
+ },
+ errorBox: {
+ padding: "12px 20px",
+ color: theme.warningText,
+ fontSize: "12px",
+ backgroundColor: theme.warningBg,
+ border: `1px solid ${theme.warningBorder}`,
+ borderRadius: "6px",
+ margin: "0 10px",
+ },
+ emptyText: {
+ padding: "0 20px",
+ color: theme.textSecondary,
+ fontSize: "13px",
+ },
+ treeContainer: {
+ fontSize: "13px",
+ color: theme.textSecondary,
+ padding: "0 10px 20px 10px",
+ },
+ };
+
+ return (
+
+ {/* Header with Refresh Button */}
+
+
Files
+
{
+ if (!loading) {
+ e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.05)";
+ }
+ }}
+ onMouseOut={(e) => {
+ e.currentTarget.style.backgroundColor = "transparent";
+ }}
+ >
+
+
+
+ {loading ? "..." : "Refresh"}
+
+
+
+ {/* Branch switch indicator (shown above existing tree, doesn't clear it) */}
+ {isSwitchingBranch && (
+
Loading branch...
+ )}
+
+ {/* Content */}
+ {loading && tree.length === 0 && (
+
Loading files...
+ )}
+
+ {!loading && !isSwitchingBranch && error && (
+
{error}
+ )}
+
+ {!loading && !isSwitchingBranch && !error && tree.length === 0 && (
+
No files found
+ )}
+
+ {tree.length > 0 && (
+ <>
+ {/* In-sidebar file search. Enterprise repos run to hundreds
+ of files; the explorer needs a quick narrowing affordance
+ before any of the contextual menus matter. */}
+
setQuery(e.target.value)}
+ placeholder="🔍 Search files…"
+ spellCheck={false}
+ style={{
+ width: "100%", boxSizing: "border-box",
+ margin: "4px 0 8px",
+ padding: "6px 10px", fontSize: 12,
+ background: "#0d0e17", color: "#e4e4e7",
+ border: "1px solid #27272A", borderRadius: 6,
+ outline: "none",
+ fontFamily: "system-ui, sans-serif",
+ }}
+ />
+
+
+ {tree.map((node) => (
+
+ ))}
+
+ >
+ )}
+
+ );
+}
+
+// Files with these extensions get a "Prepare Run" menu item. Mirrors
+// the backend's _RUNNABLE_EXTENSIONS so the menu only offers a run
+// where the sandbox planner would actually accept the file.
+const RUNNABLE_FILE_EXTS = new Set(["py", "js", "mjs", "cjs", "sh", "bash"]);
+
+function isRunnableFile(name, type) {
+ if (type === "tree") return false;
+ if (!name || !name.includes(".")) return false;
+ const ext = name.split(".").pop().toLowerCase();
+ return RUNNABLE_FILE_EXTS.has(ext);
+}
+
+// Window-event dispatch helpers — keep FileTree decoupled from
+// ChatPanel. Same pattern as the existing approval-flow events.
+function dispatchOpenFile(path) {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:open-file", { detail: { path } }));
+ } catch (_e) { /* old browser */ }
+}
+function dispatchOpenInCanvas(path) {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:open-in-canvas", { detail: { path } }));
+ } catch (_e) { /* old browser */ }
+}
+function dispatchRunFile(path) {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:run-file", { detail: { path } }));
+ } catch (_e) { /* old browser */ }
+}
+function dispatchAskAboutFile(path) {
+ try {
+ window.dispatchEvent(new CustomEvent("gitpilot:ask-about-file", { detail: { path } }));
+ } catch (_e) { /* old browser */ }
+}
+function copyToClipboard(text) {
+ if (navigator?.clipboard) navigator.clipboard.writeText(text).catch(() => {});
+}
+
+// Tiny dropdown — positioned absolutely below the row's ⋯ trigger.
+// Closes on outside click or Escape. Built-in would be
+// faster to write but the visual contract for an enterprise file
+// explorer demands a real menu (icons, separators, descriptions).
+function FileActionsMenu({ path, runnable, onClose }) {
+ React.useEffect(() => {
+ const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
+ const onDown = () => onClose?.();
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("mousedown", onDown);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("mousedown", onDown);
+ };
+ }, [onClose]);
+
+ // Menu vocabulary maps 1:1 to the design's recommended verbs. "Open
+ // Preview" is the calm default; "Open Workspace" widens the panel
+ // for serious reading/editing; "Prepare Run…" surfaces the
+ // ExecutionPlanCard. Canvas (the runnable split editor) is moved
+ // to the overflow because it's the heaviest mode and shouldn't
+ // compete with Preview / Workspace for attention.
+ const items = [
+ { label: "Open Preview", onClick: () => dispatchOpenFile(path) },
+ {
+ label: "Open Workspace",
+ onClick: () => window.dispatchEvent(
+ new CustomEvent("gitpilot:open-workspace", { detail: { path } })
+ ),
+ },
+ {
+ label: "Prepare Run…",
+ onClick: () => dispatchRunFile(path),
+ runnable: true,
+ primary: true,
+ },
+ { divider: true },
+ { label: "Ask GitPilot", onClick: () => dispatchAskAboutFile(path) },
+ { label: "Open in Canvas", onClick: () => dispatchOpenInCanvas(path), runnable: true },
+ { label: "Copy path", onClick: () => copyToClipboard(path) },
+ ];
+
+ return (
+ e.stopPropagation()}
+ style={{
+ position: "absolute", right: 4, top: 22, zIndex: 50,
+ minWidth: 180,
+ background: "#18181B", border: "1px solid #3F3F46",
+ borderRadius: 6, padding: "4px 0",
+ boxShadow: "0 8px 20px rgba(0,0,0,0.45)",
+ fontFamily: "system-ui, sans-serif",
+ }}
+ >
+ {items.map((it, i) => {
+ if (it.divider) {
+ return
;
+ }
+ if (it.runnable && !runnable) return null;
+ return (
+
{ e.stopPropagation(); it.onClick(); onClose?.(); }}
+ style={{
+ width: "100%", textAlign: "left",
+ background: "transparent",
+ color: it.primary ? "#86efac" : "#E4E4E7",
+ border: "none",
+ padding: "6px 12px", fontSize: 12, cursor: "pointer",
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.background = "#27272A"}
+ onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
+ >
+ {it.label}
+
+ );
+ })}
+
+ );
+}
+
+// True when ``node`` or any descendant path/basename contains ``filter``.
+// Folders are rendered if any descendant matches so the filter looks
+// like a flat search even though the tree is recursive.
+function _matchesFilter(node, filter) {
+ if (!filter) return true;
+ const inThis =
+ (node.path && node.path.toLowerCase().includes(filter)) ||
+ (node.name && node.name.toLowerCase().includes(filter));
+ if (inThis) return true;
+ if (!node.children) return false;
+ return node.children.some((c) => _matchesFilter(c, filter));
+}
+
+// Recursive Node Component
+function TreeNode({ node, level, filter = "", selectedPath = null }) {
+ const [userExpanded, setUserExpanded] = useState(false);
+ const [hovered, setHovered] = useState(false);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const isFolder = node.children && node.children.length > 0;
+ const runnable = !isFolder && isRunnableFile(node.name, node.type);
+ const isSelected = !isFolder && selectedPath === node.path;
+
+ // Honor the filter: drop subtrees that don't match anywhere. When
+ // the filter is active, folders auto-expand so users see the matches
+ // without having to chase carets.
+ if (filter && !_matchesFilter(node, filter)) return null;
+ const expanded = userExpanded || Boolean(filter);
+
+ const icon = isFolder ? (expanded ? "📂" : "📁") : "📄";
+
+ const onRowClick = () => {
+ if (isFolder) setUserExpanded(!userExpanded);
+ else dispatchOpenFile(node.path);
+ };
+
+ return (
+
+
setHovered(true)}
+ onMouseLeave={() => { setHovered(false); /* menu closes on outside-click */ }}
+ style={{
+ padding: "4px 0",
+ paddingLeft: `${level * 12}px`,
+ paddingRight: 6,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ gap: "6px",
+ color: isFolder
+ ? "#EDEDED"
+ : (isSelected ? "#86efac" : "#D4D4D8"),
+ whiteSpace: "nowrap",
+ borderRadius: 4,
+ background: isSelected
+ ? "rgba(16,185,129,0.10)"
+ : (hovered ? "#1f1f23" : "transparent"),
+ borderLeft: isSelected ? "2px solid #10B981" : "2px solid transparent",
+ }}
+ title={isFolder ? "" : "Click to open · ⋯ for actions"}
+ >
+ {icon}
+
+ {node.name}
+
+ {/* Selected marker — orient users when scanning a long list. */}
+ {isSelected && (
+ ◄
+ )}
+
+ {/* Per-row ⋯ menu trigger — visible on hover only so the
+ list reads as a clean inventory at rest. */}
+ {!isFolder && hovered && (
+ e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation();
+ setMenuOpen((v) => !v);
+ }}
+ title="File actions"
+ style={{
+ background: "transparent",
+ border: "1px solid transparent",
+ color: "#A1A1AA",
+ cursor: "pointer",
+ fontSize: 14,
+ lineHeight: 1,
+ padding: "0 6px",
+ borderRadius: 4,
+ }}
+ >
+ ⋯
+
+ )}
+
+
+ {menuOpen && (
+
setMenuOpen(false)}
+ />
+ )}
+
+ {isFolder && expanded && (
+
+ {node.children.map(child => (
+
+ ))}
+
+ )}
+
+ );
+}
+
+// Helper to build tree structure from flat file list
+function buildTree(files) {
+ const root = [];
+
+ files.forEach(file => {
+ const parts = file.path.split('/');
+ let currentLevel = root;
+ let currentPath = "";
+
+ parts.forEach((part, idx) => {
+ currentPath = currentPath ? `${currentPath}/${part}` : part;
+
+ // Check if node exists at this level
+ let existingNode = currentLevel.find(n => n.name === part);
+
+ if (!existingNode) {
+ const newNode = {
+ name: part,
+ path: currentPath,
+ type: idx === parts.length - 1 ? file.type : 'tree',
+ children: []
+ };
+ currentLevel.push(newNode);
+ existingNode = newNode;
+ }
+
+ if (idx < parts.length - 1) {
+ currentLevel = existingNode.children;
+ }
+ });
+ });
+
+ // Sort folders first, then files
+ const sortNodes = (nodes) => {
+ nodes.sort((a, b) => {
+ const aIsFolder = a.children.length > 0;
+ const bIsFolder = b.children.length > 0;
+ if (aIsFolder && !bIsFolder) return -1;
+ if (!aIsFolder && bIsFolder) return 1;
+ return a.name.localeCompare(b.name);
+ });
+ nodes.forEach(n => {
+ if (n.children.length > 0) sortNodes(n.children);
+ });
+ };
+
+ sortNodes(root);
+ return root;
+}
\ No newline at end of file
diff --git a/frontend/components/FlowViewer.jsx b/frontend/components/FlowViewer.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..71ef1e0b71603c85dd38ed37b2e930ebf6405bde
--- /dev/null
+++ b/frontend/components/FlowViewer.jsx
@@ -0,0 +1,659 @@
+import React, { useEffect, useState, useCallback, useRef } from "react";
+import ReactFlow, { Background, Controls, MiniMap } from "reactflow";
+import "reactflow/dist/style.css";
+
+/* ------------------------------------------------------------------ */
+/* Node type → colour mapping */
+/* ------------------------------------------------------------------ */
+const NODE_COLOURS = {
+ agent: { border: "#ff7a3c", bg: "#20141a" },
+ router: { border: "#6c8cff", bg: "#141828" },
+ tool: { border: "#3a3b4d", bg: "#141821" },
+ tool_group: { border: "#3a3b4d", bg: "#141821" },
+ user: { border: "#4caf88", bg: "#14211a" },
+ output: { border: "#9c6cff", bg: "#1a1428" },
+};
+const DEFAULT_COLOUR = { border: "#3a3b4d", bg: "#141821" };
+
+function colourFor(type) {
+ return NODE_COLOURS[type] || DEFAULT_COLOUR;
+}
+
+const STYLE_COLOURS = {
+ single_task: "#6c8cff",
+ react_loop: "#ff7a3c",
+ crew_pipeline: "#4caf88",
+};
+
+const STYLE_LABELS = {
+ single_task: "Dispatch",
+ react_loop: "ReAct Loop",
+ crew_pipeline: "Pipeline",
+};
+
+/* ------------------------------------------------------------------ */
+/* TopologyCard — single clickable topology card */
+/* ------------------------------------------------------------------ */
+function TopologyCard({ topology, isActive, onClick }) {
+ const styleColor = STYLE_COLOURS[topology.execution_style] || "#9a9bb0";
+ const agentCount = topology.agents_used?.length || 0;
+
+ return (
+
+
+ {topology.icon}
+
+ {STYLE_LABELS[topology.execution_style] || topology.execution_style}
+
+
+
+ {topology.name}
+
+ {topology.description}
+
+ {agentCount} agent{agentCount !== 1 ? "s" : ""}
+
+
+ );
+}
+
+const cardStyles = {
+ card: {
+ display: "flex",
+ flexDirection: "column",
+ gap: 4,
+ padding: "10px 12px",
+ borderRadius: 8,
+ border: "1px solid #1e1f30",
+ cursor: "pointer",
+ textAlign: "left",
+ minWidth: 170,
+ maxWidth: 200,
+ flexShrink: 0,
+ transition: "border-color 0.2s, background-color 0.2s",
+ },
+ cardTop: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 6,
+ },
+ icon: {
+ fontSize: 18,
+ },
+ styleBadge: {
+ fontSize: 9,
+ fontWeight: 700,
+ textTransform: "uppercase",
+ letterSpacing: "0.05em",
+ padding: "1px 6px",
+ borderRadius: 4,
+ border: "1px solid",
+ },
+ name: {
+ fontSize: 12,
+ fontWeight: 600,
+ lineHeight: 1.3,
+ },
+ desc: {
+ fontSize: 10,
+ color: "#71717A",
+ lineHeight: 1.3,
+ overflow: "hidden",
+ display: "-webkit-box",
+ WebkitLineClamp: 2,
+ WebkitBoxOrient: "vertical",
+ },
+ agentCount: {
+ fontSize: 9,
+ color: "#52525B",
+ fontWeight: 600,
+ marginTop: 2,
+ },
+};
+
+/* ------------------------------------------------------------------ */
+/* TopologyPanel — card grid grouped by category */
+/* ------------------------------------------------------------------ */
+function TopologyPanel({
+ topologies,
+ activeTopology,
+ autoMode,
+ autoResult,
+ onSelect,
+ onToggleAuto,
+}) {
+ const systems = topologies.filter((t) => t.category === "system");
+ const pipelines = topologies.filter((t) => t.category === "pipeline");
+
+ return (
+
+ {/* Auto-detect toggle */}
+
+
+
+
+
+
+ Auto
+
+ {autoMode && autoResult && (
+
+ Detected: {autoResult.icon} {autoResult.name}
+ {autoResult.confidence != null && (
+
+ {" "}({Math.round(autoResult.confidence * 100)}%)
+
+ )}
+
+ )}
+
+
+ {/* System architectures */}
+
+
System Architectures
+
+ {systems.map((t) => (
+ onSelect(t.id)}
+ />
+ ))}
+
+
+
+ {/* Task pipelines */}
+
+
Task Pipelines
+
+ {pipelines.map((t) => (
+ onSelect(t.id)}
+ />
+ ))}
+
+
+
+ );
+}
+
+const panelStyles = {
+ root: {
+ padding: "8px 16px 12px",
+ borderBottom: "1px solid #1e1f30",
+ backgroundColor: "#08090e",
+ },
+ autoRow: {
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ marginBottom: 10,
+ },
+ autoBtn: {
+ display: "flex",
+ alignItems: "center",
+ gap: 5,
+ padding: "4px 10px",
+ borderRadius: 6,
+ border: "1px solid #27272A",
+ background: "transparent",
+ fontSize: 11,
+ fontWeight: 600,
+ cursor: "pointer",
+ transition: "border-color 0.15s, color 0.15s",
+ },
+ autoHint: {
+ fontSize: 11,
+ color: "#9a9bb0",
+ },
+ section: {
+ marginBottom: 8,
+ },
+ sectionLabel: {
+ fontSize: 9,
+ fontWeight: 700,
+ textTransform: "uppercase",
+ letterSpacing: "0.08em",
+ color: "#52525B",
+ marginBottom: 6,
+ },
+ cardRow: {
+ display: "flex",
+ gap: 8,
+ overflowX: "auto",
+ scrollbarWidth: "none",
+ paddingBottom: 2,
+ },
+};
+
+/* ------------------------------------------------------------------ */
+/* Main FlowViewer component */
+/* ------------------------------------------------------------------ */
+export default function FlowViewer() {
+ const [nodes, setNodes] = useState([]);
+ const [edges, setEdges] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState("");
+
+ // Topology state
+ const [topologies, setTopologies] = useState([]);
+ const [activeTopology, setActiveTopology] = useState(null);
+ const [topologyMeta, setTopologyMeta] = useState(null);
+
+ // Auto-detection state
+ const [autoMode, setAutoMode] = useState(false);
+ const [autoResult, setAutoResult] = useState(null);
+ const [autoTestMessage, setAutoTestMessage] = useState("");
+
+ const initialLoadDone = useRef(false);
+
+ /* ---------- Load topology list on mount ---------- */
+ useEffect(() => {
+ (async () => {
+ try {
+ const [topoRes, prefRes] = await Promise.all([
+ fetch("/api/flow/topologies"),
+ fetch("/api/settings/topology"),
+ ]);
+ if (topoRes.ok) {
+ const data = await topoRes.json();
+ setTopologies(data);
+ }
+ if (prefRes.ok) {
+ const { topology } = await prefRes.json();
+ if (topology) {
+ setActiveTopology(topology);
+ }
+ }
+ } catch (e) {
+ console.warn("Failed to load topologies:", e);
+ }
+ initialLoadDone.current = true;
+ })();
+ }, []);
+
+ /* ---------- Load graph when topology changes ---------- */
+ const loadGraph = useCallback(async (topologyId) => {
+ setLoading(true);
+ setError("");
+ try {
+ const url = topologyId
+ ? `/api/flow/current?topology=${encodeURIComponent(topologyId)}`
+ : "/api/flow/current";
+ const res = await fetch(url);
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || "Failed to load flow");
+
+ // Track topology metadata from response
+ if (data.topology_id) {
+ setTopologyMeta({
+ id: data.topology_id,
+ name: data.topology_name,
+ icon: data.topology_icon,
+ description: data.topology_description,
+ execution_style: data.execution_style,
+ agents_used: topologies.find((t) => t.id === data.topology_id)?.agents_used || [],
+ });
+ }
+
+ // Build ReactFlow nodes
+ const RFnodes = data.nodes.map((n, i) => {
+ const nodeType = n.type || "default";
+ const colour = colourFor(nodeType);
+ const d = n.data || {};
+
+ const label = d.label || n.label || n.id;
+ const description = d.description || n.description || "";
+ const model = d.model;
+ const mode = d.mode;
+
+ const pos = n.position || {
+ x: 50 + (i % 3) * 250,
+ y: 50 + Math.floor(i / 3) * 180,
+ };
+
+ return {
+ id: n.id,
+ data: {
+ label: (
+
+
+ {label}
+
+ {model && (
+
+ {model}
+
+ )}
+ {mode && (
+
+ {mode}
+
+ )}
+
+ {description}
+
+
+ ),
+ },
+ position: pos,
+ type: "default",
+ style: {
+ borderRadius: 12,
+ padding: "12px 16px",
+ border: `2px solid ${colour.border}`,
+ background: colour.bg,
+ color: "#f5f5f7",
+ fontSize: 13,
+ minWidth: 180,
+ maxWidth: 220,
+ },
+ };
+ });
+
+ // Build ReactFlow edges
+ const RFedges = data.edges.map((e) => ({
+ id: e.id,
+ source: e.source,
+ target: e.target,
+ label: e.label,
+ animated: e.animated !== false,
+ style: { stroke: "#7a7b8e", strokeWidth: 2 },
+ labelStyle: { fill: "#c3c5dd", fontSize: 11, fontWeight: 500 },
+ labelBgStyle: { fill: "#101117", fillOpacity: 0.9 },
+ ...(e.type === "bidirectional" && {
+ markerEnd: { type: "arrowclosed", color: "#7a7b8e" },
+ markerStart: { type: "arrowclosed", color: "#7a7b8e" },
+ animated: false,
+ style: { stroke: "#555670", strokeWidth: 1.5, strokeDasharray: "5 5" },
+ }),
+ }));
+
+ setNodes(RFnodes);
+ setEdges(RFedges);
+ } catch (e) {
+ console.error(e);
+ setError(e.message);
+ } finally {
+ setLoading(false);
+ }
+ }, [topologies]);
+
+ // Load graph whenever activeTopology changes
+ useEffect(() => {
+ loadGraph(activeTopology);
+ }, [activeTopology, loadGraph]);
+
+ /* ---------- Topology selection handler ---------- */
+ const handleTopologyChange = useCallback(
+ async (newTopologyId) => {
+ setActiveTopology(newTopologyId);
+ setAutoMode(false); // Manual selection disables auto
+ // Persist preference (fire-and-forget)
+ try {
+ await fetch("/api/settings/topology", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ topology: newTopologyId }),
+ });
+ } catch (e) {
+ console.warn("Failed to save topology preference:", e);
+ }
+ },
+ []
+ );
+
+ /* ---------- Auto-detection ---------- */
+ const handleToggleAuto = useCallback(() => {
+ setAutoMode((prev) => !prev);
+ if (!autoMode) {
+ setAutoResult(null);
+ }
+ }, [autoMode]);
+
+ const handleAutoClassify = useCallback(
+ async (message) => {
+ if (!message.trim()) return;
+ try {
+ const res = await fetch("/api/flow/classify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ message }),
+ });
+ if (!res.ok) return;
+ const data = await res.json();
+ const recommendedId = data.recommended_topology;
+ const topo = topologies.find((t) => t.id === recommendedId);
+ setAutoResult({
+ id: recommendedId,
+ name: topo?.name || recommendedId,
+ icon: topo?.icon || "",
+ confidence: data.confidence,
+ alternatives: data.alternatives || [],
+ });
+ setActiveTopology(recommendedId);
+ } catch (e) {
+ console.warn("Auto-classify failed:", e);
+ }
+ },
+ [topologies]
+ );
+
+ // Debounced auto-classify when test message changes
+ useEffect(() => {
+ if (!autoMode || !autoTestMessage.trim()) return;
+ const t = setTimeout(() => handleAutoClassify(autoTestMessage), 500);
+ return () => clearTimeout(t);
+ }, [autoTestMessage, autoMode, handleAutoClassify]);
+
+ /* ---------- Render ---------- */
+ const activeStyleColor = STYLE_COLOURS[topologyMeta?.execution_style] || "#9a9bb0";
+
+ return (
+
+ {/* Header */}
+
+
+
Agent Workflow
+
+ Visual view of the multi-agent system that GitPilot uses to
+ plan and apply changes to your repositories.
+
+
+
+ {topologyMeta && (
+
+ {topologyMeta.icon}
+ {topologyMeta.name}
+
+ {STYLE_LABELS[topologyMeta.execution_style] || topologyMeta.execution_style}
+
+ {topologyMeta.agents_used?.length || 0} agents
+
+ )}
+ {loading &&
Loading... }
+
+
+
+ {/* Topology selector panel */}
+ {topologies.length > 0 && (
+
+ )}
+
+ {/* Auto-detection test input (shown when auto mode is on) */}
+ {autoMode && (
+
+
+ Test auto-detection: type a task description to see which topology is recommended
+
+
setAutoTestMessage(e.target.value)}
+ style={autoInputStyles.input}
+ />
+ {autoResult && autoResult.alternatives?.length > 0 && (
+
+ Alternatives:
+ {autoResult.alternatives.slice(0, 3).map((alt) => {
+ const altTopo = topologies.find((t) => t.id === alt.id);
+ return (
+ handleTopologyChange(alt.id)}
+ >
+ {altTopo?.icon} {altTopo?.name || alt.id}
+
+ {alt.confidence != null ? ` ${Math.round(alt.confidence * 100)}%` : ""}
+
+
+ );
+ })}
+
+ )}
+
+ )}
+
+ {/* Description bar */}
+ {topologyMeta && topologyMeta.description && !autoMode && (
+
+ {topologyMeta.icon} {topologyMeta.description}
+
+ )}
+
+ {/* ReactFlow canvas */}
+
+ {error ? (
+
+ ) : (
+
+
+ {
+ const border = node.style?.border || "";
+ if (border.includes("#ff7a3c")) return "#ff7a3c";
+ if (border.includes("#6c8cff")) return "#6c8cff";
+ if (border.includes("#4caf88")) return "#4caf88";
+ if (border.includes("#9c6cff")) return "#9c6cff";
+ return "#3a3b4d";
+ }}
+ maskColor="rgba(0, 0, 0, 0.6)"
+ />
+
+
+ )}
+
+
+ );
+}
+
+const autoInputStyles = {
+ wrap: {
+ padding: "8px 16px 10px",
+ borderBottom: "1px solid #1e1f30",
+ backgroundColor: "#0c0d14",
+ },
+ label: {
+ fontSize: 10,
+ color: "#71717A",
+ marginBottom: 6,
+ },
+ input: {
+ width: "100%",
+ padding: "8px 12px",
+ borderRadius: 6,
+ border: "1px solid #27272A",
+ background: "#08090e",
+ color: "#e0e1f0",
+ fontSize: 12,
+ fontFamily: "monospace",
+ outline: "none",
+ boxSizing: "border-box",
+ },
+ altRow: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ marginTop: 6,
+ flexWrap: "wrap",
+ },
+ altBtn: {
+ padding: "2px 8px",
+ borderRadius: 4,
+ border: "1px solid #27272A",
+ background: "transparent",
+ color: "#9a9bb0",
+ fontSize: 10,
+ cursor: "pointer",
+ },
+};
diff --git a/frontend/components/Footer.jsx b/frontend/components/Footer.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..71e8a0bca926c639c885bde541d6b3f7c9c10fbd
--- /dev/null
+++ b/frontend/components/Footer.jsx
@@ -0,0 +1,48 @@
+import React from "react";
+
+export default function Footer() {
+ return (
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/components/LlmSettings.jsx b/frontend/components/LlmSettings.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..e90b2180af222ad7fda08a9cd18852ed806eaf44
--- /dev/null
+++ b/frontend/components/LlmSettings.jsx
@@ -0,0 +1,623 @@
+import React, { useEffect, useMemo, useState } from "react";
+import { testProvider } from "../utils/api";
+
+const PROVIDERS = ["ollabridge", "openai", "claude", "watsonx", "ollama"];
+
+const PROVIDER_LABELS = {
+ ollabridge: "OllaBridge Cloud",
+ openai: "OpenAI",
+ claude: "Claude",
+ watsonx: "Watsonx",
+ ollama: "Ollama",
+};
+
+const AUTH_MODES = [
+ { id: "device", label: "Device Pairing", icon: "📱" },
+ { id: "apikey", label: "API Key", icon: "🔑" },
+ { id: "local", label: "Local Trust", icon: "🏠" },
+];
+
+function LoadingState({ loadingMessage, loadingSlow, onRetry }) {
+ return (
+
+
+
+
AI Providers
+
Admin / LLM Settings
+
{loadingMessage}
+
+ {loadingSlow && (
+
+
+ This is taking longer than expected. The backend may still be
+ starting or the settings endpoint may be slow.
+
+
+ Retry
+
+
+ )}
+
+
+ );
+}
+
+export default function LlmSettings() {
+ const [settings, setSettings] = useState(null);
+ const [initialLoading, setInitialLoading] = useState(true);
+ const [loadingSlow, setLoadingSlow] = useState(false);
+
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+ const [savedMsg, setSavedMsg] = useState("");
+
+ const [modelsByProvider, setModelsByProvider] = useState({});
+ const [modelsError, setModelsError] = useState("");
+ const [loadingModelsFor, setLoadingModelsFor] = useState("");
+
+ const [testResult, setTestResult] = useState(null);
+ const [testing, setTesting] = useState(false);
+
+ const [authMode, setAuthMode] = useState("local");
+ const [pairCode, setPairCode] = useState("");
+ const [pairing, setPairing] = useState(false);
+ const [pairResult, setPairResult] = useState(null);
+
+ const loadingMessage = useMemo(() => {
+ if (loadingSlow) {
+ return "Still loading provider configuration…";
+ }
+ return "Loading current configuration…";
+ }, [loadingSlow]);
+
+ const loadSettings = async () => {
+ setInitialLoading(true);
+ setError("");
+ setLoadingSlow(false);
+
+ let slowTimer;
+ try {
+ slowTimer = window.setTimeout(() => {
+ setLoadingSlow(true);
+ }, 1500);
+
+ const res = await fetch("/api/settings");
+ const data = await res.json();
+
+ if (!res.ok) {
+ throw new Error(data.error || "Failed to load settings");
+ }
+
+ setSettings(data);
+ } catch (e) {
+ console.error(e);
+ setError(e.message || "Failed to load settings");
+ } finally {
+ window.clearTimeout(slowTimer);
+ setInitialLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ loadSettings();
+ }, []);
+
+ const updateField = (section, field, value) => {
+ setSettings((prev) => ({
+ ...prev,
+ [section]: {
+ ...prev[section],
+ [field]: value,
+ },
+ }));
+ };
+
+ const handleSave = async () => {
+ setSaving(true);
+ setError("");
+ setSavedMsg("");
+
+ try {
+ const res = await fetch("/api/settings/llm", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(settings),
+ });
+
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || "Failed to save settings");
+
+ setSettings(data);
+ setSavedMsg("Settings saved successfully!");
+ setTimeout(() => setSavedMsg(""), 3000);
+ } catch (e) {
+ console.error(e);
+ setError(e.message || "Failed to save settings");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const loadModelsForProvider = async (provider) => {
+ setModelsError("");
+ setLoadingModelsFor(provider);
+
+ try {
+ const res = await fetch(`/api/settings/models?provider=${provider}`);
+ const data = await res.json();
+
+ if (!res.ok || data.error) {
+ throw new Error(data.error || "Failed to load models");
+ }
+
+ setModelsByProvider((prev) => ({
+ ...prev,
+ [provider]: data.models || [],
+ }));
+ } catch (e) {
+ console.error(e);
+ setModelsError(e.message || "Failed to load models");
+ } finally {
+ setLoadingModelsFor("");
+ }
+ };
+
+ const handlePair = async () => {
+ if (!pairCode.trim()) return;
+
+ setPairing(true);
+ setPairResult(null);
+
+ try {
+ const baseUrl =
+ settings?.ollabridge?.base_url || "https://ruslanmv-ollabridge.hf.space";
+
+ const res = await fetch("/api/ollabridge/pair", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ base_url: baseUrl, code: pairCode.trim() }),
+ });
+
+ const data = await res.json();
+
+ if (data.success) {
+ setPairResult({ ok: true, message: "Paired successfully!" });
+ if (data.token) {
+ updateField("ollabridge", "api_key", data.token);
+ }
+ } else {
+ setPairResult({
+ ok: false,
+ message: data.error || "Pairing failed",
+ });
+ }
+ } catch (e) {
+ setPairResult({ ok: false, message: e.message || "Pairing failed" });
+ } finally {
+ setPairing(false);
+ }
+ };
+
+ const handleTestConnection = async () => {
+ setTesting(true);
+ setTestResult(null);
+
+ try {
+ const activeProvider = settings?.provider || "ollama";
+ const config = { provider: activeProvider };
+
+ if (activeProvider === "openai" && settings?.openai) {
+ config.openai = {
+ api_key: settings.openai.api_key,
+ base_url: settings.openai.base_url,
+ model: settings.openai.model,
+ };
+ } else if (activeProvider === "claude" && settings?.claude) {
+ config.claude = {
+ api_key: settings.claude.api_key,
+ base_url: settings.claude.base_url,
+ model: settings.claude.model,
+ };
+ } else if (activeProvider === "watsonx" && settings?.watsonx) {
+ config.watsonx = {
+ api_key: settings.watsonx.api_key,
+ project_id: settings.watsonx.project_id,
+ base_url: settings.watsonx.base_url,
+ model_id: settings.watsonx.model_id,
+ };
+ } else if (activeProvider === "ollama" && settings?.ollama) {
+ config.ollama = {
+ base_url: settings.ollama.base_url,
+ model: settings.ollama.model,
+ };
+ } else if (activeProvider === "ollabridge" && settings?.ollabridge) {
+ config.ollabridge = {
+ base_url: settings.ollabridge.base_url,
+ model: settings.ollabridge.model,
+ api_key: settings.ollabridge.api_key,
+ };
+ }
+
+ const result = await testProvider(config);
+ setTestResult(result);
+ } catch (err) {
+ setTestResult({
+ health: "error",
+ warning: err.message || "Test failed",
+ });
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ if (initialLoading) {
+ return (
+
+ );
+ }
+
+ if (!settings) {
+ return (
+
+
+
AI Providers
+
Admin / LLM Settings
+
+ {error || "Unable to load current configuration."}
+
+
+ Retry
+
+
+
+ );
+ }
+
+ const { provider } = settings;
+ const availableModels = modelsByProvider[provider] || [];
+
+ return (
+
+
AI Providers
+
+ Choose which LLM provider GitPilot should use for planning and agent
+ workflows. Provider settings are stored on the server.
+
+
+ {error &&
{error}
}
+ {savedMsg &&
{savedMsg}
}
+
+
+
Active provider
+
+ {PROVIDERS.map((p) => (
+ setSettings((prev) => ({ ...prev, provider: p }))}
+ >
+ {PROVIDER_LABELS[p] || p}
+
+ ))}
+
+
+
+ {provider === "ollabridge" && (
+
+
OllaBridge Cloud Configuration
+
+ Connect to OllaBridge Cloud or any OllaBridge instance for LLM
+ inference. No API key required for public endpoints.
+
+
+
Authentication Mode
+
+ {AUTH_MODES.map((m) => (
+ setAuthMode(m.id)}
+ >
+ {m.icon}
+ {m.label}
+
+ ))}
+
+
+ {authMode === "device" && (
+
+
+ Enter the pairing code from your OllaBridge console and click
+ Pair.
+
+
+ setPairCode(e.target.value.toUpperCase())}
+ onKeyDown={(e) => e.key === "Enter" && handlePair()}
+ />
+
+ {pairing ? "Pairing…" : "Pair"}
+
+
+ {pairResult && (
+
+ {pairResult.message}
+
+ )}
+
+ )}
+
+
Base URL
+
+ updateField("ollabridge", "base_url", e.target.value)
+ }
+ placeholder="https://your-ollabridge-endpoint"
+ />
+
+ {(authMode === "apikey" || authMode === "local") && (
+ <>
+
API Key
+
+ updateField("ollabridge", "api_key", e.target.value)
+ }
+ placeholder="Optional API key"
+ />
+ >
+ )}
+
+
Model
+
+
+ updateField("ollabridge", "model", e.target.value)
+ }
+ placeholder="qwen2.5:1.5b"
+ />
+ loadModelsForProvider("ollabridge")}
+ disabled={loadingModelsFor === "ollabridge"}
+ >
+ {loadingModelsFor === "ollabridge" ? "Loading…" : "Load Models"}
+
+
+
+ )}
+
+ {provider === "openai" && (
+
+
OpenAI Configuration
+
+
API Key
+
updateField("openai", "api_key", e.target.value)}
+ placeholder="sk-..."
+ />
+
+
Base URL
+
updateField("openai", "base_url", e.target.value)}
+ placeholder="Optional custom base URL"
+ />
+
+
Model
+
updateField("openai", "model", e.target.value)}
+ placeholder="gpt-4o-mini"
+ />
+
+ )}
+
+ {provider === "claude" && (
+
+
Claude Configuration
+
+
API Key
+
updateField("claude", "api_key", e.target.value)}
+ placeholder="Anthropic API key"
+ />
+
+
Base URL
+
updateField("claude", "base_url", e.target.value)}
+ placeholder="Optional custom base URL"
+ />
+
+
Model
+
updateField("claude", "model", e.target.value)}
+ placeholder="claude-sonnet-4-5"
+ />
+
+ )}
+
+ {provider === "watsonx" && (
+
+ )}
+
+ {provider === "ollama" && (
+
+
Ollama Configuration
+
+
Base URL
+
updateField("ollama", "base_url", e.target.value)}
+ placeholder="http://localhost:11434"
+ />
+
+
Model
+
+ updateField("ollama", "model", e.target.value)}
+ placeholder="llama3"
+ />
+ loadModelsForProvider("ollama")}
+ disabled={loadingModelsFor === "ollama"}
+ >
+ {loadingModelsFor === "ollama" ? "Loading…" : "Load Models"}
+
+
+
+ )}
+
+ {availableModels.length > 0 && (
+
+
Available Models
+
+ {availableModels.map((model) => (
+ updateField(provider, "model", model)}
+ >
+ {model}
+
+ ))}
+
+
+ )}
+
+ {modelsError &&
{modelsError}
}
+
+ {testResult && (
+
+ {testResult.health === "ok"
+ ? testResult.details || "Provider connection successful."
+ : testResult.warning || "Provider connection failed."}
+
+ )}
+
+
+
+ {saving ? "Saving…" : "Save Settings"}
+
+
+
+ {testing ? "Testing…" : "Test Connection"}
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/components/LoginPage.jsx b/frontend/components/LoginPage.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..9d0fd67d1300c080de52c6ce91b0e03a0ce503dc
--- /dev/null
+++ b/frontend/components/LoginPage.jsx
@@ -0,0 +1,544 @@
+// frontend/components/LoginPage.jsx
+import React, { useState, useEffect, useRef } from "react";
+import { apiUrl, safeFetchJSON } from "../utils/api.js";
+import { initApp } from "../utils/appInit.js";
+
+/**
+ * GitPilot – Enterprise Agentic Login
+ * Theme: "Claude Code" / Anthropic Enterprise (Dark + Warm Orange)
+ */
+
+export default function LoginPage({ onAuthenticated, backendReady = false }) {
+ // Auth State
+ const [authProcessing, setAuthProcessing] = useState(false);
+ const [error, setError] = useState("");
+
+ // Mode State: 'loading' | 'web' (Has Secret) | 'device' (No Secret)
+ const [mode, setMode] = useState("loading");
+
+ // Device Flow State
+ const [deviceData, setDeviceData] = useState(null);
+ const pollTimer = useRef(null);
+ const stopPolling = useRef(false); // Flag to safely stop async polling
+
+ // Web Flow State
+ const [missingClientId, setMissingClientId] = useState(false);
+
+ // REF FIX: Prevents React StrictMode from running the auth exchange twice
+ const processingRef = useRef(false);
+ const authCheckDone = useRef(false);
+
+ // 1. Initialization Effect — runs once on mount AND when backendReady changes
+ useEffect(() => {
+ // Skip if already resolved
+ if (authCheckDone.current && mode !== "loading") return;
+
+ const params = new URLSearchParams(window.location.search);
+ const code = params.get("code");
+ const state = params.get("state");
+
+ // A. If returning from GitHub (Web Flow Callback)
+ if (code) {
+ if (!processingRef.current) {
+ processingRef.current = true;
+ setMode("web");
+ consumeOAuthCallback(code, state);
+ }
+ return;
+ }
+
+ // B. Use the shared singleton init — reuses App.jsx's result.
+ // No duplicate /api/auth/status calls, no separate retry loops.
+ initApp().then((result) => {
+ authCheckDone.current = true;
+ if (result.ready) {
+ setError("");
+ setMode(result.authMode === "web" ? "web" : "device");
+ } else {
+ // Backend unreachable — allow device flow as fallback
+ setError(result.error || "Backend unavailable");
+ setMode("device");
+ }
+ });
+
+ // Cleanup polling on unmount
+ return () => {
+ stopPolling.current = true;
+ if (pollTimer.current) clearTimeout(pollTimer.current);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [backendReady]);
+
+ // ===========================================================================
+ // WEB FLOW LOGIC (Standard OAuth2)
+ // ===========================================================================
+
+ async function consumeOAuthCallback(code, state) {
+ const expectedState = sessionStorage.getItem("gitpilot_oauth_state");
+ if (state && expectedState && expectedState !== state) {
+ console.warn("OAuth state mismatch - proceeding with caution.");
+ }
+
+ setAuthProcessing(true);
+ setError("");
+ window.history.replaceState({}, document.title, window.location.pathname);
+
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/auth/callback"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ code, state: state || "" }),
+ });
+
+ handleSuccess(data);
+ } catch (err) {
+ console.error("Login Error:", err);
+ setError(err instanceof Error ? err.message : "Login failed.");
+ setAuthProcessing(false);
+ }
+ }
+
+ async function handleSignInWithGitHub() {
+ setError("");
+ setMissingClientId(false);
+ setAuthProcessing(true);
+
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/auth/url"));
+
+ if (data.state) {
+ sessionStorage.setItem("gitpilot_oauth_state", data.state);
+ }
+
+ window.location.href = data.authorization_url;
+ } catch (err) {
+ console.error("Auth Start Error:", err);
+ // Check for missing client ID (404/500 errors)
+ if (err.message && (err.message.includes('404') || err.message.includes('500'))) {
+ setMissingClientId(true);
+ } else {
+ setError(err instanceof Error ? err.message : "Could not start sign-in.");
+ }
+ setAuthProcessing(false);
+ }
+ }
+
+ // ===========================================================================
+ // DEVICE FLOW LOGIC (No Client Secret Required)
+ // ===========================================================================
+
+ const startDeviceFlow = async () => {
+ setError("");
+ setAuthProcessing(true);
+ stopPolling.current = false; // Reset stop flag
+
+ try {
+ const data = await safeFetchJSON(apiUrl("/api/auth/device/code"), { method: "POST" });
+
+ // Handle Errors
+ if (data.error) {
+ if (data.error.includes("400") || data.error.includes("Bad Request")) {
+ throw new Error("Device Flow is disabled in GitHub. Please go to your GitHub App Settings > 'General' > 'Identifying and authorizing users' and check the box 'Enable Device Flow'.");
+ }
+ throw new Error(data.error);
+ }
+
+ if (!data.device_code) throw new Error("Invalid device code response");
+
+ setDeviceData(data);
+ setAuthProcessing(false);
+
+ // Start Polling (Recursive Timeout Pattern)
+ pollDeviceToken(data.device_code, data.interval || 5);
+
+ } catch (err) {
+ setError(err.message);
+ setAuthProcessing(false);
+ }
+ };
+
+ const pollDeviceToken = async (deviceCode, interval) => {
+ if (stopPolling.current) return;
+
+ try {
+ const response = await fetch(apiUrl("/api/auth/device/poll"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ device_code: deviceCode })
+ });
+
+ // 1. Success (200)
+ if (response.status === 200) {
+ const data = await response.json();
+ handleSuccess(data);
+ return;
+ }
+
+ // 2. Pending (202) -> Continue Polling
+ if (response.status === 202) {
+ // Schedule next poll
+ pollTimer.current = setTimeout(
+ () => pollDeviceToken(deviceCode, interval),
+ interval * 1000
+ );
+ return;
+ }
+
+ // 3. Error (4xx/5xx) -> Stop Polling & Show Error
+ const errData = await response.json().catch(() => ({ error: "Unknown polling error" }));
+
+ // Special case: If it's just a 'slow_down' warning (sometimes 400), we just wait longer
+ if (errData.error === "slow_down") {
+ pollTimer.current = setTimeout(
+ () => pollDeviceToken(deviceCode, interval + 5),
+ (interval + 5) * 1000
+ );
+ return;
+ }
+
+ // Terminal errors
+ throw new Error(errData.error || `Polling failed: ${response.status}`);
+
+ } catch (e) {
+ console.error("Poll error:", e);
+ if (!stopPolling.current) {
+ setError(e.message || "Failed to connect to authentication server.");
+ setDeviceData(null); // Return to initial state
+ }
+ }
+ };
+
+ const handleManualCheck = async () => {
+ if (!deviceData?.device_code) return;
+
+ try {
+ const response = await fetch(apiUrl("/api/auth/device/poll"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ device_code: deviceData.device_code })
+ });
+
+ if (response.status === 200) {
+ const data = await response.json();
+ handleSuccess(data);
+ } else if (response.status === 202) {
+ // Visual feedback for pending state
+ const btn = document.getElementById("manual-check-btn");
+ if (btn) {
+ const originalText = btn.innerText;
+ btn.innerText = "Still Pending...";
+ btn.disabled = true;
+ setTimeout(() => {
+ btn.innerText = originalText;
+ btn.disabled = false;
+ }, 2000);
+ }
+ }
+ } catch (e) {
+ console.error("Manual check failed", e);
+ }
+ };
+
+ const handleCancelDeviceFlow = () => {
+ stopPolling.current = true;
+ if (pollTimer.current) clearTimeout(pollTimer.current);
+ setDeviceData(null);
+ setError("");
+ };
+
+ // ===========================================================================
+ // SHARED HELPERS
+ // ===========================================================================
+
+ function handleSuccess(data) {
+ stopPolling.current = true; // Ensure polling stops
+ if (pollTimer.current) clearTimeout(pollTimer.current);
+
+ if (!data.access_token || !data.user) {
+ setError("Server returned incomplete session data.");
+ return;
+ }
+
+ try {
+ localStorage.setItem("github_token", data.access_token);
+ localStorage.setItem("github_user", JSON.stringify(data.user));
+ } catch (e) {
+ console.warn("LocalStorage access denied:", e);
+ }
+
+ if (typeof onAuthenticated === "function") {
+ onAuthenticated({
+ access_token: data.access_token,
+ user: data.user,
+ });
+ }
+ }
+
+ // --- Design Token System ---
+ const theme = {
+ bg: "#131316",
+ cardBg: "#1C1C1F",
+ border: "#27272A",
+ accent: "#D95C3D",
+ accentHover: "#C44F32",
+ textPrimary: "#EDEDED",
+ textSecondary: "#A1A1AA",
+ font: '"Söhne", "Inter", -apple-system, sans-serif',
+ };
+
+ const styles = {
+ container: {
+ minHeight: "100vh",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: theme.bg,
+ fontFamily: theme.font,
+ color: theme.textPrimary,
+ letterSpacing: "-0.01em",
+ },
+ card: {
+ backgroundColor: theme.cardBg,
+ width: "100%",
+ maxWidth: "440px",
+ borderRadius: "12px",
+ border: `1px solid ${theme.border}`,
+ boxShadow: "0 24px 48px -12px rgba(0, 0, 0, 0.6)",
+ padding: "48px 40px",
+ textAlign: "center",
+ position: "relative",
+ },
+ logoBadge: {
+ width: "48px",
+ height: "48px",
+ backgroundColor: "rgba(217, 92, 61, 0.15)",
+ color: theme.accent,
+ borderRadius: "10px",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ fontSize: "22px",
+ fontWeight: "700",
+ margin: "0 auto 32px auto",
+ border: "1px solid rgba(217, 92, 61, 0.2)",
+ },
+ h1: {
+ fontSize: "24px",
+ fontWeight: "600",
+ marginBottom: "12px",
+ color: theme.textPrimary,
+ },
+ p: {
+ fontSize: "14px",
+ color: theme.textSecondary,
+ lineHeight: "1.6",
+ marginBottom: "40px",
+ },
+ button: {
+ width: "100%",
+ height: "48px",
+ backgroundColor: theme.accent,
+ color: "#FFFFFF",
+ border: "none",
+ borderRadius: "8px",
+ fontSize: "14px",
+ fontWeight: "500",
+ cursor: (authProcessing || (mode === 'loading')) ? "not-allowed" : "pointer",
+ opacity: (authProcessing || (mode === 'loading')) ? 0.7 : 1,
+ transition: "background-color 0.2s ease",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: "10px",
+ boxShadow: "0 4px 12px rgba(217, 92, 61, 0.25)",
+ },
+ secondaryButton: {
+ backgroundColor: "transparent",
+ color: "#A1A1AA",
+ border: "1px solid #3F3F46",
+ padding: "8px 16px",
+ borderRadius: "6px",
+ fontSize: "12px",
+ cursor: "pointer",
+ marginTop: "16px",
+ minWidth: "100px"
+ },
+ errorBox: {
+ backgroundColor: "rgba(185, 28, 28, 0.15)",
+ border: "1px solid rgba(185, 28, 28, 0.3)",
+ color: "#FCA5A5",
+ padding: "12px",
+ borderRadius: "8px",
+ fontSize: "13px",
+ marginBottom: "24px",
+ textAlign: "left",
+ },
+ configCard: {
+ textAlign: "left",
+ backgroundColor: "#111",
+ border: "1px solid #333",
+ padding: "24px",
+ borderRadius: "8px",
+ marginBottom: "24px",
+ },
+ codeDisplay: {
+ backgroundColor: "#27272A",
+ color: theme.accent,
+ fontSize: "20px",
+ fontWeight: "700",
+ padding: "12px",
+ borderRadius: "6px",
+ textAlign: "center",
+ letterSpacing: "2px",
+ margin: "12px 0",
+ border: `1px dashed ${theme.accent}`,
+ cursor: "pointer",
+ },
+ footer: {
+ marginTop: "48px",
+ fontSize: "12px",
+ color: "#52525B",
+ }
+ };
+
+ // --- RENDER: Device Flow UI ---
+ const renderDeviceFlow = () => {
+ if (!deviceData) {
+ return (
+ !authProcessing && (e.currentTarget.style.backgroundColor = theme.accentHover)}
+ onMouseOut={(e) => !authProcessing && (e.currentTarget.style.backgroundColor = theme.accent)}
+ >
+ {authProcessing ? "Connecting..." : "Sign in with GitHub"}
+
+ );
+ }
+
+ return (
+
+
Authorize Device
+
+ GitPilot needs authorization to access your repositories.
+
+
+
+
1. Copy code:
+
{
+ navigator.clipboard.writeText(deviceData.user_code);
+ }}
+ title="Click to copy"
+ >
+ {deviceData.user_code}
+
+
+
+
+
+
+ ↻
+ Waiting for authorization...
+
+
+
+
+
+ Check Status
+
+
+ Cancel
+
+
+
+ );
+ };
+
+ // --- RENDER: Config Error ---
+ if (missingClientId) {
+ return (
+
+
+
⚠️
+
Configuration Error
+
Could not connect to GitHub Authentication services.
+
setMissingClientId(false)} style={{...styles.button, backgroundColor: "#3F3F46"}}>Retry
+
+
+ );
+ }
+
+ // --- RENDER: Main ---
+ return (
+
+
+
GP
+
+
GitPilot Enterprise
+
+ Agentic AI workflow for your repositories.
+ Secure. Context-aware. Automated.
+
+
+ {error &&
{error}
}
+
+ {mode === "loading" && (
+
Initializing...
+ )}
+
+ {mode === "web" && (
+
!authProcessing && (e.currentTarget.style.backgroundColor = theme.accentHover)}
+ onMouseOut={(e) => !authProcessing && (e.currentTarget.style.backgroundColor = theme.accent)}
+ >
+ {authProcessing ? "Connecting..." : (
+ <>
+
+ Sign in with GitHub
+ >
+ )}
+
+ )}
+
+ {mode === "device" && renderDeviceFlow()}
+
+
+ © {new Date().getFullYear()} GitPilot Inc.
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/components/PlanView.jsx b/frontend/components/PlanView.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..c4906fe7cf0503be3994270f513da12effe5c421
--- /dev/null
+++ b/frontend/components/PlanView.jsx
@@ -0,0 +1,143 @@
+import React from "react";
+
+/**
+ * PlanView — enterprise "Proposed execution plan" card.
+ *
+ * One main card. Subtle internal spacing instead of bordered nested boxes.
+ * Steps are rendered as a vertical numbered timeline; file actions become
+ * compact pill badges (READ / CREATE / MODIFY / DELETE / INDEX).
+ *
+ * The card itself is borderless — the surrounding AssistantMessage
+ * already provides the outer container.
+ */
+export default function PlanView({ plan, planStatus }) {
+ if (!plan) return null;
+
+ const totals = { CREATE: 0, MODIFY: 0, DELETE: 0, INDEX: 0, READ: 0 };
+ plan.steps.forEach((step) => {
+ step.files.forEach((file) => {
+ totals[file.action] = (totals[file.action] || 0) + 1;
+ });
+ });
+
+ return (
+
+
+
+
+
Proposed execution plan
+
{plan.goal}
+
+
+
+ {planStatus === "executed" && (
+
+
+
+
+ Executed
+
+ )}
+ {planStatus === "rejected" && (
+
+
+
+
+
+ Rejected
+
+ )}
+
+
+ {totals.CREATE > 0 && (
+
+ {totals.CREATE} create
+
+ )}
+ {totals.MODIFY > 0 && (
+
+ {totals.MODIFY} modify
+
+ )}
+ {totals.DELETE > 0 && (
+
+ {totals.DELETE} delete
+
+ )}
+ {totals.INDEX > 0 && (
+
+ {totals.INDEX === 1 ? "1 setup" : `${totals.INDEX} setup`}
+
+ )}
+
+
+
+
+
+ {plan.steps.map((s, idx) => (
+
+
+
{s.step_number}
+ {idx < plan.steps.length - 1 && (
+
+ )}
+
+
+
{s.title}
+ {s.description && (
+
{s.description}
+ )}
+
+ {s.files && s.files.length > 0 && (
+
+ {s.files.map((file, fi) => (
+
+
+ {file.action}
+
+
+ {file.action === "INDEX"
+ ? "Build semantic index for this repo"
+ : file.path}
+
+
+ ))}
+
+ )}
+
+ {s.files && s.files.some((f) => f.action === "INDEX") && (
+
+ One-time semantic index build (~80 MB model, ~30 s, ~12 MB on
+ disk). No cloud calls. Click Reject plan to
+ skip — you'll be offered the grep fallback.
+
+ )}
+
+ {s.risks && (
+
+ ⚠
+ {s.risks}
+
+ )}
+
+
+ ))}
+
+
+ );
+}
diff --git a/frontend/components/ProjectContextPanel.jsx b/frontend/components/ProjectContextPanel.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..fdf9a63449e8be8d2df74eefe920f5d577375672
--- /dev/null
+++ b/frontend/components/ProjectContextPanel.jsx
@@ -0,0 +1,581 @@
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import FileTree from "./FileTree.jsx";
+import BranchPicker from "./BranchPicker.jsx";
+import SandboxStatusWidget from "./SandboxStatusWidget.jsx";
+
+// --- INJECTED STYLES FOR ANIMATIONS ---
+const animationStyles = `
+ @keyframes highlight-pulse {
+ 0% { background-color: rgba(59, 130, 246, 0.10); }
+ 50% { background-color: rgba(59, 130, 246, 0.22); }
+ 100% { background-color: transparent; }
+ }
+ .pulse-context {
+ animation: highlight-pulse 1.1s ease-out;
+ }
+`;
+
+/**
+ * ProjectContextPanel (Production-ready)
+ *
+ * Controlled component:
+ * - Branch source of truth is App.jsx:
+ * - defaultBranch (prod)
+ * - currentBranch (what user sees)
+ * - sessionBranches (list of all active AI session branches)
+ *
+ * Responsibilities:
+ * - Show project context + branch dropdown + AI badge/banner
+ * - Fetch access status + file count for the currentBranch
+ * - Trigger visual pulse on pulseNonce (Hard Switch)
+ */
+export default function ProjectContextPanel({
+ repo,
+ defaultBranch,
+ currentBranch,
+ sessionBranch, // Active session branch (optional, for specific highlighting)
+ sessionBranches = [], // List of all AI branches
+ onBranchChange,
+ pulseNonce,
+ onSettingsClick,
+}) {
+ const [appUrl, setAppUrl] = useState("");
+ const [fileCount, setFileCount] = useState(0);
+
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
+
+ // Data Loading State
+ const [analyzing, setAnalyzing] = useState(false);
+ const [accessInfo, setAccessInfo] = useState(null);
+ const [treeError, setTreeError] = useState(null);
+
+ // Retry / Refresh Logic
+ const [refreshTrigger, setRefreshTrigger] = useState(0);
+ const [retryCount, setRetryCount] = useState(0);
+ const retryTimeoutRef = useRef(null);
+
+ // UX State
+ const [animateHeader, setAnimateHeader] = useState(false);
+ const [toast, setToast] = useState({ visible: false, title: "", msg: "" });
+
+ // Calculate effective default to prevent 'main' fallback errors
+ const effectiveDefaultBranch = defaultBranch || repo?.default_branch || "main";
+ const branch = currentBranch || effectiveDefaultBranch;
+
+ // Determine if we are currently viewing an AI Session branch
+ const isAiSession = (sessionBranches.includes(branch)) || (sessionBranch === branch && branch !== effectiveDefaultBranch);
+
+ // Fetch App URL on mount
+ useEffect(() => {
+ fetch("/api/auth/app-url")
+ .then((res) => res.json())
+ .then((data) => {
+ if (data.app_url) setAppUrl(data.app_url);
+ })
+ .catch((err) => console.error("Failed to fetch App URL:", err));
+ }, []);
+
+ // Hard Switch pulse: whenever App increments pulseNonce
+ useEffect(() => {
+ if (!pulseNonce) return;
+ setAnimateHeader(true);
+ const t = window.setTimeout(() => setAnimateHeader(false), 1100);
+ return () => window.clearTimeout(t);
+ }, [pulseNonce]);
+
+ // Main data fetcher (Access + Tree stats) for currentBranch
+ // Stale-while-revalidate: keep previous data visible during fetch
+ useEffect(() => {
+ if (!repo) return;
+
+ // Only show full "analyzing" spinner if we have no data yet
+ if (!accessInfo) setAnalyzing(true);
+ setTreeError(null);
+
+ if (retryTimeoutRef.current) {
+ clearTimeout(retryTimeoutRef.current);
+ retryTimeoutRef.current = null;
+ }
+
+ let headers = {};
+ try {
+ const token = localStorage.getItem("github_token");
+ if (token) headers = { Authorization: `Bearer ${token}` };
+ } catch (e) {
+ console.warn("Unable to read github_token:", e);
+ }
+
+ let cancelled = false;
+ const cacheBuster = `&_t=${Date.now()}&retry=${retryCount}`;
+
+ // A) Access Check (with Stale Cache Fix)
+ fetch(`/api/auth/repo-access?owner=${repo.owner}&repo=${repo.name}${cacheBuster}`, {
+ headers,
+ cache: "no-cache",
+ })
+ .then(async (res) => {
+ if (cancelled) return;
+ const data = await res.json().catch(() => ({}));
+
+ if (!res.ok) {
+ setAccessInfo({ can_write: false, app_installed: false, auth_type: "none" });
+ return;
+ }
+
+ setAccessInfo(data);
+
+ // Auto-retry if user has push access but App is not detected yet (Stale Cache)
+ if (data.can_write && !data.app_installed && retryCount === 0) {
+ retryTimeoutRef.current = setTimeout(() => {
+ setRetryCount(1);
+ }, 1000);
+ }
+ })
+ .catch(() => {
+ if (!cancelled) setAccessInfo({ can_write: false, app_installed: false, auth_type: "none" });
+ });
+
+ // B) Tree count for the selected branch
+ // Don't clear fileCount — keep stale value visible until new one arrives
+ const hadFileCount = fileCount > 0;
+ if (!hadFileCount) setAnalyzing(true);
+
+ fetch(`/api/repos/${repo.owner}/${repo.name}/tree?ref=${encodeURIComponent(branch)}&_t=${Date.now()}`, {
+ headers,
+ cache: "no-cache",
+ })
+ .then(async (res) => {
+ if (cancelled) return;
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ setTreeError(data.detail || "Failed to load tree");
+ setFileCount(0);
+ return;
+ }
+ setFileCount(Array.isArray(data.files) ? data.files.length : 0);
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ setTreeError(err.message);
+ setFileCount(0);
+ })
+ .finally(() => { if (!cancelled) setAnalyzing(false); });
+
+ return () => {
+ cancelled = true;
+ if (retryTimeoutRef.current) clearTimeout(retryTimeoutRef.current);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [repo?.owner, repo?.name, branch, refreshTrigger, retryCount]);
+
+ const showToast = (title, msg) => {
+ setToast({ visible: true, title, msg });
+ setTimeout(() => setToast((prev) => ({ ...prev, visible: false })), 3000);
+ };
+
+ const handleManualSwitch = (targetBranch) => {
+ if (!targetBranch || targetBranch === branch) {
+ setIsDropdownOpen(false);
+ return;
+ }
+
+ // Local UI feedback (App.jsx will handle the actual state change)
+ const goingAi = sessionBranches.includes(targetBranch);
+ showToast(
+ goingAi ? "Context Switched" : "Switched to Production",
+ goingAi ? `Viewing AI Session: ${targetBranch}` : `Viewing ${targetBranch}.`
+ );
+
+ setIsDropdownOpen(false);
+ if (onBranchChange) onBranchChange(targetBranch);
+ };
+
+ const handleRefresh = () => {
+ setAnalyzing(true);
+ setRetryCount(0);
+ setRefreshTrigger((prev) => prev + 1);
+ };
+
+ const handleInstallClick = () => {
+ if (!appUrl) return;
+ const targetUrl = appUrl.endsWith("/") ? `${appUrl}installations/new` : `${appUrl}/installations/new`;
+ window.open(targetUrl, "_blank", "noopener,noreferrer");
+ };
+
+ // --- STYLES ---
+ const theme = useMemo(
+ () => ({
+ bg: "#131316",
+ border: "#27272A",
+ textPrimary: "#EDEDED",
+ textSecondary: "#A1A1AA",
+ accent: "#3b82f6",
+ warningBorder: "rgba(245, 158, 11, 0.2)",
+ warningText: "#F59E0B",
+ successColor: "#10B981",
+ cardBg: "#18181B",
+ aiBg: "rgba(59, 130, 246, 0.10)",
+ aiBorder: "rgba(59, 130, 246, 0.30)",
+ aiText: "#60a5fa",
+ }),
+ []
+ );
+
+ const styles = useMemo(
+ () => ({
+ container: {
+ height: "100%",
+ borderRight: `1px solid ${theme.border}`,
+ backgroundColor: theme.bg,
+ display: "flex",
+ flexDirection: "column",
+ fontFamily: '"Söhne", "Inter", sans-serif',
+ position: "relative",
+ overflow: "hidden",
+ },
+ header: {
+ padding: "16px 20px",
+ borderBottom: `1px solid ${theme.border}`,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ transition: "background-color 0.3s ease",
+ },
+ titleGroup: { display: "flex", alignItems: "center", gap: "8px" },
+ title: { fontSize: "13px", fontWeight: "600", color: theme.textPrimary },
+ repoBadge: {
+ backgroundColor: "#27272A",
+ color: theme.textSecondary,
+ fontSize: "11px",
+ padding: "2px 8px",
+ borderRadius: "12px",
+ border: `1px solid ${theme.border}`,
+ fontFamily: "monospace",
+ },
+ aiBadge: {
+ display: "flex",
+ alignItems: "center",
+ gap: "6px",
+ backgroundColor: theme.aiBg,
+ color: theme.aiText,
+ fontSize: "10px",
+ fontWeight: "bold",
+ padding: "2px 8px",
+ borderRadius: "12px",
+ border: `1px solid ${theme.aiBorder}`,
+ textTransform: "uppercase",
+ letterSpacing: "0.5px",
+ },
+ content: {
+ padding: "16px 20px 12px 20px",
+ display: "flex",
+ flexDirection: "column",
+ gap: "12px",
+ },
+ statRow: { display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "4px" },
+ label: { color: theme.textSecondary },
+ value: { color: theme.textPrimary, fontWeight: "500" },
+ dropdownContainer: { position: "relative" },
+ branchButton: {
+ display: "flex",
+ alignItems: "center",
+ gap: "6px",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ border: `1px solid ${isAiSession ? theme.aiBorder : theme.border}`,
+ backgroundColor: isAiSession ? "rgba(59, 130, 246, 0.05)" : "transparent",
+ color: isAiSession ? theme.aiText : theme.textPrimary,
+ fontSize: "13px",
+ cursor: "pointer",
+ fontFamily: "monospace",
+ },
+ dropdownMenu: {
+ position: "absolute",
+ top: "100%",
+ left: 0,
+ marginTop: "4px",
+ width: "240px",
+ backgroundColor: "#1F1F23",
+ border: `1px solid ${theme.border}`,
+ borderRadius: "6px",
+ boxShadow: "0 4px 12px rgba(0,0,0,0.5)",
+ zIndex: 50,
+ display: isDropdownOpen ? "block" : "none",
+ overflow: "hidden",
+ },
+ dropdownItem: {
+ padding: "8px 12px",
+ fontSize: "13px",
+ color: theme.textSecondary,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ gap: "8px",
+ borderBottom: `1px solid ${theme.border}`,
+ },
+ contextBanner: {
+ backgroundColor: theme.aiBg,
+ borderTop: `1px solid ${theme.aiBorder}`,
+ padding: "8px 20px",
+ fontSize: "11px",
+ color: theme.aiText,
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ },
+ toast: {
+ position: "absolute",
+ top: "16px",
+ right: "16px",
+ backgroundColor: "#18181B",
+ border: `1px solid ${theme.border}`,
+ borderLeft: `3px solid ${theme.accent}`,
+ borderRadius: "6px",
+ padding: "12px",
+ boxShadow: "0 4px 12px rgba(0,0,0,0.5)",
+ zIndex: 100,
+ minWidth: "240px",
+ transition: "all 0.3s cubic-bezier(0.16, 1, 0.3, 1)",
+ transform: toast.visible ? "translateX(0)" : "translateX(120%)",
+ opacity: toast.visible ? 1 : 0,
+ },
+ toastTitle: { fontSize: "13px", fontWeight: "bold", color: theme.textPrimary, marginBottom: "2px" },
+ toastMsg: { fontSize: "11px", color: theme.textSecondary },
+ refreshButton: {
+ marginTop: "8px",
+ height: "32px",
+ padding: "0 12px",
+ backgroundColor: "transparent",
+ color: theme.textSecondary,
+ border: `1px solid ${theme.border}`,
+ borderRadius: "6px",
+ fontSize: "12px",
+ cursor: analyzing ? "not-allowed" : "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: "6px",
+ },
+ settingsBtn: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ width: "28px",
+ height: "28px",
+ borderRadius: "6px",
+ border: `1px solid ${theme.border}`,
+ backgroundColor: "transparent",
+ color: theme.textSecondary,
+ cursor: "pointer",
+ padding: 0,
+ transition: "color 0.15s, border-color 0.15s",
+ },
+ treeWrapper: { flex: 1, overflow: "auto", borderTop: `1px solid ${theme.border}` },
+ installCard: {
+ marginTop: "8px",
+ padding: "12px",
+ borderRadius: "8px",
+ backgroundColor: theme.cardBg,
+ border: `1px solid ${theme.warningBorder}`,
+ },
+ installHeader: {
+ display: "flex",
+ alignItems: "center",
+ gap: "10px",
+ fontSize: "14px",
+ fontWeight: "600",
+ color: theme.textPrimary,
+ },
+ installText: {
+ fontSize: "13px",
+ color: theme.textSecondary,
+ lineHeight: "1.5",
+ },
+ }),
+ [analyzing, isAiSession, isDropdownOpen, theme, toast.visible]
+ );
+
+ // Determine status text
+ let statusText = "Checking...";
+ let statusColor = theme.textSecondary;
+ let showInstallCard = false;
+
+ if (!analyzing && accessInfo) {
+ if (accessInfo.app_installed) {
+ statusText = "Write Access ✓";
+ statusColor = theme.successColor;
+ } else if (accessInfo.can_write && retryCount === 0) {
+ statusText = "Verifying...";
+ } else if (accessInfo.can_write) {
+ statusText = "Push Access (No App)";
+ statusColor = theme.warningText;
+ showInstallCard = true;
+ } else {
+ statusText = "Read Only";
+ statusColor = theme.warningText;
+ showInstallCard = true;
+ }
+ }
+
+ if (!repo) {
+ return (
+
+ );
+ }
+
+ return (
+
+
+
+ {/* TOAST */}
+
+
{toast.title}
+
{toast.msg}
+
+
+ {/* HEADER */}
+
+
+
Project context
+ {isAiSession && (
+
+
+
+
+ AI Session
+
+ )}
+
+
+ {!isAiSession &&
{repo.name} }
+ {onSettingsClick && (
+
+
+
+
+
+
+ )}
+
+
+
+ {/* CONTENT */}
+
+ {/* Branch selector (Claude-Code-on-Web parity — uses BranchPicker with search) */}
+
+ Branch:
+
+
+
+ {/* Stats */}
+
+ Files:
+ {analyzing ? "…" : fileCount}
+
+
+
+ Status:
+ {statusText}
+
+
+ {/* Tree error (optional display) */}
+ {treeError && (
+
+ {treeError}
+
+ )}
+
+ {/* Refresh */}
+
+
+
+
+ {analyzing ? "Refreshing..." : "Refresh"}
+
+
+ {/* Install card */}
+ {showInstallCard && (
+
+
+ ⚡
+ Enable Write Access
+
+
+ Install the GitPilot App to enable AI agent operations.
+
+
+ Alternatively, use Folder or Local Git mode for local-first workflows without GitHub.
+
+
+ Install App
+
+
+ )}
+
+
+ {/* Context banner */}
+ {isAiSession && (
+
+
+
+
+
+
+
+ You are viewing an AI Session branch.
+
+ handleManualSwitch(effectiveDefaultBranch)}>
+ Return to {effectiveDefaultBranch}
+
+
+ )}
+
+ {/* File tree (branch-aware) */}
+
+
+
+
+ {/* Sandbox status — always visible. Click "Change" / "Repair"
+ to open Settings (matches the existing settings affordance
+ at the top), or "Use Local" to one-click flip the backend
+ when MatrixLab is unreachable. */}
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/components/ProjectSettings/ContextTab.jsx b/frontend/components/ProjectSettings/ContextTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..5272c846b181fb9c17031215e4056b565a865f09
--- /dev/null
+++ b/frontend/components/ProjectSettings/ContextTab.jsx
@@ -0,0 +1,352 @@
+import React, { useEffect, useMemo, useRef, useState } from "react";
+
+export default function ContextTab({ owner, repo }) {
+ const [assets, setAssets] = useState([]);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [uploadHint, setUploadHint] = useState("");
+ const inputRef = useRef(null);
+
+ const canUse = useMemo(() => Boolean(owner && repo), [owner, repo]);
+
+ async function loadAssets() {
+ if (!canUse) return;
+ setError("");
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/context/assets`);
+ if (!res.ok) throw new Error(`Failed to list assets (${res.status})`);
+ const data = await res.json();
+ setAssets(data.assets || []);
+ } catch (e) {
+ setError(e?.message || "Failed to load assets");
+ }
+ }
+
+ useEffect(() => {
+ loadAssets();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [owner, repo]);
+
+ async function uploadFiles(fileList) {
+ if (!canUse) return;
+ const files = Array.from(fileList || []);
+ if (!files.length) return;
+
+ setBusy(true);
+ setError("");
+ setUploadHint(`Uploading ${files.length} file(s)...`);
+
+ try {
+ for (const f of files) {
+ const form = new FormData();
+ form.append("file", f);
+
+ const res = await fetch(
+ `/api/repos/${owner}/${repo}/context/assets/upload`,
+ { method: "POST", body: form }
+ );
+ if (!res.ok) {
+ const txt = await res.text().catch(() => "");
+ throw new Error(`Upload failed (${res.status}) ${txt}`);
+ }
+ }
+ setUploadHint("Upload complete. Refreshing list...");
+ await loadAssets();
+ setUploadHint("");
+ } catch (e) {
+ setError(e?.message || "Upload failed");
+ setUploadHint("");
+ } finally {
+ setBusy(false);
+ if (inputRef.current) inputRef.current.value = "";
+ }
+ }
+
+ async function deleteAsset(assetId) {
+ if (!canUse) return;
+ const ok = window.confirm("Delete this asset? This cannot be undone.");
+ if (!ok) return;
+
+ setBusy(true);
+ setError("");
+ try {
+ const res = await fetch(
+ `/api/repos/${owner}/${repo}/context/assets/${assetId}`,
+ { method: "DELETE" }
+ );
+ if (!res.ok) throw new Error(`Delete failed (${res.status})`);
+ await loadAssets();
+ } catch (e) {
+ setError(e?.message || "Delete failed");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function downloadAsset(assetId) {
+ if (!canUse) return;
+ window.open(
+ `/api/repos/${owner}/${repo}/context/assets/${assetId}/download`,
+ "_blank"
+ );
+ }
+
+ const empty = !assets || assets.length === 0;
+
+ return (
+
+
+
+
Project Context
+
+ Upload documents, transcripts, screenshots, etc. (non-destructive,
+ additive).
+
+
+
+
+ uploadFiles(e.target.files)}
+ style={styles.fileInput}
+ />
+ inputRef.current?.click()}
+ >
+ Upload
+
+
+ Refresh
+
+
+
+
+
{
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (busy) return;
+ uploadFiles(e.dataTransfer.files);
+ }}
+ >
+
+ Drag & drop files here, or click Upload .
+
+
+ Tip: For audio/video, upload a transcript file too.
+
+
+
+ {uploadHint ?
{uploadHint}
: null}
+ {error ?
{error}
: null}
+
+
+
+
File
+
Type
+
Size
+
Indexed
+
Actions
+
+
+ {empty ? (
+
+ No context assets yet. Upload docs, transcripts, and screenshots to
+ improve planning quality.
+
+ ) : (
+ assets.map((a) => (
+
+
+
{a.filename}
+
+ Added: {a.created_at || "-"} | Extracted:{" "}
+ {Number(a.extracted_chars || 0).toLocaleString()} chars
+
+
+
+
+ {a.mime || "unknown"}
+
+
+
+ {formatBytes(a.size_bytes || 0)}
+
+
+
+ {a.indexed_chunks || 0} chunks
+
+
+
+ downloadAsset(a.asset_id)}
+ >
+ Download
+
+ deleteAsset(a.asset_id)}
+ >
+ Delete
+
+
+
+ ))
+ )}
+
+
+ );
+}
+
+function formatBytes(bytes) {
+ const b = Number(bytes || 0);
+ if (!b) return "0 B";
+ const units = ["B", "KB", "MB", "GB", "TB"];
+ let i = 0;
+ let v = b;
+ while (v >= 1024 && i < units.length - 1) {
+ v /= 1024;
+ i += 1;
+ }
+ return `${v.toFixed(v >= 10 || i === 0 ? 0 : 1)} ${units[i]}`;
+}
+
+const styles = {
+ wrap: { display: "flex", flexDirection: "column", gap: 12 },
+ topRow: {
+ display: "flex",
+ justifyContent: "space-between",
+ gap: 12,
+ alignItems: "flex-start",
+ flexWrap: "wrap",
+ },
+ left: { minWidth: 280 },
+ right: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" },
+ h1: { fontSize: 14, fontWeight: 800, color: "#fff" },
+ h2: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 4 },
+ fileInput: { display: "none" },
+ btn: {
+ background: "rgba(255,255,255,0.10)",
+ border: "1px solid rgba(255,255,255,0.18)",
+ color: "#fff",
+ borderRadius: 10,
+ padding: "8px 10px",
+ cursor: "pointer",
+ fontSize: 13,
+ },
+ dropzone: {
+ border: "1px dashed rgba(255,255,255,0.22)",
+ borderRadius: 12,
+ padding: 16,
+ background: "rgba(255,255,255,0.03)",
+ },
+ dropText: { color: "rgba(255,255,255,0.85)", fontSize: 13 },
+ dropSub: { color: "rgba(255,255,255,0.55)", fontSize: 12, marginTop: 6 },
+ hint: {
+ color: "rgba(255,255,255,0.75)",
+ fontSize: 12,
+ padding: "8px 10px",
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 10,
+ background: "rgba(255,255,255,0.03)",
+ },
+ error: {
+ color: "#ffb3b3",
+ fontSize: 12,
+ padding: "8px 10px",
+ border: "1px solid rgba(255,120,120,0.25)",
+ borderRadius: 10,
+ background: "rgba(255,80,80,0.08)",
+ },
+ tableWrap: {
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ overflow: "hidden",
+ },
+ tableHeader: {
+ display: "grid",
+ gridTemplateColumns: "1.6fr 1fr 0.6fr 0.6fr 0.8fr",
+ gap: 0,
+ padding: "10px 12px",
+ background: "rgba(255,255,255,0.03)",
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
+ fontSize: 12,
+ color: "rgba(255,255,255,0.65)",
+ },
+ row: {
+ display: "grid",
+ gridTemplateColumns: "1.6fr 1fr 0.6fr 0.6fr 0.8fr",
+ padding: "10px 12px",
+ borderBottom: "1px solid rgba(255,255,255,0.08)",
+ alignItems: "center",
+ },
+ col: { minWidth: 0 },
+ colName: {},
+ colMeta: { color: "rgba(255,255,255,0.75)", fontSize: 12 },
+ colActions: { display: "flex", gap: 8, justifyContent: "flex-end" },
+ fileName: {
+ color: "#fff",
+ fontSize: 13,
+ fontWeight: 700,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ },
+ small: {
+ color: "rgba(255,255,255,0.55)",
+ fontSize: 11,
+ marginTop: 4,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ },
+ badge: {
+ display: "inline-flex",
+ alignItems: "center",
+ padding: "2px 8px",
+ borderRadius: 999,
+ border: "1px solid rgba(255,255,255,0.16)",
+ background: "rgba(255,255,255,0.04)",
+ fontSize: 11,
+ color: "rgba(255,255,255,0.80)",
+ maxWidth: "100%",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ },
+ smallBtn: {
+ background: "rgba(255,255,255,0.08)",
+ border: "1px solid rgba(255,255,255,0.16)",
+ color: "#fff",
+ borderRadius: 10,
+ padding: "6px 8px",
+ cursor: "pointer",
+ fontSize: 12,
+ },
+ dangerBtn: {
+ border: "1px solid rgba(255,90,90,0.35)",
+ background: "rgba(255,90,90,0.10)",
+ },
+ empty: {
+ padding: 14,
+ color: "rgba(255,255,255,0.65)",
+ fontSize: 13,
+ },
+};
diff --git a/frontend/components/ProjectSettings/ConventionsTab.jsx b/frontend/components/ProjectSettings/ConventionsTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..d508ccf1a65817f1b5a44dbebcdfc1861c42b8b6
--- /dev/null
+++ b/frontend/components/ProjectSettings/ConventionsTab.jsx
@@ -0,0 +1,151 @@
+import React, { useEffect, useMemo, useState } from "react";
+
+export default function ConventionsTab({ owner, repo }) {
+ const [content, setContent] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+
+ const canUse = useMemo(() => Boolean(owner && repo), [owner, repo]);
+
+ async function load() {
+ if (!canUse) return;
+ setError("");
+ setBusy(true);
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/context`);
+ if (!res.ok) throw new Error(`Failed to load conventions (${res.status})`);
+ const data = await res.json();
+ // backend may return { context: "..."} or { conventions: "..."} depending on implementation
+ setContent(data.context || data.conventions || data.memory || data.text || "");
+ } catch (e) {
+ setError(e?.message || "Failed to load conventions");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function initialize() {
+ if (!canUse) return;
+ setError("");
+ setBusy(true);
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/context/init`, {
+ method: "POST",
+ });
+ if (!res.ok) {
+ const txt = await res.text().catch(() => "");
+ throw new Error(`Init failed (${res.status}) ${txt}`);
+ }
+ await load();
+ } catch (e) {
+ setError(e?.message || "Init failed");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ useEffect(() => {
+ load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [owner, repo]);
+
+ return (
+
+
+
+
Project Conventions
+
+ This is the project memory/conventions file used by GitPilot.
+
+
+
+
+ Refresh
+
+
+ Initialize
+
+
+
+
+ {error ?
{error}
: null}
+
+
+ {content ? (
+
{content}
+ ) : (
+
+ No conventions found yet. Click Initialize to create default
+ project memory if supported.
+
+ )}
+
+
+
+ Editing conventions is intentionally not included here to keep this
+ feature additive/non-destructive. You can extend this later with an
+ explicit "Edit" mode.
+
+
+ );
+}
+
+const styles = {
+ wrap: { display: "flex", flexDirection: "column", gap: 12 },
+ topRow: {
+ display: "flex",
+ justifyContent: "space-between",
+ gap: 12,
+ alignItems: "flex-start",
+ flexWrap: "wrap",
+ },
+ actions: { display: "flex", gap: 8, flexWrap: "wrap" },
+ h1: { fontSize: 14, fontWeight: 800, color: "#fff" },
+ h2: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 4 },
+ btn: {
+ background: "rgba(255,255,255,0.10)",
+ border: "1px solid rgba(255,255,255,0.18)",
+ color: "#fff",
+ borderRadius: 10,
+ padding: "8px 10px",
+ cursor: "pointer",
+ fontSize: 13,
+ },
+ error: {
+ color: "#ffb3b3",
+ fontSize: 12,
+ padding: "8px 10px",
+ border: "1px solid rgba(255,120,120,0.25)",
+ borderRadius: 10,
+ background: "rgba(255,80,80,0.08)",
+ },
+ box: {
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ overflow: "hidden",
+ background: "rgba(0,0,0,0.22)",
+ },
+ pre: {
+ margin: 0,
+ padding: 12,
+ color: "rgba(255,255,255,0.85)",
+ fontSize: 12,
+ lineHeight: 1.35,
+ whiteSpace: "pre-wrap",
+ overflow: "auto",
+ maxHeight: 520,
+ },
+ empty: {
+ padding: 12,
+ color: "rgba(255,255,255,0.65)",
+ fontSize: 13,
+ },
+ note: {
+ color: "rgba(255,255,255,0.55)",
+ fontSize: 12,
+ },
+};
diff --git a/frontend/components/ProjectSettings/UseCaseTab.jsx b/frontend/components/ProjectSettings/UseCaseTab.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..b01e9a46d3ac15c42d16decf69b93e0cf7192db2
--- /dev/null
+++ b/frontend/components/ProjectSettings/UseCaseTab.jsx
@@ -0,0 +1,637 @@
+import React, { useEffect, useMemo, useRef, useState } from "react";
+
+export default function UseCaseTab({ owner, repo }) {
+ const [useCases, setUseCases] = useState([]);
+ const [selectedId, setSelectedId] = useState("");
+ const [useCase, setUseCase] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [draftTitle, setDraftTitle] = useState("New Use Case");
+ const [message, setMessage] = useState("");
+ const messagesEndRef = useRef(null);
+
+ const canUse = useMemo(() => Boolean(owner && repo), [owner, repo]);
+ const spec = useCase?.spec || {};
+
+ function scrollToBottom() {
+ requestAnimationFrame(() => {
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
+ });
+ }
+
+ async function loadUseCases() {
+ if (!canUse) return;
+ setError("");
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/use-cases`);
+ if (!res.ok) throw new Error(`Failed to list use cases (${res.status})`);
+ const data = await res.json();
+ const list = data.use_cases || [];
+ setUseCases(list);
+
+ // auto select active or first
+ const active = list.find((x) => x.is_active);
+ const nextId = active?.use_case_id || list[0]?.use_case_id || "";
+ if (!selectedId && nextId) setSelectedId(nextId);
+ } catch (e) {
+ setError(e?.message || "Failed to load use cases");
+ }
+ }
+
+ async function loadUseCase(id) {
+ if (!canUse || !id) return;
+ setError("");
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/use-cases/${id}`);
+ if (!res.ok) throw new Error(`Failed to load use case (${res.status})`);
+ const data = await res.json();
+ setUseCase(data.use_case || null);
+ scrollToBottom();
+ } catch (e) {
+ setError(e?.message || "Failed to load use case");
+ }
+ }
+
+ useEffect(() => {
+ loadUseCases();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [owner, repo]);
+
+ useEffect(() => {
+ if (!selectedId) return;
+ loadUseCase(selectedId);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedId]);
+
+ async function createUseCase() {
+ if (!canUse) return;
+ setBusy(true);
+ setError("");
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/use-cases`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title: draftTitle || "New Use Case" }),
+ });
+ if (!res.ok) {
+ const txt = await res.text().catch(() => "");
+ throw new Error(`Create failed (${res.status}) ${txt}`);
+ }
+ const data = await res.json();
+ const id = data?.use_case?.use_case_id;
+ await loadUseCases();
+ if (id) setSelectedId(id);
+ setDraftTitle("New Use Case");
+ } catch (e) {
+ setError(e?.message || "Create failed");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function sendMessage() {
+ if (!canUse || !selectedId) return;
+ const msg = (message || "").trim();
+ if (!msg) return;
+
+ setBusy(true);
+ setError("");
+
+ // optimistic UI: append user message immediately
+ setUseCase((prev) => {
+ if (!prev) return prev;
+ const next = { ...prev };
+ next.messages = Array.isArray(next.messages) ? [...next.messages] : [];
+ next.messages.push({ role: "user", content: msg, ts: new Date().toISOString() });
+ return next;
+ });
+ setMessage("");
+ scrollToBottom();
+
+ try {
+ const res = await fetch(
+ `/api/repos/${owner}/${repo}/use-cases/${selectedId}/chat`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ message: msg }),
+ }
+ );
+ if (!res.ok) {
+ const txt = await res.text().catch(() => "");
+ throw new Error(`Chat failed (${res.status}) ${txt}`);
+ }
+ const data = await res.json();
+ setUseCase(data.use_case || null);
+ await loadUseCases();
+ scrollToBottom();
+ } catch (e) {
+ setError(e?.message || "Chat failed");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function finalizeUseCase() {
+ if (!canUse || !selectedId) return;
+ setBusy(true);
+ setError("");
+ try {
+ const res = await fetch(
+ `/api/repos/${owner}/${repo}/use-cases/${selectedId}/finalize`,
+ { method: "POST" }
+ );
+ if (!res.ok) {
+ const txt = await res.text().catch(() => "");
+ throw new Error(`Finalize failed (${res.status}) ${txt}`);
+ }
+ const data = await res.json();
+ setUseCase(data.use_case || null);
+ await loadUseCases();
+ alert(
+ "Use Case finalized and marked active.\n\nA Markdown export was saved in the repo workspace .gitpilot/context/use_cases/."
+ );
+ } catch (e) {
+ setError(e?.message || "Finalize failed");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const activeId = useCases.find((x) => x.is_active)?.use_case_id;
+
+ return (
+
+
+
+
Use Case
+
+ Guided chat to clarify requirements and produce a versioned spec.
+
+
+
+
+ setDraftTitle(e.target.value)}
+ placeholder="New use case title..."
+ style={styles.titleInput}
+ disabled={!canUse || busy}
+ />
+
+ New
+
+
+ Finalize
+
+
+ Refresh
+
+
+
+
+ {error ?
{error}
: null}
+
+
+
+
Use Cases
+
+ {useCases.length === 0 ? (
+
+ No use cases yet. Create one with New .
+
+ ) : (
+ useCases.map((uc) => (
+
setSelectedId(uc.use_case_id)}
+ >
+
+
+ {uc.title || "(untitled)"}
+
+ {uc.use_case_id === activeId ? (
+
ACTIVE
+ ) : null}
+
+
+ Updated: {uc.updated_at || uc.created_at || "-"}
+
+
+ ))
+ )}
+
+
+
+
+
Guided Chat
+
+ {Array.isArray(useCase?.messages) && useCase.messages.length ? (
+ useCase.messages.map((m, idx) => (
+
+
+ {m.role === "user" ? "You" : "Assistant"}
+
+
{m.content}
+
+ ))
+ ) : (
+
+ Select a use case and start chatting. You can paste structured
+ info like:
+
+{`Summary: ...
+Problem: ...
+Users: ...
+Requirements:
+- ...
+Acceptance Criteria:
+- ...`}
+
+
+ )}
+
+
+
+
+
+
+
+
+
Spec Preview
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Finalize will save a Markdown spec and mark it ACTIVE for context.
+
+
+ Finalize Spec
+
+
+
+
+
+ );
+}
+
+function Section({ title, value }) {
+ return (
+
+
{title}
+
+ {String(value || "").trim() ? (
+
{value}
+ ) : (
+
(empty)
+ )}
+
+
+ );
+}
+
+function ListSection({ title, items }) {
+ const list = Array.isArray(items) ? items : [];
+ return (
+
+
{title}
+
+ {list.length ? (
+
+ {list.map((x, i) => (
+
+ {x}
+
+ ))}
+
+ ) : (
+
(empty)
+ )}
+
+
+ );
+}
+
+const styles = {
+ wrap: { display: "flex", flexDirection: "column", gap: 12 },
+ topRow: {
+ display: "flex",
+ justifyContent: "space-between",
+ gap: 12,
+ alignItems: "flex-start",
+ flexWrap: "wrap",
+ },
+ left: { minWidth: 280 },
+ right: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" },
+ h1: { fontSize: 14, fontWeight: 800, color: "#fff" },
+ h2: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 4 },
+ titleInput: {
+ width: 260,
+ maxWidth: "70vw",
+ padding: "8px 10px",
+ borderRadius: 10,
+ border: "1px solid rgba(255,255,255,0.18)",
+ background: "rgba(0,0,0,0.25)",
+ color: "#fff",
+ fontSize: 13,
+ outline: "none",
+ },
+ btn: {
+ background: "rgba(255,255,255,0.10)",
+ border: "1px solid rgba(255,255,255,0.18)",
+ color: "#fff",
+ borderRadius: 10,
+ padding: "8px 10px",
+ cursor: "pointer",
+ fontSize: 13,
+ },
+ primaryBtn: {
+ background: "rgba(255,255,255,0.12)",
+ border: "1px solid rgba(255,255,255,0.22)",
+ color: "#fff",
+ borderRadius: 10,
+ padding: "8px 12px",
+ cursor: "pointer",
+ fontSize: 13,
+ fontWeight: 700,
+ },
+ error: {
+ color: "#ffb3b3",
+ fontSize: 12,
+ padding: "8px 10px",
+ border: "1px solid rgba(255,120,120,0.25)",
+ borderRadius: 10,
+ background: "rgba(255,80,80,0.08)",
+ },
+ grid: {
+ display: "grid",
+ gridTemplateColumns: "300px 1.2fr 0.9fr",
+ gap: 12,
+ alignItems: "stretch",
+ },
+ sidebar: {
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ overflow: "hidden",
+ background: "rgba(255,255,255,0.02)",
+ display: "flex",
+ flexDirection: "column",
+ minHeight: 520,
+ },
+ sidebarTitle: {
+ padding: 10,
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
+ fontSize: 12,
+ fontWeight: 800,
+ color: "rgba(255,255,255,0.85)",
+ },
+ sidebarList: {
+ padding: 8,
+ display: "flex",
+ flexDirection: "column",
+ gap: 8,
+ overflow: "auto",
+ },
+ sidebarEmpty: {
+ color: "rgba(255,255,255,0.65)",
+ fontSize: 12,
+ padding: 8,
+ },
+ ucItem: {
+ textAlign: "left",
+ background: "rgba(0,0,0,0.25)",
+ border: "1px solid rgba(255,255,255,0.12)",
+ color: "#fff",
+ borderRadius: 12,
+ padding: 10,
+ cursor: "pointer",
+ },
+ ucItemActive: {
+ border: "1px solid rgba(255,255,255,0.25)",
+ background: "rgba(255,255,255,0.06)",
+ },
+ ucTitleRow: { display: "flex", alignItems: "center", gap: 8 },
+ ucTitle: {
+ fontSize: 13,
+ fontWeight: 800,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ flex: 1,
+ },
+ activePill: {
+ fontSize: 10,
+ fontWeight: 800,
+ padding: "2px 8px",
+ borderRadius: 999,
+ border: "1px solid rgba(120,255,180,0.30)",
+ background: "rgba(120,255,180,0.10)",
+ color: "rgba(200,255,220,0.95)",
+ },
+ ucMeta: {
+ marginTop: 6,
+ fontSize: 11,
+ color: "rgba(255,255,255,0.60)",
+ },
+ chatCol: {
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ overflow: "hidden",
+ display: "flex",
+ flexDirection: "column",
+ background: "rgba(255,255,255,0.02)",
+ minHeight: 520,
+ },
+ specCol: {
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ overflow: "hidden",
+ display: "flex",
+ flexDirection: "column",
+ background: "rgba(255,255,255,0.02)",
+ minHeight: 520,
+ },
+ panelTitle: {
+ padding: 10,
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
+ fontSize: 12,
+ fontWeight: 800,
+ color: "rgba(255,255,255,0.85)",
+ },
+ chatBox: {
+ flex: 1,
+ overflow: "auto",
+ padding: 10,
+ display: "flex",
+ flexDirection: "column",
+ gap: 10,
+ },
+ chatEmpty: {
+ color: "rgba(255,255,255,0.65)",
+ fontSize: 12,
+ padding: 6,
+ },
+ pre: {
+ marginTop: 10,
+ padding: 10,
+ borderRadius: 10,
+ border: "1px solid rgba(255,255,255,0.12)",
+ background: "rgba(0,0,0,0.25)",
+ color: "rgba(255,255,255,0.8)",
+ overflow: "auto",
+ fontSize: 11,
+ },
+ msg: {
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ padding: 10,
+ background: "rgba(0,0,0,0.25)",
+ },
+ msgUser: {
+ border: "1px solid rgba(255,255,255,0.18)",
+ background: "rgba(255,255,255,0.04)",
+ },
+ msgAsst: {},
+ msgRole: {
+ fontSize: 11,
+ fontWeight: 800,
+ color: "rgba(255,255,255,0.70)",
+ marginBottom: 6,
+ },
+ msgContent: {
+ whiteSpace: "pre-wrap",
+ fontSize: 13,
+ color: "rgba(255,255,255,0.90)",
+ lineHeight: 1.35,
+ },
+ composer: {
+ borderTop: "1px solid rgba(255,255,255,0.10)",
+ padding: 10,
+ display: "flex",
+ gap: 10,
+ alignItems: "flex-end",
+ },
+ textarea: {
+ flex: 1,
+ minHeight: 52,
+ maxHeight: 120,
+ resize: "vertical",
+ padding: 10,
+ borderRadius: 12,
+ border: "1px solid rgba(255,255,255,0.18)",
+ background: "rgba(0,0,0,0.25)",
+ color: "#fff",
+ fontSize: 13,
+ outline: "none",
+ },
+ sendBtn: {
+ background: "rgba(255,255,255,0.12)",
+ border: "1px solid rgba(255,255,255,0.22)",
+ color: "#fff",
+ borderRadius: 12,
+ padding: "10px 12px",
+ cursor: "pointer",
+ fontSize: 13,
+ fontWeight: 800,
+ },
+ specBox: {
+ flex: 1,
+ overflow: "auto",
+ padding: 10,
+ display: "flex",
+ flexDirection: "column",
+ gap: 10,
+ },
+ specFooter: {
+ borderTop: "1px solid rgba(255,255,255,0.10)",
+ padding: 10,
+ display: "flex",
+ gap: 10,
+ alignItems: "center",
+ justifyContent: "space-between",
+ },
+ specHint: { fontSize: 12, color: "rgba(255,255,255,0.60)" },
+ section: {
+ border: "1px solid rgba(255,255,255,0.10)",
+ borderRadius: 12,
+ background: "rgba(0,0,0,0.22)",
+ overflow: "hidden",
+ },
+ sectionTitle: {
+ padding: "8px 10px",
+ borderBottom: "1px solid rgba(255,255,255,0.08)",
+ fontSize: 12,
+ fontWeight: 800,
+ color: "rgba(255,255,255,0.80)",
+ background: "rgba(255,255,255,0.02)",
+ },
+ sectionBody: { padding: "8px 10px" },
+ sectionText: {
+ whiteSpace: "pre-wrap",
+ fontSize: 12,
+ color: "rgba(255,255,255,0.90)",
+ lineHeight: 1.35,
+ },
+ sectionEmpty: { fontSize: 12, color: "rgba(255,255,255,0.45)" },
+ ul: { margin: 0, paddingLeft: 18 },
+ li: { color: "rgba(255,255,255,0.90)", fontSize: 12, lineHeight: 1.35 },
+};
diff --git a/frontend/components/ProjectSettingsModal.jsx b/frontend/components/ProjectSettingsModal.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..ff6cc365af5a1c1226d544b425ffa7bbc88698b4
--- /dev/null
+++ b/frontend/components/ProjectSettingsModal.jsx
@@ -0,0 +1,230 @@
+import React, { useEffect, useMemo, useState } from "react";
+import ContextTab from "./ProjectSettings/ContextTab.jsx";
+import UseCaseTab from "./ProjectSettings/UseCaseTab.jsx";
+import ConventionsTab from "./ProjectSettings/ConventionsTab.jsx";
+import EnvironmentSelector from "./EnvironmentSelector.jsx";
+
+export default function ProjectSettingsModal({
+ owner,
+ repo,
+ isOpen,
+ onClose,
+ activeEnvId,
+ onEnvChange,
+}) {
+ const [activeTab, setActiveTab] = useState("context");
+
+ useEffect(() => {
+ if (!isOpen) return;
+ // reset to Context each time opened (safe default)
+ setActiveTab("context");
+ }, [isOpen]);
+
+ const title = useMemo(() => {
+ const repoLabel = owner && repo ? `${owner}/${repo}` : "Project";
+ return `Project Settings — ${repoLabel}`;
+ }, [owner, repo]);
+
+ if (!isOpen) return null;
+
+ return (
+ {
+ // click outside closes
+ if (e.target === e.currentTarget) onClose?.();
+ }}
+ >
+
e.stopPropagation()}>
+
+
+
{title}
+
+ Manage context, use cases, and project conventions (additive only).
+
+
+
+ ✕
+
+
+
+
+ setActiveTab("context")}
+ />
+ setActiveTab("usecase")}
+ />
+ setActiveTab("conventions")}
+ />
+ setActiveTab("environment")}
+ />
+
+
+
+ {activeTab === "context" &&
}
+ {activeTab === "usecase" &&
}
+ {activeTab === "conventions" && (
+
+ )}
+ {activeTab === "environment" && (
+
+
+ Select and configure the execution environment for agent operations.
+
+
+
+ )}
+
+
+
+
+ Tip: Upload meeting notes/transcripts in Context, then finalize a Use
+ Case spec.
+
+
+ Done
+
+
+
+
+ );
+}
+
+function TabButton({ label, isActive, onClick }) {
+ return (
+
+ {label}
+
+ );
+}
+
+const styles = {
+ backdrop: {
+ position: "fixed",
+ inset: 0,
+ background: "rgba(0,0,0,0.45)",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ zIndex: 9999,
+ padding: 16,
+ },
+ modal: {
+ width: "min(1100px, 96vw)",
+ height: "min(760px, 90vh)",
+ background: "#111",
+ border: "1px solid rgba(255,255,255,0.12)",
+ borderRadius: 12,
+ overflow: "hidden",
+ display: "flex",
+ flexDirection: "column",
+ boxShadow: "0 12px 40px rgba(0,0,0,0.35)",
+ },
+ header: {
+ padding: "14px 14px 10px",
+ display: "flex",
+ gap: 12,
+ alignItems: "flex-start",
+ justifyContent: "space-between",
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
+ background: "linear-gradient(180deg, rgba(255,255,255,0.04), transparent)",
+ },
+ headerLeft: {
+ display: "flex",
+ flexDirection: "column",
+ gap: 4,
+ minWidth: 0,
+ },
+ title: {
+ fontSize: 16,
+ fontWeight: 700,
+ color: "#fff",
+ lineHeight: 1.2,
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ maxWidth: "88vw",
+ },
+ subtitle: {
+ fontSize: 12,
+ color: "rgba(255,255,255,0.65)",
+ },
+ closeBtn: {
+ background: "transparent",
+ border: "1px solid rgba(255,255,255,0.18)",
+ color: "rgba(255,255,255,0.85)",
+ borderRadius: 10,
+ padding: "6px 10px",
+ cursor: "pointer",
+ },
+ tabsRow: {
+ display: "flex",
+ gap: 8,
+ padding: 10,
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
+ background: "rgba(255,255,255,0.02)",
+ },
+ tabBtn: {
+ background: "transparent",
+ border: "1px solid rgba(255,255,255,0.14)",
+ color: "rgba(255,255,255,0.75)",
+ borderRadius: 999,
+ padding: "8px 12px",
+ cursor: "pointer",
+ fontSize: 13,
+ },
+ tabBtnActive: {
+ border: "1px solid rgba(255,255,255,0.28)",
+ color: "#fff",
+ background: "rgba(255,255,255,0.06)",
+ },
+ body: {
+ flex: 1,
+ overflow: "auto",
+ padding: 12,
+ },
+ footer: {
+ padding: 12,
+ borderTop: "1px solid rgba(255,255,255,0.10)",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 12,
+ background: "rgba(255,255,255,0.02)",
+ },
+ footerHint: {
+ color: "rgba(255,255,255,0.6)",
+ fontSize: 12,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ },
+ primaryBtn: {
+ background: "rgba(255,255,255,0.10)",
+ border: "1px solid rgba(255,255,255,0.20)",
+ color: "#fff",
+ borderRadius: 10,
+ padding: "8px 12px",
+ cursor: "pointer",
+ },
+};
diff --git a/frontend/components/RepoSelector.jsx b/frontend/components/RepoSelector.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..dd601f4f7cb9b8a19a7858280d5886607a33271c
--- /dev/null
+++ b/frontend/components/RepoSelector.jsx
@@ -0,0 +1,269 @@
+import React, { useEffect, useState, useCallback } from "react";
+import { authFetch } from "../utils/api.js";
+
+export default function RepoSelector({ onSelect }) {
+ const [query, setQuery] = useState("");
+ const [repos, setRepos] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [status, setStatus] = useState("");
+ const [page, setPage] = useState(1);
+ const [hasMore, setHasMore] = useState(false);
+ const [totalCount, setTotalCount] = useState(null);
+
+ /**
+ * Fetch repositories with pagination and optional search
+ * @param {number} pageNum - Page number to fetch
+ * @param {boolean} append - Whether to append or replace results
+ * @param {string} searchQuery - Search query (uses current query if not provided)
+ */
+ const fetchRepos = useCallback(async (pageNum = 1, append = false, searchQuery = query) => {
+ // Set appropriate loading state
+ if (pageNum === 1) {
+ setLoading(true);
+ setStatus("");
+ } else {
+ setLoadingMore(true);
+ }
+
+ try {
+ // Build URL with query parameters
+ const params = new URLSearchParams();
+ params.append("page", pageNum);
+ params.append("per_page", "100");
+ if (searchQuery) {
+ params.append("query", searchQuery);
+ }
+
+ const url = `/api/repos?${params.toString()}`;
+ const res = await authFetch(url);
+ const data = await res.json();
+
+ if (!res.ok) {
+ throw new Error(data.detail || data.error || "Failed to load repositories");
+ }
+
+ // Update repositories - append or replace
+ if (append) {
+ setRepos((prev) => [...prev, ...data.repositories]);
+ } else {
+ setRepos(data.repositories);
+ }
+
+ // Update pagination state
+ setPage(pageNum);
+ setHasMore(data.has_more);
+ setTotalCount(data.total_count);
+
+ // Show status if no results
+ if (!append && data.repositories.length === 0) {
+ if (searchQuery) {
+ setStatus(`No repositories matching "${searchQuery}"`);
+ } else {
+ setStatus("No repositories found");
+ }
+ } else {
+ setStatus("");
+ }
+ } catch (err) {
+ console.error("Error fetching repositories:", err);
+ setStatus(err.message || "Failed to load repositories");
+ } finally {
+ setLoading(false);
+ setLoadingMore(false);
+ }
+ }, [query]);
+
+ /**
+ * Load more repositories (next page)
+ */
+ const loadMore = () => {
+ fetchRepos(page + 1, true);
+ };
+
+ /**
+ * Handle search - resets to page 1
+ */
+ const handleSearch = () => {
+ setPage(1);
+ fetchRepos(1, false, query);
+ };
+
+ /**
+ * Handle input change - trigger search on Enter key
+ */
+ const handleKeyDown = (e) => {
+ if (e.key === "Enter") {
+ handleSearch();
+ }
+ };
+
+ /**
+ * Clear search and show all repos
+ */
+ const clearSearch = () => {
+ setQuery("");
+ setPage(1);
+ fetchRepos(1, false, "");
+ };
+
+ // Initial load on mount
+ useEffect(() => {
+ fetchRepos(1, false, "");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ /**
+ * Format repository count for display
+ */
+ const getCountText = () => {
+ if (totalCount !== null) {
+ // Search mode - show filtered count
+ return `${repos.length} of ${totalCount} repositories`;
+ } else {
+ // Pagination mode - show loaded count
+ return `${repos.length} ${repos.length === 1 ? "repository" : "repositories"}${hasMore ? "+" : ""}`;
+ }
+ };
+
+ return (
+
+
+ GitHub repos are optional. Use Folder or Local Git mode for local-first workflows.
+
+ {/* Search Header */}
+
+
+ setQuery(e.target.value)}
+ onKeyDown={handleKeyDown}
+ disabled={loading}
+ />
+
+ {loading ? "..." : "Search"}
+
+
+
+ {/* Search Info Bar */}
+ {(query || repos.length > 0) && (
+
+ {getCountText()}
+ {query && (
+
+ Clear search
+
+ )}
+
+ )}
+
+
+ {/* Status Message */}
+ {status && !loading && (
+
+ {status}
+
+ )}
+
+ {/* Repository List */}
+
+ {repos.map((r) => (
+
onSelect(r)}
+ >
+
+ {r.name}
+ {r.owner}
+
+ {r.private && (
+ Private
+ )}
+
+ ))}
+
+ {/* Loading Indicator */}
+ {loading && repos.length === 0 && (
+
+
+
Loading repositories...
+
+ )}
+
+ {/* Load More Button */}
+ {hasMore && !loading && repos.length > 0 && (
+
+ {loadingMore ? (
+ <>
+
+ Loading more...
+ >
+ ) : (
+ <>
+ Load more repositories
+ ({repos.length} loaded)
+ >
+ )}
+
+ )}
+
+ {/* All Loaded Message */}
+ {!hasMore && !loading && repos.length > 0 && (
+
+ ✓ All repositories loaded ({repos.length} total)
+
+ )}
+
+
+ {/* GitHub App Installation Notice */}
+
+
+
+
+
+
+
+ Repository missing?
+
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/components/RunnableCodeBlock.jsx b/frontend/components/RunnableCodeBlock.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..818e4950ffdded978b29f5098bfc47a6f7cf7f3c
--- /dev/null
+++ b/frontend/components/RunnableCodeBlock.jsx
@@ -0,0 +1,486 @@
+import React, { useState } from "react";
+import SandboxCanvas from "./SandboxCanvas.jsx";
+import ExecutionPlanCard, { fetchExecutionPlan } from "./ExecutionPlanCard.jsx";
+
+// Languages the Run button supports. Anything not in this set still
+// renders as a normal code block (no button) — keeps the visual contract
+// honest: if there's a button, the snippet really is executable.
+const RUNNABLE = new Set([
+ "python", "py",
+ "javascript", "js", "node",
+ "bash", "sh", "shell",
+]);
+
+// Friendly badge text per backend, surfaced so the user always knows
+// which sandbox actually ran their code. Mirrors the labels in
+// SettingsModal so the two views agree.
+const BACKEND_LABELS = {
+ subprocess: "Local",
+ matrixlab: "MatrixLab",
+ off: "Pass-through",
+};
+
+// Map "py" → "python" etc. so the badge always shows the canonical
+// language name rather than whatever alias the LLM tagged the fence
+// with.
+const LANG_DISPLAY = {
+ py: "python",
+ js: "javascript",
+ node: "javascript",
+ sh: "bash",
+ shell: "bash",
+};
+
+// Default file extension per language — used when the user clicks
+// "Save to repo" and we need to seed a plausible filename.
+const LANG_EXT = {
+ python: "py", py: "py",
+ javascript: "js", js: "js", node: "js",
+ bash: "sh", sh: "sh", shell: "sh",
+};
+
+// Mirror executor's _looks_like_matplotlib heuristic so plt.show()
+// snippets don't hang the headless sandbox. False positives are
+// harmless (Agg is a valid backend for any Python script).
+function looksLikeMatplotlib(code) {
+ if (!code) return false;
+ const lower = code.toLowerCase();
+ return /import\s+matplotlib|from\s+matplotlib|plt\.show|pyplot/.test(lower);
+}
+
+function applyMatplotlibShim(language, code) {
+ if (language !== "python" && language !== "py") return code;
+ if (!looksLikeMatplotlib(code)) return code;
+ return (
+ "import os as _gp_os\n" +
+ '_gp_os.environ.setdefault("MPLBACKEND", "Agg")\n' +
+ code
+ );
+}
+
+/** A single fenced code block with a per-block Run button.
+ *
+ * Optional ``owner``/``repo`` props enable the "Save to repo" button by
+ * giving the save call a real target. When absent the button is
+ * hidden — keeps the contract honest: no button without somewhere to
+ * save. */
+export default function RunnableCodeBlock({ language, code, owner, repo }) {
+ const lang = (language || "").trim().toLowerCase();
+ const canRun = RUNNABLE.has(lang);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState(null);
+ const [error, setError] = useState(null);
+ const [canvasOpen, setCanvasOpen] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [saveMsg, setSaveMsg] = useState(null);
+ // Approval-first: clicking ▶ Run first fetches a deterministic
+ // ExecutionPlan and surfaces it inline. The actual sandbox call
+ // is gated on the user clicking "Run in Sandbox" inside the plan.
+ const [pendingPlan, setPendingPlan] = useState(null);
+ const [planError, setPlanError] = useState(null);
+ const display = LANG_DISPLAY[lang] || lang || "text";
+
+ const onRunClick = async () => {
+ setPlanError(null);
+ setResult(null);
+ setError(null);
+ setBusy(true);
+ try {
+ const shipped = applyMatplotlibShim(lang, code);
+ const plan = await fetchExecutionPlan({
+ code: shipped,
+ language: lang,
+ source: "code_block",
+ });
+ setPendingPlan(plan);
+ } catch (err) {
+ setPlanError(err.message || "Could not build execution plan");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const onApprovePlan = async (plan) => {
+ setBusy(true);
+ setResult(null);
+ setError(null);
+ try {
+ const res = await fetch("/api/sandbox/run", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ language: plan.language,
+ code: plan.inline_code,
+ timeout_sec: plan.timeout_sec,
+ }),
+ });
+ const data = await res.json();
+ if (!res.ok) {
+ setError(data.detail || `HTTP ${res.status}`);
+ return;
+ }
+ setResult(data);
+ setPendingPlan(null);
+ } catch (err) {
+ setError(err.message || "Run failed");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const onCancelPlan = () => {
+ setPendingPlan(null);
+ setPlanError(null);
+ };
+
+ const copy = () => {
+ if (navigator?.clipboard) navigator.clipboard.writeText(code).catch(() => {});
+ };
+
+ // POST the snippet to /api/repos/{owner}/{repo}/file with a path
+ // chosen by the user. Pure client-side prompt — no new backend
+ // wiring needed because the endpoint already exists.
+ const saveToRepo = async (snippet, snippetLang) => {
+ if (!owner || !repo) {
+ setSaveMsg("No repository context — open this chat inside a repo to save.");
+ return;
+ }
+ const ext = LANG_EXT[(snippetLang || lang).toLowerCase()] || "txt";
+ const suggested = `snippets/inline.${ext}`;
+ const path = window.prompt("Save snippet to path (inside repo):", suggested);
+ if (!path) return;
+ setSaving(true);
+ setSaveMsg(null);
+ try {
+ const res = await fetch(`/api/repos/${owner}/${repo}/file`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ path,
+ content: snippet,
+ message: `Save snippet from chat (${path})`,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ setSaveMsg(data.detail || `Save failed (HTTP ${res.status})`);
+ return;
+ }
+ setSaveMsg(`Saved to ${path}`);
+ } catch (err) {
+ setSaveMsg(err.message || "Save failed");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+
+
+
{display}
+
+
+ Copy
+
+ {canRun && (
+ setCanvasOpen(true)}
+ title="Open the snippet in the Canvas split-view editor"
+ >
+ ⊞ Canvas
+
+ )}
+ {canRun && owner && repo && (
+ saveToRepo(code, lang)}
+ disabled={saving}
+ title="Save this snippet as a file in the current repository"
+ >
+ {saving ? "Saving…" : "Save"}
+
+ )}
+ {canRun && (
+
+ {busy && !pendingPlan ? "Preparing…" : "▶ Run"}
+
+ )}
+
+
+
{code}
+
+ {pendingPlan && (
+
+ )}
+ {planError && (
+
Plan error: {planError}
+ )}
+
+ {(result || error) && (
+
+
+ Output
+ {result && (
+
+
+ exit {result.exit_code}
+
+
+ {BACKEND_LABELS[result.backend] || result.backend}
+
+ {typeof result.duration_ms === "number" && (
+ {result.duration_ms} ms
+ )}
+ {result.timed_out && timed out }
+ {result.truncated && truncated }
+
+ )}
+
+ {error &&
{error} }
+ {result?.stdout &&
{result.stdout} }
+ {result?.stderr &&
{result.stderr} }
+ {Array.isArray(result?.artifacts) && result.artifacts.length > 0 && (
+
+
Artifacts ({result.artifacts.length})
+
+ {result.artifacts.map((a, i) => (
+
+ {a.name || a.id}
+ {a.size && · {a.size} bytes }
+ {a.mime && · {a.mime} }
+
+ ))}
+
+
+ )}
+ {result && !result.stdout && !result.stderr && (
+
(no output)
+ )}
+
+ )}
+
+ {saveMsg &&
{saveMsg}
}
+
+ {canvasOpen && (
+
setCanvasOpen(false)}
+ onSaveAsFile={owner && repo ? saveToRepo : undefined}
+ />
+ )}
+
+ );
+}
+
+/** Split a markdown-ish string into text and fenced-code segments.
+ *
+ * Returned shape: ``[{type: 'text', value} | {type: 'code', language, code}]``.
+ *
+ * Kept deliberately small — full markdown rendering is out of scope; this
+ * only needs to recognise ```lang fences so the Run button can attach to
+ * code blocks the model emits. */
+export function splitFences(input) {
+ if (!input) return [];
+ const out = [];
+ const re = /```([a-zA-Z0-9_+-]*)\s*\n([\s\S]*?)```/g;
+ let last = 0;
+ let m;
+ while ((m = re.exec(input)) !== null) {
+ if (m.index > last) {
+ out.push({ type: "text", value: input.slice(last, m.index) });
+ }
+ out.push({ type: "code", language: m[1] || "", code: m[2].replace(/\s+$/, "") });
+ last = m.index + m[0].length;
+ }
+ if (last < input.length) {
+ out.push({ type: "text", value: input.slice(last) });
+ }
+ return out;
+}
+
+const styles = {
+ wrap: {
+ margin: "8px 0",
+ background: "#09090B",
+ border: "1px solid #27272A",
+ borderRadius: 8,
+ overflow: "hidden",
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
+ },
+ head: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "6px 12px",
+ background: "#18181B",
+ borderBottom: "1px solid #27272A",
+ fontSize: 11,
+ },
+ headRight: { display: "flex", gap: 6, alignItems: "center" },
+ lang: {
+ color: "#A1A1AA",
+ fontWeight: 600,
+ textTransform: "uppercase",
+ letterSpacing: "0.05em",
+ fontSize: 10,
+ },
+ iconBtn: {
+ background: "transparent",
+ color: "#A1A1AA",
+ border: "1px solid #3F3F46",
+ borderRadius: 4,
+ padding: "2px 8px",
+ fontSize: 11,
+ cursor: "pointer",
+ },
+ runBtn: {
+ background: "#10B981",
+ color: "#052e1c",
+ border: "0",
+ borderRadius: 4,
+ padding: "2px 10px",
+ fontSize: 11,
+ fontWeight: 600,
+ cursor: "pointer",
+ },
+ code: {
+ margin: 0,
+ padding: "12px 14px",
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
+ fontSize: 12.5,
+ lineHeight: 1.55,
+ color: "#E4E4E7",
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ overflowX: "auto",
+ },
+ output: {
+ background: "#0c0c10",
+ borderTop: "1px solid #27272A",
+ padding: "8px 14px 10px",
+ },
+ outputHead: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ marginBottom: 6,
+ },
+ outputLabel: {
+ fontSize: 10,
+ fontWeight: 600,
+ color: "#A1A1AA",
+ textTransform: "uppercase",
+ letterSpacing: "0.05em",
+ },
+ metaRow: { display: "flex", gap: 6, alignItems: "center" },
+ okPill: {
+ fontSize: 10,
+ fontWeight: 600,
+ padding: "1px 6px",
+ borderRadius: 9,
+ background: "rgba(16, 185, 129, 0.12)",
+ color: "#10B981",
+ border: "1px solid rgba(16, 185, 129, 0.35)",
+ },
+ failPill: {
+ fontSize: 10,
+ fontWeight: 600,
+ padding: "1px 6px",
+ borderRadius: 9,
+ background: "rgba(239, 68, 68, 0.12)",
+ color: "#ef4444",
+ border: "1px solid rgba(239, 68, 68, 0.35)",
+ },
+ warnPill: {
+ fontSize: 10,
+ fontWeight: 600,
+ padding: "1px 6px",
+ borderRadius: 9,
+ background: "rgba(217, 119, 6, 0.12)",
+ color: "#f59e0b",
+ border: "1px solid rgba(217, 119, 6, 0.35)",
+ },
+ backendPill: {
+ fontSize: 10,
+ fontWeight: 600,
+ padding: "1px 6px",
+ borderRadius: 9,
+ background: "rgba(79, 70, 229, 0.12)",
+ color: "#a5b4fc",
+ border: "1px solid rgba(79, 70, 229, 0.35)",
+ },
+ dim: { color: "#71717A", fontSize: 11 },
+ stdout: {
+ margin: "4px 0 0",
+ padding: "6px 8px",
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
+ fontSize: 12,
+ color: "#D4D4D8",
+ background: "#000",
+ borderRadius: 4,
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ },
+ stderr: {
+ margin: "4px 0 0",
+ padding: "6px 8px",
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
+ fontSize: 12,
+ color: "#fca5a5",
+ background: "#0a0000",
+ borderRadius: 4,
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ },
+ artifactsBox: {
+ marginTop: 8,
+ padding: "6px 8px",
+ background: "#0a0a0f",
+ border: "1px solid #27272A",
+ borderRadius: 4,
+ },
+ artifactList: {
+ listStyle: "none",
+ padding: 0,
+ margin: "4px 0 0",
+ },
+ artifactItem: {
+ padding: "2px 0",
+ fontSize: 12,
+ color: "#D4D4D8",
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
+ },
+ saveBanner: {
+ margin: "0",
+ padding: "6px 12px",
+ fontSize: 11,
+ color: "#A1A1AA",
+ background: "#0c0c10",
+ borderTop: "1px solid #27272A",
+ },
+ errorBanner: {
+ margin: "6px 0",
+ padding: "8px 10px",
+ fontSize: 12,
+ color: "#fca5a5",
+ background: "#3d1111",
+ border: "1px solid #7f1d1d",
+ borderRadius: 6,
+ },
+};
diff --git a/frontend/components/SandboxCanvas.jsx b/frontend/components/SandboxCanvas.jsx
new file mode 100644
index 0000000000000000000000000000000000000000..8b98fdc9061717f838bcc2df788b562c2d0a141b
--- /dev/null
+++ b/frontend/components/SandboxCanvas.jsx
@@ -0,0 +1,1052 @@
+// frontend/components/SandboxCanvas.jsx
+//
+// File-aware Canvas: a modal that adapts to the file type it was
+// opened with. Three modes:
+//
+// code → split editor + sandbox output. Prepare-Run flow.
+// Used for .py / .js / .sh / inline snippets.
+// markdown → split source + rendered preview. No Run button.
+// Used for .md / .markdown.
+// text → source-only viewer (read-only by default).
+// Used for everything else: .json, .yml, .csv,
+// .html, .txt, ...
+//
+// Mode is computed from the ``filename`` prop's extension. When
+// ``filename`` is null (an anonymous inline snippet from a chat code
+// block) we fall back to code mode using the ``initialLanguage`` tag.
+//
+// The sandbox approval contract is unchanged: Prepare Run dispatches
+// /api/sandbox/plan, the user approves a green ExecutionPlanCard,
+// only then /api/sandbox/run actually executes.
+
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { fetchExecutionPlan } from "./ExecutionPlanCard.jsx";
+
+const BACKEND_LABELS = {
+ subprocess: "Local",
+ matrixlab: "MatrixLab",
+ off: "Pass-through",
+};
+
+const LANG_DISPLAY = {
+ py: "python", js: "javascript", node: "javascript",
+ sh: "bash", shell: "bash",
+};
+
+// Extensions that route through the sandbox. Everything else gets
+// a viewer-only canvas — README.md must NOT show a Python execution
+// plan, JSON must NOT pretend it can run.
+const RUNNABLE_EXTS = new Set(["py", "js", "mjs", "cjs", "sh", "bash"]);
+const MARKDOWN_EXTS = new Set(["md", "markdown", "mdx"]);
+
+// Map extension → canonical sandbox language tag used by the planner.
+const EXT_TO_LANG = {
+ py: "python", js: "javascript", mjs: "javascript", cjs: "javascript",
+ sh: "bash", bash: "bash",
+};
+
+// Display label per file type — keeps the header honest about what
+// the Canvas is showing.
+const TYPE_LABEL = {
+ python: "Python", javascript: "JavaScript", bash: "Shell",
+ markdown: "Markdown", json: "JSON", yaml: "YAML", csv: "CSV",
+ html: "HTML", text: "Text",
+};
+
+function extOf(name) {
+ if (!name || !name.includes(".")) return "";
+ return name.split(".").pop().toLowerCase();
+}
+
+// Decide which Canvas branch to render based on the opening context.
+// Pure function so tests can pin it.
+function resolveCanvasMode({ filename, initialLanguage }) {
+ const ext = extOf(filename || "");
+ if (filename && MARKDOWN_EXTS.has(ext)) {
+ return { kind: "markdown", typeLabel: "Markdown", language: "markdown" };
+ }
+ if (filename && RUNNABLE_EXTS.has(ext)) {
+ const lang = EXT_TO_LANG[ext];
+ return { kind: "code", typeLabel: TYPE_LABEL[lang], language: lang };
+ }
+ if (filename) {
+ // Known-but-non-runnable: json / yaml / csv / html / txt / etc.
+ const known = { json: "json", yml: "yaml", yaml: "yaml",
+ csv: "csv", html: "html", txt: "text" }[ext];
+ if (known) {
+ return { kind: "text", typeLabel: TYPE_LABEL[known], language: known };
+ }
+ return { kind: "text", typeLabel: ext.toUpperCase() || "Text", language: "text" };
+ }
+ // No filename → inline snippet from a chat code block. Honor the
+ // language tag the chat fence carried.
+ const tag = (initialLanguage || "python").toLowerCase();
+ if (tag === "py" || tag === "python") return { kind: "code", typeLabel: "Python snippet", language: "python" };
+ if (tag === "js" || tag === "javascript" || tag === "node")
+ return { kind: "code", typeLabel: "JavaScript snippet", language: "javascript" };
+ if (tag === "sh" || tag === "bash" || tag === "shell")
+ return { kind: "code", typeLabel: "Shell snippet", language: "bash" };
+ return { kind: "text", typeLabel: "Text", language: "text" };
+}
+
+// Minimal, dependency-free Markdown → HTML renderer. Covers the
+// patterns that matter for README files: headings, bold, italic,
+// inline code, fenced code blocks, lists, links. Escapes HTML to
+// avoid XSS when README contains
+