github-actions[bot] commited on
Commit
708ad2c
·
0 Parent(s):

Deploy from 1b731f39

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +98 -0
  2. README.md +80 -0
  3. REPO_README.md +463 -0
  4. frontend/.dockerignore +39 -0
  5. frontend/App.jsx +1392 -0
  6. frontend/components/AboutModal.jsx +488 -0
  7. frontend/components/AddRepoModal.jsx +256 -0
  8. frontend/components/AdminTabs/AccountTab.jsx +305 -0
  9. frontend/components/AdminTabs/AdvancedTab.jsx +360 -0
  10. frontend/components/AdminTabs/IntegrationsTab.jsx +220 -0
  11. frontend/components/AdminTabs/MCPServersTab.jsx +349 -0
  12. frontend/components/AdminTabs/MatrixLabInstallModal.jsx +1013 -0
  13. frontend/components/AdminTabs/SandboxTab.jsx +218 -0
  14. frontend/components/AdminTabs/SecurityTab.jsx +341 -0
  15. frontend/components/AdminTabs/SessionsTab.jsx +362 -0
  16. frontend/components/AdminTabs/SkillsTab.jsx +266 -0
  17. frontend/components/AdminTabs/WorkspaceModesTab.jsx +267 -0
  18. frontend/components/AdminTabs/index.js +11 -0
  19. frontend/components/AdminTabs/mcp/CatalogList.jsx +101 -0
  20. frontend/components/AdminTabs/mcp/CustomInstallForm.jsx +134 -0
  21. frontend/components/AdminTabs/mcp/GatewayForm.jsx +379 -0
  22. frontend/components/AdminTabs/mcp/GatewayHeader.jsx +145 -0
  23. frontend/components/AdminTabs/mcp/ServerCard.jsx +334 -0
  24. frontend/components/AdminTabs/mcp/SyncReport.jsx +152 -0
  25. frontend/components/AdminTabs/mcp/ToolRow.jsx +149 -0
  26. frontend/components/AssistantMessage.jsx +428 -0
  27. frontend/components/AuthPage.jsx +459 -0
  28. frontend/components/BranchPicker.jsx +398 -0
  29. frontend/components/ChatPanel.jsx +1331 -0
  30. frontend/components/ContextBar.jsx +156 -0
  31. frontend/components/ContextMeter.jsx +411 -0
  32. frontend/components/CreatePRButton.jsx +160 -0
  33. frontend/components/DiffStats.jsx +59 -0
  34. frontend/components/DiffViewer.jsx +263 -0
  35. frontend/components/EnvironmentEditor.jsx +278 -0
  36. frontend/components/EnvironmentSelector.jsx +200 -0
  37. frontend/components/ExecutionPlanCard.jsx +302 -0
  38. frontend/components/FilePreviewPanel.jsx +463 -0
  39. frontend/components/FileTree.jsx +570 -0
  40. frontend/components/FlowViewer.jsx +664 -0
  41. frontend/components/Footer.jsx +48 -0
  42. frontend/components/LandingPage.jsx +474 -0
  43. frontend/components/LlmSettings.jsx +647 -0
  44. frontend/components/LoginPage.jsx +544 -0
  45. frontend/components/PlanView.jsx +152 -0
  46. frontend/components/ProjectContextPanel.jsx +585 -0
  47. frontend/components/ProjectSettings/ContextTab.jsx +353 -0
  48. frontend/components/ProjectSettings/ConventionsTab.jsx +152 -0
  49. frontend/components/ProjectSettings/UseCaseTab.jsx +638 -0
  50. frontend/components/ProjectSettingsModal.jsx +230 -0
Dockerfile ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # GitPilot - Hugging Face Spaces Dockerfile
3
+ # =============================================================================
4
+ # Follows the official HF Docker Spaces pattern:
5
+ # https://huggingface.co/docs/hub/spaces-sdks-docker
6
+ #
7
+ # Architecture:
8
+ # React UI (Vite build) -> FastAPI backend -> OllaBridge Cloud / any LLM
9
+ # =============================================================================
10
+
11
+ # -- Stage 1: Build React frontend -------------------------------------------
12
+ FROM node:20-slim AS frontend-builder
13
+
14
+ WORKDIR /build
15
+
16
+ COPY frontend/package.json frontend/package-lock.json ./
17
+ RUN npm ci --production=false
18
+
19
+ COPY frontend/ ./
20
+ RUN npm run build
21
+
22
+ # -- Stage 2: Python runtime -------------------------------------------------
23
+ FROM python:3.12-slim
24
+
25
+ # System deps needed at runtime
26
+ RUN apt-get update && apt-get install -y --no-install-recommends \
27
+ git curl ca-certificates \
28
+ && rm -rf /var/lib/apt/lists/*
29
+
30
+ # HF Spaces runs containers as UID 1000 — create user early (official pattern)
31
+ RUN useradd -m -u 1000 user
32
+
33
+ USER user
34
+
35
+ ENV HOME=/home/user \
36
+ PATH=/home/user/.local/bin:$PATH \
37
+ PYTHONUNBUFFERED=1 \
38
+ GITPILOT_PROVIDER=ollabridge \
39
+ OLLABRIDGE_BASE_URL=https://ruslanmv-ollabridge.hf.space \
40
+ GITPILOT_OLLABRIDGE_MODEL=qwen2.5:1.5b \
41
+ CORS_ORIGINS="*" \
42
+ GITPILOT_CONFIG_DIR=/tmp/gitpilot
43
+
44
+ WORKDIR $HOME/app
45
+
46
+ # ── Install Python dependencies BEFORE copying source code ──────────
47
+ # This ensures pip install layers are cached even when code changes.
48
+ COPY --chown=user pyproject.toml README.md ./
49
+
50
+ # Step 1: lightweight deps (cached layer)
51
+ RUN pip install --no-cache-dir --upgrade pip && \
52
+ pip install --no-cache-dir \
53
+ "fastapi>=0.111.0" \
54
+ "uvicorn[standard]>=0.30.0" \
55
+ "httpx>=0.27.0" \
56
+ "python-dotenv>=1.1.0,<1.2.0" \
57
+ "typer>=0.12.0,<0.24.0" \
58
+ "pydantic>=2.7.0,<2.12.0" \
59
+ "rich>=13.0.0" \
60
+ "pyjwt[crypto]>=2.8.0" \
61
+ "psycopg[binary]>=3.1" \
62
+ "resend>=2.0.0"
63
+
64
+ # Step 2: heavy ML/agent deps (separate layer for better caching)
65
+ RUN pip install --no-cache-dir \
66
+ "litellm" \
67
+ "crewai[anthropic]>=0.76.9" \
68
+ "crewai-tools>=0.13.4" \
69
+ "anthropic>=0.39.0" \
70
+ "ibm-watsonx-ai>=1.1.0" \
71
+ "langchain-ibm>=0.3.0"
72
+
73
+ # ── Now copy source code (cache-busting only affects layers below) ──
74
+ COPY --chown=user gitpilot ./gitpilot
75
+
76
+ # Copy built frontend into gitpilot/web/
77
+ COPY --chown=user --from=frontend-builder /build/dist/ ./gitpilot/web/
78
+
79
+ # Step 3: editable install of gitpilot itself (deps already satisfied)
80
+ RUN pip install --no-cache-dir --no-deps -e .
81
+
82
+ EXPOSE 7860
83
+
84
+ # NOTE: Do NOT add a Docker HEALTHCHECK here.
85
+ # HF Spaces has its own HTTP probe on app_port (7860) and ignores the
86
+ # Docker HEALTHCHECK directive.
87
+
88
+ # Direct CMD — no shell script, fewer failure points.
89
+ # Single worker: the Matrix run registry (gitpilot.matrix_runs_router._RUNS) is
90
+ # in-memory per worker, so multiple workers would scatter a run's status/diff/
91
+ # logs across processes and 404 intermittently. One worker keeps run state
92
+ # consistent; back the registry with a shared store to scale workers later.
93
+ CMD ["python", "-m", "uvicorn", "gitpilot.api:app", \
94
+ "--host", "0.0.0.0", \
95
+ "--port", "7860", \
96
+ "--workers", "1", \
97
+ "--limit-concurrency", "10", \
98
+ "--timeout-keep-alive", "120"]
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: GitPilot
3
+ emoji: "\U0001F916"
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ startup_duration_timeout: 5m
9
+ pinned: true
10
+ license: mit
11
+ short_description: Enterprise AI Coding Assistant for GitHub Repositories
12
+ ---
13
+
14
+ # GitPilot — Hugging Face Spaces
15
+
16
+ **Enterprise-grade AI coding assistant** for GitHub repositories with multi-LLM support, visual workflow insights, and intelligent code analysis.
17
+
18
+ ## What This Does
19
+
20
+ This Space runs the full GitPilot stack:
21
+ 1. **React Frontend** — Professional dark-theme UI with chat, file browser, and workflow visualization
22
+ 2. **FastAPI Backend** — 80+ API endpoints for repository management, AI chat, planning, and execution
23
+ 3. **Multi-Agent AI** — CrewAI orchestration with 7 switchable agent topologies
24
+
25
+ ## LLM Providers
26
+
27
+ GitPilot connects to your favorite LLM provider. Configure in **Admin / LLM Settings**:
28
+
29
+ | Provider | Default | API Key Required |
30
+ |---|---|---|
31
+ | **OllaBridge Cloud** (default) | `qwen2.5:1.5b` | No |
32
+ | OpenAI | `gpt-4o-mini` | Yes |
33
+ | Anthropic Claude | `claude-sonnet-4-5` | Yes |
34
+ | Ollama (local) | `llama3` | No |
35
+ | Custom endpoint | Any model | Optional |
36
+
37
+ ## Quick Start
38
+
39
+ 1. Open the Space UI
40
+ 2. Enter your **GitHub Token** (Settings -> GitHub)
41
+ 3. Select a repository from the sidebar
42
+ 4. Start chatting with your AI coding assistant
43
+
44
+ ## API Endpoints
45
+
46
+ | Endpoint | Description |
47
+ |---|---|
48
+ | `GET /api/health` | Health check |
49
+ | `POST /api/chat/message` | Chat with AI assistant |
50
+ | `POST /api/chat/plan` | Generate implementation plan |
51
+ | `GET /api/repos` | List repositories |
52
+ | `GET /api/settings` | View/update settings |
53
+ | `GET /docs` | Interactive API docs (Swagger) |
54
+
55
+ ## Connect to OllaBridge Cloud
56
+
57
+ 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.
58
+
59
+ To use your own OllaBridge instance:
60
+ 1. Go to **Admin / LLM Settings**
61
+ 2. Select **OllaBridge** provider
62
+ 3. Enter your OllaBridge URL and model
63
+
64
+ ## Environment Variables
65
+
66
+ Configure via HF Spaces secrets:
67
+
68
+ | Variable | Description | Default |
69
+ |---|---|---|
70
+ | `GITPILOT_PROVIDER` | LLM provider | `ollabridge` |
71
+ | `OLLABRIDGE_BASE_URL` | OllaBridge Cloud URL | `https://ruslanmv-ollabridge.hf.space` |
72
+ | `GITHUB_TOKEN` | GitHub personal access token | - |
73
+ | `OPENAI_API_KEY` | OpenAI API key (if using OpenAI) | - |
74
+ | `ANTHROPIC_API_KEY` | Anthropic API key (if using Claude) | - |
75
+
76
+ ## Links
77
+
78
+ - [GitPilot Repository](https://github.com/ruslanmv/gitpilot)
79
+ - [OllaBridge Cloud](https://huggingface.co/spaces/ruslanmv/ollabridge)
80
+ - [Documentation](https://github.com/ruslanmv/gitpilot#readme)
REPO_README.md ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="docs/logo.svg" alt="GitPilot" width="140" />
4
+
5
+ # GitPilot
6
+
7
+ ### The first open-source multi-agent AI coding assistant.
8
+
9
+ Ten specialized agents — Explorer, Planner, Coder, Reviewer and six more — collaborate on every task, coordinated by a router that picks the right ones for the request. By default, GitPilot requests confirmation before executing high-impact actions. Switch to Auto or Plan mode at any time.
10
+
11
+ [![PyPI](https://img.shields.io/pypi/v/gitcopilot?style=flat-square&color=D95C3D&labelColor=1C1C1F&label=pypi)](https://pypi.org/project/gitcopilot/)
12
+ [![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12-D95C3D?style=flat-square&labelColor=1C1C1F)](https://www.python.org/)
13
+ [![License](https://img.shields.io/badge/license-Apache%202.0-D95C3D?style=flat-square&labelColor=1C1C1F)](LICENSE)
14
+ [![VS Code](https://img.shields.io/badge/VS%20Code-Extension-D95C3D?style=flat-square&labelColor=1C1C1F)](https://marketplace.visualstudio.com/)
15
+ [![Tests](https://img.shields.io/badge/tests-2218%20passing-D95C3D?style=flat-square&labelColor=1C1C1F)](#contributing)
16
+
17
+ [**Get Started**](#get-started) &nbsp;·&nbsp; [VS Code](#vs-code-extension) &nbsp;·&nbsp; [Web App](#web-app) &nbsp;·&nbsp; [How It Works](#how-it-works) &nbsp;·&nbsp; [Providers](#supported-ai-providers)
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ <p align="center">
24
+ <picture>
25
+ <source srcset="docs/assets/flow.svg" type="image/svg+xml" />
26
+ <img src="docs/assets/flow.png" alt="GitPilot loop: Ask, Plan, Code, Ship — you approve every change." width="900" />
27
+ </picture>
28
+ </p>
29
+
30
+ ## Why GitPilot?
31
+
32
+ Most AI coding tools are a **single model behind a chat box**. GitPilot is fundamentally different: a **request router** inspects each task and dispatches it to the specialists that fit — just like a real engineering team.
33
+
34
+ > **Matrix‑native:** GitPilot is the worker for [Matrix Builder](https://github.com/agent-matrix/matrix-builder) — it runs a signed Matrix Bundle under contract via `POST /api/v1/gitpilot/runs` (A2A‑secured), returns a controlled diff, and never approves or commits its own work.
35
+
36
+ ### The agent roster
37
+
38
+ Ten specialists. Which ones run depends on the request and the
39
+ [topology](docs/agents.md) in force — a small change may use one, a feature
40
+ build uses five.
41
+
42
+ | Agent | Role | What it does |
43
+ |---|---|---|
44
+ | **Explorer** | Context | Reads your repo, git log, test suite, and dependencies so the plan starts with real knowledge — not guesses |
45
+ | **Planner** | Strategy | Drafts a safe, step-by-step plan with diffs and surfaces risks before any file is touched |
46
+ | **Coder** | Execution | Writes code, runs your tests, and self-corrects on failure — iterating until the suite passes |
47
+ | **Reviewer** | Quality | Audits changes for security, quality, test coverage and performance, ranked by severity |
48
+ | **Issue Manager** | GitHub | Creates, updates, triages and closes issues |
49
+ | **PR Manager** | GitHub | Opens branches, commits, pushes, and drafts pull requests with a test plan |
50
+ | **Search & Discovery** | GitHub | Searches code, repositories, issues and users |
51
+ | **Learning & Guidance** | GitHub | Explains GitHub features and best practices |
52
+ | **Local Editor** | Workspace | Reads and writes files directly in your local workspace |
53
+ | **Terminal** | Workspace | Runs shell commands inside the sandbox |
54
+
55
+ **Full details:** [Agent architecture and topologies](docs/agents.md).
56
+
57
+ **You control how the agent runs.** Three execution modes — selectable per session from the VS Code compose bar or backend API:
58
+
59
+ | Mode | Default? | Behavior |
60
+ |---|---|---|
61
+ | **Ask** | Yes | Prompts you before each dangerous action (write, edit, run, commit). You see the diff and click Allow / Deny. |
62
+ | **Auto** | | Executes all tools automatically. Fastest for experienced users who trust the plan. |
63
+ | **Plan** | | Read-only. Generates and displays the plan but blocks all file writes and commands. |
64
+
65
+ Diffs are shown before they're applied. Tests run before anything is committed. No surprises.
66
+
67
+ ### What else sets GitPilot apart
68
+
69
+ - 🧭 **Works where you work** — VS Code, web app, and CLI share one login, one history, and one set of approvals.
70
+ - 🧠 **Any LLM, zero lock-in** — OpenAI, Anthropic Claude, IBM Watsonx, Ollama (local & free) or OllaBridge. Switch in settings, no code change.
71
+ - 🔐 **Private by default** — run the entire stack locally with Ollama. No telemetry, no data leaves your machine.
72
+ - 🏢 **Enterprise-ready, Apache 2.0 open source** — 2,218 passing tests, Docker & Hugging Face deployment recipes, audit the code yourself.
73
+ - 🌍 **Runs anywhere** — laptop, private cloud, air-gapped environments, or managed hosting. Your repo, your rules.
74
+
75
+ ---
76
+
77
+ ## What is GitPilot?
78
+
79
+ 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.
80
+
81
+ **Works with any language. Runs on any LLM.** Start free and local with Ollama, or bring your own OpenAI, Claude, or Watsonx key.
82
+
83
+ ```
84
+ You: "Add input validation to the login form"
85
+
86
+ GitPilot:
87
+ 1. Reading src/auth/login.ts...
88
+ 2. Planning 3 changes...
89
+ 3. Editing login.ts → [Apply Patch] [Revert]
90
+ 4. Running npm test... 3 passed
91
+ 5. Done — files written to your workspace.
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Get Started
97
+
98
+ ### Option 1: VS Code Extension (recommended)
99
+
100
+ Install the extension, configure your LLM, and start chatting:
101
+
102
+ ```
103
+ 1. Open VS Code
104
+ 2. Install "GitPilot Workspace" from Extensions
105
+ 3. Click the GitPilot icon in the sidebar
106
+ 4. Choose your AI provider (OpenAI, Claude, Ollama...)
107
+ 5. Start asking questions about your code
108
+ ```
109
+
110
+ ### Option 2: Web App
111
+ ![assets/2026-04-07-14-22-32.png](assets/2026-04-07-14-22-32.png)
112
+ Run the full web interface with Docker:
113
+
114
+ ```bash
115
+ git clone https://github.com/ruslanmv/gitpilot.git
116
+ cd gitpilot
117
+ docker compose up
118
+ ```
119
+
120
+ Open [http://localhost:3000](http://localhost:3000) in your browser.
121
+
122
+ ### Live Demo on Hugging Face
123
+
124
+ Experience the application in action through our hosted demo environment:
125
+
126
+ [![Live Demo Preview](assets/2026-04-07-16-17-56.png)](https://huggingface.co/spaces/ruslanmv/gitpilot)
127
+
128
+ 🔗 **Access the live demo:**
129
+ [https://huggingface.co/spaces/ruslanmv/gitpilot](https://huggingface.co/spaces/ruslanmv/gitpilot)
130
+
131
+ ### Option 3: Python CLI (fastest)
132
+
133
+ ```bash
134
+ pip install gitcopilot
135
+ gitpilot serve
136
+ ```
137
+
138
+ Open [http://localhost:8000](http://localhost:8000) and you're done.
139
+
140
+ If something else already holds :8000, GitPilot starts on the next free port and
141
+ tells you which — no `make stop` first. A port you ask for yourself
142
+ (`gitpilot serve --port 9000`, or `GITPILOT_PORT=9000`) is honoured strictly
143
+ instead, because a proxy or container map may depend on that exact number; add
144
+ `--no-strict-port` to let it drift anyway. See
145
+ [docs/PORTS.md](docs/PORTS.md).
146
+
147
+ > **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.
148
+
149
+ ---
150
+
151
+ ## VS Code Extension
152
+ ![assets/2026-04-07-14-15-33.png](assets/2026-04-07-14-15-33.png)
153
+ The sidebar panel gives you everything in one place:
154
+
155
+ | Feature | What it does |
156
+ |---|---|
157
+ | **Chat** | Ask questions, request changes, review code |
158
+ | **Execution Modes** | Bottom bar: `Auto` / `Ask` / `Plan` — controls agent permissions per session |
159
+ | **Plan View** | See the step-by-step plan before changes are made |
160
+ | **Plan Approval** | "Approve & Execute" / "Dismiss" bar — execution waits for your OK |
161
+ | **Tool Approvals** | Per-action Allow / Allow for session / Deny cards (Ask mode) |
162
+ | **Diff Preview** | Review proposed edits in VS Code's native diff viewer |
163
+ | **Apply / Revert** | One click to apply changes, one click to undo |
164
+ | **Quick Actions** | Explain, Review, Fix, Generate Tests, Security Scan |
165
+ | **Smart Commit** | AI-generated commit messages |
166
+ | **Code Lens** | Inline "Explain / Review" hints on functions |
167
+ | **Settings Tab** | Branded settings page (General, Provider, Agent, Editor) |
168
+ | **GitPilot Home** | Landing page in the editor — one composer, contextual to the file you have open |
169
+ | **New Task** | One click from the sidebar to Home, ready for the next thing |
170
+
171
+ ### Execution modes
172
+
173
+ The compose bar carries a mode picker that controls how the multi-agent pipeline runs:
174
+
175
+ ```
176
+ [+] [@] [/] Ask ⌄ [ ↑ ]
177
+ ```
178
+
179
+ | Mode | VS Code setting | Backend value | What happens |
180
+ |---|---|---|---|
181
+ | **Ask** (default) | `gitpilot.permissionMode: "normal"` | `"normal"` | Each dangerous tool (write, edit, run, commit) shows an approval card |
182
+ | **Agent** (shown as `Auto` in older builds) | `gitpilot.permissionMode: "auto"` | `"auto"` | Tools execute automatically — no approval prompts |
183
+ | **Plan** | `gitpilot.permissionMode: "plan"` | `"plan"` | Plan is generated and displayed, all writes/commands blocked |
184
+
185
+ Mode changes are persisted to VS Code settings and synced to the backend via `PUT /api/permissions/mode`.
186
+
187
+ ### How approvals work
188
+
189
+ ```
190
+ You send a request
191
+ → Explorer reads repo context
192
+ → Planner drafts step-by-step plan
193
+ → Plan appears in sidebar (Approve & Execute / Dismiss)
194
+ → You click Approve
195
+ → Coder begins execution
196
+ → Dangerous tool requested (e.g. write_file)
197
+ → Ask mode: approval card shown (Allow / Allow for session / Deny)
198
+ → Auto mode: executes immediately
199
+ → Plan mode: blocked
200
+ → Tests run
201
+ → Done — Apply Patch or Revert
202
+ ```
203
+
204
+ The default flow stops at Coder. To add a review step — or a PR step — pick a
205
+ topology that includes one (Settings → Agent → Agent topology, or
206
+ `GitPilot: Select Topology`). **Feature Builder** runs the full
207
+ Explorer → Planner → Coder → Reviewer → PR Manager sequence. See
208
+ [Agent architecture and topologies](docs/agents.md).
209
+
210
+ ```
211
+ ```
212
+
213
+ > **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.
214
+
215
+ ### Code generation and Apply Patch
216
+
217
+ 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.
218
+
219
+ ```
220
+ You: "Create a Flask app with app.py, requirements.txt, and README.md"
221
+
222
+ GitPilot:
223
+ → LLM generates 3 files with content
224
+ → Backend extracts structured edits (path + content)
225
+ → VS Code shows [Apply Patch] [Revert]
226
+ → You click Apply Patch
227
+ → 3 files written to disk
228
+ → Project context refreshes automatically
229
+ → First file opens in the editor
230
+ ```
231
+
232
+ How it works under the hood:
233
+ - The LLM is instructed to output code blocks with the filename on the fence line (` ```python hello.py`)
234
+ - The backend parses these blocks into `ProposedEdit` objects with file path, kind, and content
235
+ - All paths are sanitized (rejects `../` traversal, absolute paths, drive letters)
236
+ - The extension stores edits in `activeTask.edits` and shows Apply / Revert
237
+ - `PatchApplier` writes files via `vscode.workspace.fs.writeFile`
238
+ - After apply, project context refreshes and the first file opens
239
+
240
+ > **Note:** For folder-only sessions (no GitHub remote), code generation uses the LLM directly with structured output instructions. For GitHub-connected sessions, the CrewAI pipeline (Explorer → Planner → Coder) handles planning and execution. Review and PR stages are added by selecting a topology that includes them — see [Agent architecture and topologies](docs/agents.md).
241
+
242
+ ### Supported AI Providers
243
+
244
+ Configure any of these from **GitPilot: Settings → AI Providers** inside VS Code —
245
+ no browser, no config files. See the [provider setup guide](docs/vscode/ai-providers.md).
246
+
247
+ | Provider | Setup | Free? |
248
+ |---|---|---|
249
+ | **OllaBridge** | Works out of the box; sign in for more models | Yes |
250
+ | **Ollama** | Install Ollama, run `ollama pull llama3` | Yes |
251
+ | **Open WebUI** | Point GitPilot at your instance URL | Yes (self-hosted) |
252
+ | **OpenAI** | Add your API key | Paid |
253
+ | **Claude** | Add your Anthropic API key | Paid |
254
+ | **Watsonx** | Add IBM API key and project ID | Paid |
255
+ | **Custom endpoint** | Any OpenAI-compatible gateway — URL, key, headers | Depends |
256
+
257
+ ---
258
+
259
+ ## Web App
260
+
261
+ The web interface includes:
262
+
263
+ - Chat with real-time responses
264
+ - GitHub integration (connect your repos)
265
+ - File tree browser
266
+ - Diff viewer with line-by-line changes
267
+ - Pull request creation
268
+ - Session history with checkpoints
269
+ - Multi-repo support
270
+
271
+
272
+
273
+ ### Example: File Deletion
274
+ ![](assets/2025-11-16-00-25-49.png)
275
+
276
+ ### Example: Content Generation
277
+ ![](assets/2025-11-16-00-29-47.png)
278
+
279
+ ### Example: File Creation
280
+ ![](assets/2025-11-16-01-01-40.png)
281
+
282
+ ### Example multiple operations
283
+ ![](assets/2025-11-27-00-25-53.png)
284
+
285
+ ### Example of multiagent topologies
286
+ ![](assets/2026-04-07-16-11-47.png)
287
+
288
+ ---
289
+
290
+ ## How It Works
291
+
292
+ <p align="center">
293
+ <picture>
294
+ <source srcset="docs/assets/architecture.svg" type="image/svg+xml" />
295
+ <img src="docs/assets/architecture.png" alt="GitPilot architecture: Web, VS Code and CLI share one FastAPI backend that orchestrates a CrewAI multi-agent pipeline (Explorer, Planner, Executor, Reviewer) over any LLM provider." width="100%" />
296
+ </picture>
297
+ </p>
298
+
299
+ GitPilot uses a multi-agent system powered by CrewAI. A **request router**
300
+ classifies each request and dispatches it to the specialists that fit; the
301
+ default plan-and-execute flow is:
302
+
303
+ 1. **Explorer** reads your repo structure, git log, and key files
304
+ 2. **Planner** creates a safe step-by-step plan with diffs
305
+ 3. **Coder** writes code and runs tests, self-correcting on failure
306
+
307
+ Other requests skip that chain entirely — a code-review request goes straight
308
+ to the **Reviewer**, an issue request to the **Issue Manager**. Selecting a
309
+ **topology** replaces the routing with a fixed sequence, which is how you add
310
+ a review or PR stage to every task. Ten agents and nine topologies are
311
+ documented in [Agent architecture and topologies](docs/agents.md).
312
+
313
+ 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.
314
+
315
+ ---
316
+
317
+ ## Project Structure
318
+
319
+ ```
320
+ gitpilot/
321
+ gitpilot/ Python backend (FastAPI)
322
+ frontend/ React web app
323
+ extensions/vscode/ VS Code extension
324
+ docs/ Documentation and assets
325
+ tests/ Test suite
326
+ ```
327
+
328
+ ---
329
+
330
+ ## Configuration
331
+
332
+ GitPilot works with environment variables or the settings UI.
333
+
334
+ **Minimal setup** (Ollama, free, local):
335
+
336
+ ```bash
337
+ # .env
338
+ GITPILOT_PROVIDER=ollama
339
+ OLLAMA_BASE_URL=http://localhost:11434
340
+ GITPILOT_OLLAMA_MODEL=llama3
341
+ ```
342
+
343
+ **Cloud setup** (OpenAI):
344
+
345
+ ```bash
346
+ # .env
347
+ GITPILOT_PROVIDER=openai
348
+ OPENAI_API_KEY=sk-...
349
+ GITPILOT_OPENAI_MODEL=gpt-4o-mini
350
+ ```
351
+
352
+ **Cloud setup** (Claude):
353
+
354
+ ```bash
355
+ # .env
356
+ GITPILOT_PROVIDER=claude
357
+ ANTHROPIC_API_KEY=sk-ant-...
358
+ GITPILOT_CLAUDE_MODEL=claude-sonnet-4-5
359
+ ```
360
+
361
+ All settings can also be changed from the VS Code extension or web UI without editing files.
362
+
363
+ ---
364
+
365
+ ## API
366
+
367
+ GitPilot exposes a REST + WebSocket API:
368
+
369
+ | Endpoint | What it does |
370
+ |---|---|
371
+ | `GET /api/status` | Server health check |
372
+ | `POST /api/chat/send` | Send a message, get a response |
373
+ | `POST /api/v2/chat/stream` | Stream agent events (SSE) — accepts `permission_mode` |
374
+ | `WS /ws/v2/sessions/{id}` | Real-time WebSocket streaming |
375
+ | `POST /api/chat/plan` | Generate an execution plan |
376
+ | `POST /api/chat/execute` | Execute a plan |
377
+ | `GET /api/repos` | List connected repositories |
378
+ | `GET /api/sessions` | List chat sessions |
379
+ | `GET /api/permissions` | Current permission policy |
380
+ | `PUT /api/permissions/mode` | Set execution mode: `normal` / `auto` / `plan` |
381
+ | `POST /api/v2/approval/respond` | Approve or deny a tool execution request |
382
+
383
+ Full API docs at `http://localhost:8000/docs` (Swagger UI).
384
+
385
+ ---
386
+
387
+ ## Deployment
388
+
389
+ ### Hugging Face Spaces
390
+
391
+ GitPilot runs on Hugging Face Spaces with OllaBridge (free):
392
+
393
+ ```
394
+ Runtime: Docker
395
+ Port: 7860
396
+ Provider: OllaBridge (cloud Ollama)
397
+ ```
398
+
399
+ ### Docker Compose
400
+
401
+ ```bash
402
+ docker compose up -d
403
+ # Backend: http://localhost:8000
404
+ # Frontend: http://localhost:3000
405
+ ```
406
+
407
+ ### Vercel
408
+
409
+ The frontend deploys to Vercel. Set `VITE_BACKEND_URL` to your backend.
410
+
411
+ ---
412
+
413
+ ## Contributing
414
+
415
+ ```bash
416
+ # Standard install: runtime backend + frontend + MCP stack
417
+ make install
418
+ # WSL note: the Makefile defaults uv to UV_LINK_MODE=copy to avoid
419
+ # hardlink fallback warnings on /mnt/c checkouts. For best install speed,
420
+ # clone the repo inside the native WSL filesystem (for example ~/workspace).
421
+
422
+ # Developer/test tooling
423
+ make install-dev
424
+ make test
425
+
426
+ # Frontend only
427
+ cd frontend
428
+ npm ci
429
+ npm run dev
430
+
431
+ # VS Code Extension
432
+ cd extensions/vscode
433
+ npm install
434
+ make compile
435
+ # Press F5 in VS Code to launch debug host
436
+ ```
437
+
438
+ ---
439
+
440
+ ## License
441
+
442
+ Apache License 2.0. See [LICENSE](LICENSE).
443
+
444
+ ---
445
+
446
+ <div align="center">
447
+
448
+ **GitPilot** is made by [Ruslan Magana Vsevolodovna](https://github.com/ruslanmv)
449
+
450
+ [Star on GitHub](https://github.com/ruslanmv/gitpilot) &#8226; [Report a Bug](https://github.com/ruslanmv/gitpilot/issues) &#8226; [Request a Feature](https://github.com/ruslanmv/gitpilot/issues)
451
+
452
+ </div>
453
+
454
+ ---
455
+ **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).
456
+
457
+ ---
458
+
459
+ ## What's New
460
+
461
+ > **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.
462
+
463
+ > **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.
frontend/.dockerignore ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Node
2
+ node_modules/
3
+ npm-debug.log*
4
+ yarn-debug.log*
5
+ yarn-error.log*
6
+ .pnpm-debug.log*
7
+
8
+ # Build
9
+ dist/
10
+ build/
11
+
12
+ # Environment
13
+ .env
14
+ .env.local
15
+ .env.development
16
+ .env.test
17
+ .env.production.local
18
+
19
+ # IDE
20
+ .vscode/
21
+ .idea/
22
+ *.swp
23
+ *.swo
24
+ *~
25
+
26
+ # OS
27
+ .DS_Store
28
+ Thumbs.db
29
+
30
+ # Git
31
+ .git
32
+ .gitignore
33
+
34
+ # Testing
35
+ coverage/
36
+ .nyc_output/
37
+
38
+ # Misc
39
+ *.log
frontend/App.jsx ADDED
@@ -0,0 +1,1392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import StartupScreen from "./components/StartupScreen.jsx";
3
+ import LoginPage from "./components/LoginPage.jsx";
4
+ import LandingPage from "./components/LandingPage.jsx";
5
+ import AuthPage from "./components/AuthPage.jsx";
6
+ import RepoSelector from "./components/RepoSelector.jsx";
7
+ import ProjectContextPanel from "./components/ProjectContextPanel.jsx";
8
+ import ChatPanel from "./components/ChatPanel.jsx";
9
+ import LlmSettings from "./components/LlmSettings.jsx";
10
+ import FlowViewer from "./components/FlowViewer.jsx";
11
+ import Footer from "./components/Footer.jsx";
12
+ import ProjectSettingsModal from "./components/ProjectSettingsModal.jsx";
13
+ import SessionSidebar from "./components/SessionSidebar.jsx";
14
+ import ContextBar from "./components/ContextBar.jsx";
15
+ import AddRepoModal from "./components/AddRepoModal.jsx";
16
+ import UserMenu from "./components/UserMenu.jsx";
17
+ import AboutModal from "./components/AboutModal.jsx";
18
+ import {
19
+ WorkspaceModesTab,
20
+ SecurityTab,
21
+ IntegrationsTab,
22
+ MCPServersTab,
23
+ SkillsTab,
24
+ SessionsTab,
25
+ AdvancedTab,
26
+ SandboxTab,
27
+ AccountTab,
28
+ } from "./components/AdminTabs";
29
+ import { apiUrl, safeFetchJSON, fetchStatus, getAuthHeaders, clearSessionToken, startSession } from "./utils/api.js";
30
+ import { initApp } from "./utils/appInit.js";
31
+
32
+ function makeRepoKey(repo) {
33
+ if (!repo) return null;
34
+ return repo.full_name || `${repo.owner}/${repo.name}`;
35
+ }
36
+
37
+ function uniq(arr) {
38
+ return Array.from(new Set((arr || []).filter(Boolean)));
39
+ }
40
+
41
+ function getProviderLabel(status) {
42
+ if (!status) return "Checking...";
43
+ return (
44
+ status?.provider?.name ||
45
+ status?.provider_name ||
46
+ status?.provider?.provider ||
47
+ "Checking..."
48
+ );
49
+ }
50
+
51
+ function getBackendVersion(status) {
52
+ if (!status) return "Checking...";
53
+ return status?.version || status?.app_version || "Checking...";
54
+ }
55
+
56
+ export default function App() {
57
+ const frontendVersion = __APP_VERSION__ || "unknown";
58
+
59
+ // ---- Multi-repo context state ----
60
+ const [contextRepos, setContextRepos] = useState([]);
61
+ // Each entry: { repoKey: "owner/repo", repo: {...}, branch: "main" }
62
+ const [activeRepoKey, setActiveRepoKey] = useState(null);
63
+ const [addRepoOpen, setAddRepoOpen] = useState(false);
64
+
65
+ const [activePage, setActivePage] = useState("workspace");
66
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
67
+ const [isLoading, setIsLoading] = useState(true);
68
+ const [userInfo, setUserInfo] = useState(null);
69
+
70
+ // Startup / enterprise loader state
71
+ const [startupPhase, setStartupPhase] = useState("booting");
72
+ const [startupStatusMessage, setStartupStatusMessage] = useState("Starting application...");
73
+ const [startupDetailMessage, setStartupDetailMessage] = useState(
74
+ "Initializing authentication, provider, and workspace context."
75
+ );
76
+ const [startupStatusSnapshot, setStartupStatusSnapshot] = useState(null);
77
+
78
+ // Repo + Session State Machine
79
+ const [repoStateByKey, setRepoStateByKey] = useState({});
80
+ const [toast, setToast] = useState(null);
81
+ const [settingsOpen, setSettingsOpen] = useState(false);
82
+ const [aboutOpen, setAboutOpen] = useState(false);
83
+ const [adminTab, setAdminTab] = useState("overview");
84
+ const [adminStatus, setAdminStatus] = useState(null);
85
+
86
+ // Fetch admin status when overview tab is active
87
+ useEffect(() => {
88
+ if (activePage === "admin" && adminTab === "overview") {
89
+ fetchStatus()
90
+ .then((data) => setAdminStatus(data))
91
+ .catch(() => setAdminStatus(null));
92
+ }
93
+ }, [activePage, adminTab]);
94
+
95
+ // Claude-Code-on-Web: Session sidebar + Environment state
96
+ const [activeSessionId, setActiveSessionId] = useState(null);
97
+ const [activeEnvId, setActiveEnvId] = useState("default");
98
+ const [sessionRefreshNonce, setSessionRefreshNonce] = useState(0);
99
+
100
+ // Sidebar collapse state (persisted in localStorage)
101
+ const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
102
+ try {
103
+ return localStorage.getItem("gitpilot_sidebar_collapsed") === "true";
104
+ } catch {
105
+ return false;
106
+ }
107
+ });
108
+
109
+ const toggleSidebar = useCallback(() => {
110
+ setSidebarCollapsed((prev) => {
111
+ const next = !prev;
112
+ try {
113
+ localStorage.setItem("gitpilot_sidebar_collapsed", String(next));
114
+ } catch {}
115
+ return next;
116
+ });
117
+ }, []);
118
+
119
+ // Keyboard shortcut: Cmd/Ctrl + B to toggle sidebar
120
+ useEffect(() => {
121
+ const handler = (e) => {
122
+ if ((e.metaKey || e.ctrlKey) && e.key === "b") {
123
+ e.preventDefault();
124
+ toggleSidebar();
125
+ }
126
+ };
127
+ window.addEventListener("keydown", handler);
128
+ return () => window.removeEventListener("keydown", handler);
129
+ }, [toggleSidebar]);
130
+
131
+ // ---- Derived `repo` — keeps all downstream consumers unchanged ----
132
+ const repo = useMemo(() => {
133
+ const entry = contextRepos.find((r) => r.repoKey === activeRepoKey);
134
+ return entry?.repo || null;
135
+ }, [contextRepos, activeRepoKey]);
136
+
137
+ const repoKey = activeRepoKey;
138
+
139
+ // Convenient selectors
140
+ const currentRepoState = repoKey ? repoStateByKey[repoKey] : null;
141
+
142
+ const defaultBranch = currentRepoState?.defaultBranch || repo?.default_branch || "main";
143
+ const currentBranch = currentRepoState?.currentBranch || defaultBranch;
144
+ const sessionBranches = currentRepoState?.sessionBranches || [];
145
+ const lastExecution = currentRepoState?.lastExecution || null;
146
+ const pulseNonce = currentRepoState?.pulseNonce || 0;
147
+ const chatByBranch = currentRepoState?.chatByBranch || {};
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // Multi-repo context management
151
+ // ---------------------------------------------------------------------------
152
+ const addRepoToContext = useCallback((r) => {
153
+ const key = makeRepoKey(r);
154
+ if (!key) return;
155
+
156
+ setContextRepos((prev) => {
157
+ if (prev.some((e) => e.repoKey === key)) {
158
+ setActiveRepoKey(key);
159
+ return prev;
160
+ }
161
+ const entry = { repoKey: key, repo: r, branch: r.default_branch || "main" };
162
+ return [...prev, entry];
163
+ });
164
+
165
+ setActiveRepoKey(key);
166
+ setAddRepoOpen(false);
167
+ }, []);
168
+
169
+ const removeRepoFromContext = useCallback((key) => {
170
+ setContextRepos((prev) => {
171
+ const next = prev.filter((e) => e.repoKey !== key);
172
+ setActiveRepoKey((curActive) => {
173
+ if (curActive === key) {
174
+ return next.length > 0 ? next[0].repoKey : null;
175
+ }
176
+ return curActive;
177
+ });
178
+ return next;
179
+ });
180
+ }, []);
181
+
182
+ const clearAllContext = useCallback(() => {
183
+ setContextRepos([]);
184
+ setActiveRepoKey(null);
185
+ }, []);
186
+
187
+ const handleContextBranchChange = useCallback((targetRepoKey, newBranch) => {
188
+ setContextRepos((prev) =>
189
+ prev.map((e) =>
190
+ e.repoKey === targetRepoKey ? { ...e, branch: newBranch } : e
191
+ )
192
+ );
193
+
194
+ setRepoStateByKey((prev) => {
195
+ const cur = prev[targetRepoKey];
196
+ if (!cur) return prev;
197
+ return {
198
+ ...prev,
199
+ [targetRepoKey]: { ...cur, currentBranch: newBranch },
200
+ };
201
+ });
202
+ }, []);
203
+
204
+ // Init / reconcile repo state when active repo changes
205
+ useEffect(() => {
206
+ if (!repoKey || !repo) return;
207
+
208
+ setRepoStateByKey((prev) => {
209
+ const existing = prev[repoKey];
210
+ const d = repo.default_branch || "main";
211
+
212
+ if (!existing) {
213
+ return {
214
+ ...prev,
215
+ [repoKey]: {
216
+ defaultBranch: d,
217
+ currentBranch: d,
218
+ sessionBranches: [],
219
+ lastExecution: null,
220
+ pulseNonce: 0,
221
+ chatByBranch: {
222
+ [d]: { messages: [], plan: null },
223
+ },
224
+ },
225
+ };
226
+ }
227
+
228
+ const next = { ...existing };
229
+ next.defaultBranch = d;
230
+
231
+ if (!next.chatByBranch?.[d]) {
232
+ next.chatByBranch = {
233
+ ...(next.chatByBranch || {}),
234
+ [d]: { messages: [], plan: null },
235
+ };
236
+ }
237
+
238
+ if (!next.currentBranch) next.currentBranch = d;
239
+
240
+ return { ...prev, [repoKey]: next };
241
+ });
242
+ }, [repoKey, repo?.id, repo?.default_branch]);
243
+
244
+ const showToast = (title, message) => {
245
+ setToast({ title, message });
246
+ window.setTimeout(() => setToast(null), 5000);
247
+ };
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Session management — every chat is backed by a Session (Claude Code parity)
251
+ // ---------------------------------------------------------------------------
252
+
253
+ const _creatingSessionRef = useRef(false);
254
+
255
+ const [chatBySession, setChatBySession] = useState({});
256
+
257
+ const ensureSession = useCallback(
258
+ async (sessionName, seedMessages) => {
259
+ if (activeSessionId) return activeSessionId;
260
+ if (!repo) return null;
261
+ if (_creatingSessionRef.current) return null;
262
+ _creatingSessionRef.current = true;
263
+
264
+ try {
265
+ const token = localStorage.getItem("github_token");
266
+ const headers = {
267
+ "Content-Type": "application/json",
268
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
269
+ };
270
+
271
+ const res = await fetch(apiUrl("/api/sessions"), {
272
+ method: "POST",
273
+ headers,
274
+ body: JSON.stringify({
275
+ repo_full_name: repoKey,
276
+ branch: currentBranch,
277
+ name: sessionName || undefined,
278
+ repos: contextRepos.map((e) => ({
279
+ full_name: e.repoKey,
280
+ branch: e.branch,
281
+ mode: e.repoKey === activeRepoKey ? "write" : "read",
282
+ })),
283
+ active_repo: activeRepoKey,
284
+ }),
285
+ });
286
+
287
+ if (!res.ok) return null;
288
+ const data = await res.json();
289
+ const newId = data.session_id;
290
+
291
+ if (seedMessages && seedMessages.length > 0) {
292
+ setChatBySession((prev) => ({
293
+ ...prev,
294
+ [newId]: { messages: seedMessages, plan: null },
295
+ }));
296
+ }
297
+
298
+ setActiveSessionId(newId);
299
+ setSessionRefreshNonce((n) => n + 1);
300
+ return newId;
301
+ } catch (err) {
302
+ console.warn("Failed to create session:", err);
303
+ return null;
304
+ } finally {
305
+ _creatingSessionRef.current = false;
306
+ }
307
+ },
308
+ [activeSessionId, repo, repoKey, currentBranch, contextRepos, activeRepoKey]
309
+ );
310
+
311
+ const handleNewSession = async () => {
312
+ setActiveSessionId(null);
313
+
314
+ try {
315
+ const token = localStorage.getItem("github_token");
316
+ const headers = {
317
+ "Content-Type": "application/json",
318
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
319
+ };
320
+
321
+ const res = await fetch(apiUrl("/api/sessions"), {
322
+ method: "POST",
323
+ headers,
324
+ body: JSON.stringify({
325
+ repo_full_name: repoKey,
326
+ branch: currentBranch,
327
+ repos: contextRepos.map((e) => ({
328
+ full_name: e.repoKey,
329
+ branch: e.branch,
330
+ mode: e.repoKey === activeRepoKey ? "write" : "read",
331
+ })),
332
+ active_repo: activeRepoKey,
333
+ }),
334
+ });
335
+
336
+ if (!res.ok) return;
337
+ const data = await res.json();
338
+ setActiveSessionId(data.session_id);
339
+ setSessionRefreshNonce((n) => n + 1);
340
+ showToast("Session Created", "New session started.");
341
+ } catch (err) {
342
+ console.warn("Failed to create session:", err);
343
+ }
344
+ };
345
+
346
+ /**
347
+ * Convert a backend Message object to the frontend chat UI shape.
348
+ * Backend: { role: "user|assistant|system", content: "...", timestamp, metadata }
349
+ * Frontend: { from: "user|ai", role: "user|assistant|system", content, answer, ... }
350
+ */
351
+ const normalizeBackendMessage = (m) => {
352
+ const role = m.role || "assistant";
353
+ const content = m.content || "";
354
+ if (role === "user") {
355
+ return { from: "user", role: "user", content, text: content };
356
+ }
357
+ if (role === "system") {
358
+ return { from: "ai", role: "system", content };
359
+ }
360
+ // assistant
361
+ return {
362
+ from: "ai",
363
+ role: "assistant",
364
+ content,
365
+ answer: content,
366
+ // Preserve any structured metadata the backend stored (plan, diff, etc.)
367
+ ...(m.metadata && typeof m.metadata === "object" ? m.metadata : {}),
368
+ };
369
+ };
370
+
371
+ /**
372
+ * Fetch persisted messages for a session from the backend.
373
+ * Returns an array of normalized frontend messages (ready for ChatPanel),
374
+ * or an empty array on failure.
375
+ */
376
+ const fetchSessionMessages = useCallback(async (sessionId) => {
377
+ if (!sessionId) return [];
378
+ try {
379
+ const token = localStorage.getItem("github_token");
380
+ const headers = { "Content-Type": "application/json" };
381
+ if (token) headers["Authorization"] = `Bearer ${token}`;
382
+
383
+ const res = await fetch(apiUrl(`/api/sessions/${sessionId}/messages`), {
384
+ headers,
385
+ });
386
+ if (!res.ok) {
387
+ console.warn(`[fetchSessionMessages] ${res.status} for ${sessionId}`);
388
+ return [];
389
+ }
390
+ const data = await res.json();
391
+ const backendMessages = Array.isArray(data.messages) ? data.messages : [];
392
+ return backendMessages.map(normalizeBackendMessage);
393
+ } catch (err) {
394
+ console.warn(`[fetchSessionMessages] Failed to fetch ${sessionId}:`, err);
395
+ return [];
396
+ }
397
+ }, []);
398
+
399
+ /**
400
+ * Handle click on a session in the sidebar.
401
+ *
402
+ * Critical ordering: we must hydrate chatBySession BEFORE setting
403
+ * activeSessionId, because ChatPanel's session-sync useEffect reads
404
+ * sessionChatState only when sessionId changes (it does NOT depend on
405
+ * chatBySession to avoid prop/state loops). If we set activeSessionId
406
+ * first, ChatPanel would see an empty messages array, then our async
407
+ * hydration would complete but ChatPanel wouldn't re-sync.
408
+ */
409
+ // Resolve the branch we should jump to when reopening a session.
410
+ // Preference order:
411
+ // 1. session.repos[i].branch for the active_repo (multi-repo)
412
+ // 2. session.branch (legacy single-repo field)
413
+ // Returns ``null`` when nothing is recorded.
414
+ const resolveSessionBranch = (session) => {
415
+ if (!session) return null;
416
+ if (Array.isArray(session.repos) && session.repos.length > 0) {
417
+ const target =
418
+ session.repos.find(
419
+ (r) => session.active_repo && r?.full_name === session.active_repo,
420
+ ) || session.repos[0];
421
+ if (target?.branch) return target.branch;
422
+ }
423
+ return session.branch || null;
424
+ };
425
+
426
+ // Probe whether a branch still exists on GitHub. We deliberately
427
+ // reuse the existing tree endpoint instead of adding a new one — a
428
+ // 200 means the ref resolves, anything else (most importantly 404)
429
+ // means the branch is gone or otherwise unreachable. Failure
430
+ // degrades to "branch unknown" so a transient network blip falls
431
+ // back gracefully rather than misleading the user.
432
+ const probeBranchExists = async (repoFullName, branch) => {
433
+ if (!repoFullName || !branch) return false;
434
+ try {
435
+ const token = localStorage.getItem("github_token");
436
+ const headers = {};
437
+ if (token) headers["Authorization"] = `Bearer ${token}`;
438
+ const res = await fetch(
439
+ apiUrl(
440
+ `/api/repos/${repoFullName}/tree?ref=${encodeURIComponent(branch)}`,
441
+ ),
442
+ { headers },
443
+ );
444
+ return res.ok;
445
+ } catch {
446
+ return false;
447
+ }
448
+ };
449
+
450
+ const handleSelectSession = useCallback(async (session) => {
451
+ // 1. Fetch persisted messages first
452
+ const messages = await fetchSessionMessages(session.id);
453
+
454
+ // 2. Seed the chat cache (ChatPanel will read this via sessionChatState)
455
+ setChatBySession((prev) => ({
456
+ ...prev,
457
+ [session.id]: {
458
+ ...(prev[session.id] || { plan: null }),
459
+ messages,
460
+ },
461
+ }));
462
+
463
+ // 3. NOW activate the session — ChatPanel's sync effect will read
464
+ // the hydrated messages from chatBySession[session.id]
465
+ setActiveSessionId(session.id);
466
+
467
+ // 4. Jump to the branch this session last published to, but verify
468
+ // it still exists on GitHub first. When the branch was deleted
469
+ // (rebased away, merged-and-pruned, …) fall back to the
470
+ // repository's default branch and tell the user what happened —
471
+ // silently landing on the default would mask data loss.
472
+ const target = resolveSessionBranch(session);
473
+ if (target && target !== currentBranch) {
474
+ const repoFullName =
475
+ session.repo ||
476
+ (Array.isArray(session.repos) && session.repos[0]?.full_name);
477
+ const exists = await probeBranchExists(repoFullName, target);
478
+ if (exists) {
479
+ handleBranchChange(target);
480
+ } else {
481
+ const fallback = defaultBranch || "main";
482
+ showToast(
483
+ "Branch not found",
484
+ `'${target}' was not found on GitHub. Switched to ${fallback}.`,
485
+ );
486
+ if (fallback !== currentBranch) handleBranchChange(fallback);
487
+ }
488
+ }
489
+ // eslint-disable-next-line react-hooks/exhaustive-deps
490
+ }, [fetchSessionMessages, currentBranch, defaultBranch]);
491
+
492
+ const handleDeleteSession = useCallback(
493
+ (deletedId) => {
494
+ if (deletedId === activeSessionId) {
495
+ setActiveSessionId(null);
496
+
497
+ setChatBySession((prev) => {
498
+ const next = { ...prev };
499
+ delete next[deletedId];
500
+ return next;
501
+ });
502
+
503
+ if (repoKey) {
504
+ setRepoStateByKey((prev) => {
505
+ const cur = prev[repoKey];
506
+ if (!cur) return prev;
507
+ const branchKey = cur.currentBranch || cur.defaultBranch || defaultBranch;
508
+ return {
509
+ ...prev,
510
+ [repoKey]: {
511
+ ...cur,
512
+ chatByBranch: {
513
+ ...(cur.chatByBranch || {}),
514
+ [branchKey]: { messages: [], plan: null },
515
+ },
516
+ },
517
+ };
518
+ });
519
+ }
520
+ }
521
+ },
522
+ [activeSessionId, repoKey, defaultBranch]
523
+ );
524
+
525
+ // ---------------------------------------------------------------------------
526
+ // Chat persistence helpers
527
+ // ---------------------------------------------------------------------------
528
+ const updateChatForCurrentBranch = (patch) => {
529
+ if (!repoKey) return;
530
+
531
+ setRepoStateByKey((prev) => {
532
+ const cur = prev[repoKey];
533
+ if (!cur) return prev;
534
+
535
+ const branchKey = cur.currentBranch || cur.defaultBranch || defaultBranch;
536
+
537
+ const existing = cur.chatByBranch?.[branchKey] || {
538
+ messages: [],
539
+ plan: null,
540
+ };
541
+
542
+ return {
543
+ ...prev,
544
+ [repoKey]: {
545
+ ...cur,
546
+ chatByBranch: {
547
+ ...(cur.chatByBranch || {}),
548
+ [branchKey]: { ...existing, ...patch },
549
+ },
550
+ },
551
+ };
552
+ });
553
+ };
554
+
555
+ const currentChatState = useMemo(() => {
556
+ const b = currentBranch || defaultBranch;
557
+ return chatByBranch[b] || { messages: [], plan: null };
558
+ }, [chatByBranch, currentBranch, defaultBranch]);
559
+
560
+ const sessionChatState = useMemo(() => {
561
+ if (!activeSessionId) {
562
+ return currentChatState;
563
+ }
564
+ return chatBySession[activeSessionId] || { messages: [], plan: null };
565
+ }, [activeSessionId, chatBySession, currentChatState]);
566
+
567
+ const updateSessionChat = (patch) => {
568
+ if (activeSessionId) {
569
+ setChatBySession((prev) => ({
570
+ ...prev,
571
+ [activeSessionId]: {
572
+ ...(prev[activeSessionId] || { messages: [], plan: null }),
573
+ ...patch,
574
+ },
575
+ }));
576
+ } else {
577
+ updateChatForCurrentBranch(patch);
578
+ }
579
+ };
580
+
581
+ // ---------------------------------------------------------------------------
582
+ // Branch change (manual — for active repo)
583
+ // ---------------------------------------------------------------------------
584
+ const handleBranchChange = (nextBranch) => {
585
+ if (!repoKey) return;
586
+ if (!nextBranch || nextBranch === currentBranch) return;
587
+
588
+ setRepoStateByKey((prev) => {
589
+ const cur = prev[repoKey];
590
+ if (!cur) return prev;
591
+
592
+ const nextState = { ...cur, currentBranch: nextBranch };
593
+
594
+ if (nextBranch === cur.defaultBranch) {
595
+ nextState.chatByBranch = {
596
+ ...nextState.chatByBranch,
597
+ [nextBranch]: { messages: [], plan: null },
598
+ };
599
+ }
600
+
601
+ return { ...prev, [repoKey]: nextState };
602
+ });
603
+
604
+ setContextRepos((prev) =>
605
+ prev.map((e) =>
606
+ e.repoKey === repoKey ? { ...e, branch: nextBranch } : e
607
+ )
608
+ );
609
+
610
+ if (nextBranch === defaultBranch) {
611
+ showToast("New Session", `Switched to ${defaultBranch}. Chat cleared.`);
612
+ } else {
613
+ showToast("Context Switched", `Now viewing ${nextBranch}.`);
614
+ }
615
+ };
616
+
617
+ // ---------------------------------------------------------------------------
618
+ // Execution complete
619
+ // ---------------------------------------------------------------------------
620
+ const handleExecutionComplete = ({
621
+ branch,
622
+ mode,
623
+ commit_url,
624
+ completionMsg,
625
+ sourceBranch,
626
+ }) => {
627
+ if (!repoKey || !branch) return;
628
+
629
+ // Clear the session-keyed chat cache's ``plan`` AND append the
630
+ // completion message synchronously, before any branch change can
631
+ // trigger ChatPanel's session-sync effect. Two bugs need to be
632
+ // fixed in the same write:
633
+ //
634
+ // 1. Stale plan: without clearing, the sync effect re-reads the
635
+ // old approved plan and restores the Approve & execute / Reject
636
+ // plan buttons, enabling accidental double-execution.
637
+ //
638
+ // 2. Wiped completion: in hard-switch mode the sync effect runs
639
+ // BEFORE the persistence effect (declared earlier in
640
+ // ChatPanel), so it overwrites local ``messages`` with
641
+ // ``sessionChatState.messages`` — which doesn't yet contain
642
+ // completionMsg. The user's "Answer / Execution Log" block
643
+ // then vanishes from the session view.
644
+ //
645
+ // By appending normalizedCompletion here, sessionChatState already
646
+ // carries the completion when the sync effect reads it. No
647
+ // duplicate is introduced: local ``messages`` already has the same
648
+ // entry, so the subsequent persistence pass is a no-op write.
649
+ if (activeSessionId) {
650
+ const normalizedCompletion =
651
+ completionMsg &&
652
+ (completionMsg.answer || completionMsg.content || completionMsg.executionLog)
653
+ ? {
654
+ from: completionMsg.from || "ai",
655
+ role: completionMsg.role || "assistant",
656
+ answer: completionMsg.answer,
657
+ content: completionMsg.content,
658
+ executionLog: completionMsg.executionLog,
659
+ diff: completionMsg.diff,
660
+ }
661
+ : null;
662
+ setChatBySession((prev) => {
663
+ const existing = prev[activeSessionId];
664
+ if (!existing) return prev;
665
+ const noPlanChange = existing.plan == null;
666
+ if (noPlanChange && !normalizedCompletion) return prev;
667
+ return {
668
+ ...prev,
669
+ [activeSessionId]: {
670
+ ...existing,
671
+ messages: normalizedCompletion
672
+ ? [...(existing.messages || []), normalizedCompletion]
673
+ : existing.messages,
674
+ plan: null,
675
+ },
676
+ };
677
+ });
678
+ }
679
+
680
+ setRepoStateByKey((prev) => {
681
+ const cur =
682
+ prev[repoKey] || {
683
+ defaultBranch,
684
+ currentBranch: defaultBranch,
685
+ sessionBranches: [],
686
+ lastExecution: null,
687
+ pulseNonce: 0,
688
+ chatByBranch: { [defaultBranch]: { messages: [], plan: null } },
689
+ };
690
+
691
+ const next = { ...cur };
692
+ next.lastExecution = { mode, branch, ts: Date.now() };
693
+
694
+ if (!next.chatByBranch) next.chatByBranch = {};
695
+
696
+ const prevBranchKey =
697
+ sourceBranch || cur.currentBranch || cur.defaultBranch || defaultBranch;
698
+
699
+ const successSystemMsg = {
700
+ role: "system",
701
+ isSuccess: true,
702
+ link: commit_url,
703
+ content:
704
+ mode === "hard-switch"
705
+ ? `🌱 **Session Started:** Created branch \`${branch}\`.`
706
+ : `✅ **Update Published:** Commits pushed to \`${branch}\`.`,
707
+ };
708
+
709
+ const normalizedCompletion =
710
+ completionMsg &&
711
+ (completionMsg.answer || completionMsg.content || completionMsg.executionLog)
712
+ ? {
713
+ from: completionMsg.from || "ai",
714
+ role: completionMsg.role || "assistant",
715
+ answer: completionMsg.answer,
716
+ content: completionMsg.content,
717
+ executionLog: completionMsg.executionLog,
718
+ }
719
+ : null;
720
+
721
+ if (mode === "hard-switch") {
722
+ next.sessionBranches = uniq([...(next.sessionBranches || []), branch]);
723
+ next.currentBranch = branch;
724
+ next.pulseNonce = (next.pulseNonce || 0) + 1;
725
+
726
+ const existingTargetChat = next.chatByBranch[branch];
727
+ const isExistingSession =
728
+ existingTargetChat && (existingTargetChat.messages || []).length > 0;
729
+
730
+ if (isExistingSession) {
731
+ const appended = [
732
+ ...(existingTargetChat.messages || []),
733
+ ...(normalizedCompletion ? [normalizedCompletion] : []),
734
+ successSystemMsg,
735
+ ];
736
+
737
+ next.chatByBranch[branch] = {
738
+ ...existingTargetChat,
739
+ messages: appended,
740
+ plan: null,
741
+ };
742
+ } else {
743
+ const prevChat =
744
+ (cur.chatByBranch && cur.chatByBranch[prevBranchKey]) || {
745
+ messages: [],
746
+ plan: null,
747
+ };
748
+
749
+ next.chatByBranch[branch] = {
750
+ messages: [
751
+ ...(prevChat.messages || []),
752
+ ...(normalizedCompletion ? [normalizedCompletion] : []),
753
+ successSystemMsg,
754
+ ],
755
+ plan: null,
756
+ };
757
+ }
758
+
759
+ if (!next.chatByBranch[next.defaultBranch]) {
760
+ next.chatByBranch[next.defaultBranch] = { messages: [], plan: null };
761
+ }
762
+ } else if (mode === "sticky") {
763
+ next.currentBranch = cur.currentBranch || branch;
764
+
765
+ const targetChat = next.chatByBranch[branch] || { messages: [], plan: null };
766
+
767
+ next.chatByBranch[branch] = {
768
+ messages: [
769
+ ...(targetChat.messages || []),
770
+ ...(normalizedCompletion ? [normalizedCompletion] : []),
771
+ successSystemMsg,
772
+ ],
773
+ plan: null,
774
+ };
775
+ }
776
+
777
+ return { ...prev, [repoKey]: next };
778
+ });
779
+
780
+ if (mode === "hard-switch") {
781
+ showToast("Context Switched", `Active on ${branch}.`);
782
+ } else {
783
+ showToast("Changes Committed", `Updated ${branch}.`);
784
+ }
785
+ };
786
+
787
+ // ---------------------------------------------------------------------------
788
+ // Auth & startup render
789
+ // ---------------------------------------------------------------------------
790
+ useEffect(() => {
791
+ checkAuthentication();
792
+ }, []);
793
+
794
+ const checkAuthentication = async () => {
795
+ setStartupPhase("booting");
796
+ setStartupStatusMessage("Starting application...");
797
+ setStartupDetailMessage(
798
+ "Initializing authentication, provider, and workspace context."
799
+ );
800
+
801
+ try {
802
+ setStartupPhase("checking-backend");
803
+ setStartupStatusMessage("Connecting to backend...");
804
+ setStartupDetailMessage(
805
+ "Preparing your workspace. First launch may take a few seconds."
806
+ );
807
+
808
+ // Single-source-of-truth init: combines /api/status + /api/auth/status
809
+ // in one request. Runs exactly once per page load (StrictMode-safe).
810
+ const initResult = await initApp();
811
+ const status = initResult.status;
812
+ if (status) {
813
+ setStartupStatusSnapshot(status);
814
+ setAdminStatus(status);
815
+ }
816
+
817
+ const token = localStorage.getItem("github_token");
818
+ const user = localStorage.getItem("github_user");
819
+
820
+ if (token && user) {
821
+ setStartupPhase("validating-auth");
822
+ setStartupStatusMessage("Validating authentication...");
823
+ setStartupDetailMessage(
824
+ "Restoring your GitHub session and confirming access."
825
+ );
826
+
827
+ try {
828
+ const data = await safeFetchJSON(apiUrl("/api/auth/validate"), {
829
+ method: "POST",
830
+ headers: { "Content-Type": "application/json" },
831
+ body: JSON.stringify({ access_token: token }),
832
+ timeout: 20000, // 20s — first-load GitHub API validation can be slow
833
+ });
834
+
835
+ if (data.authenticated) {
836
+ setStartupPhase("restoring-session");
837
+ setStartupStatusMessage("Restoring workspace...");
838
+ setStartupDetailMessage(
839
+ "Loading user profile, reconnecting provider state, and preparing the workspace."
840
+ );
841
+
842
+ setIsAuthenticated(true);
843
+ setUserInfo(JSON.parse(user));
844
+ setIsLoading(false);
845
+ return;
846
+ }
847
+ } catch (err) {
848
+ console.error(err);
849
+ }
850
+
851
+ localStorage.removeItem("github_token");
852
+ localStorage.removeItem("github_user");
853
+ }
854
+
855
+ // No GitHub token — but a GitPilot account session (HttpOnly cookie) may
856
+ // exist. Recognise it so email users stay signed in across reloads.
857
+ try {
858
+ const me = await safeFetchJSON(apiUrl("/api/account/me"), {
859
+ method: "GET",
860
+ credentials: "include",
861
+ headers: getAuthHeaders(), // X-GitPilot-Session survives cross-origin
862
+ timeout: 8000,
863
+ });
864
+ if (me && me.id) {
865
+ setIsAuthenticated(true);
866
+ setUserInfo({ login: me.email, name: me.name || me.email, email: me.email });
867
+ setIsLoading(false);
868
+ return;
869
+ }
870
+ } catch (err) {
871
+ /* no account session — fall through to sign-in */
872
+ }
873
+
874
+ setStartupPhase("ready");
875
+ setStartupStatusMessage("Preparing sign-in...");
876
+ setStartupDetailMessage(
877
+ "GitPilot is ready. Please authenticate to continue."
878
+ );
879
+
880
+ setIsAuthenticated(false);
881
+ setIsLoading(false);
882
+ } catch (err) {
883
+ console.error(err);
884
+ setStartupPhase("fallback");
885
+ setStartupStatusMessage("Starting application...");
886
+ setStartupDetailMessage(
887
+ "Continuing with basic startup while backend status is still loading."
888
+ );
889
+ setIsAuthenticated(false);
890
+ setIsLoading(false);
891
+ }
892
+ };
893
+
894
+ const handleAuthenticated = (session) => {
895
+ setIsAuthenticated(true);
896
+ setUserInfo(session.user);
897
+ };
898
+
899
+ const handleLogout = () => {
900
+ // Best-effort backend logout (clears the session cookie); ignore failures.
901
+ try {
902
+ fetch(apiUrl("/api/account/logout"), {
903
+ method: "POST",
904
+ credentials: "include",
905
+ headers: getAuthHeaders(),
906
+ }).catch(() => {});
907
+ } catch { /* ignore */ }
908
+ localStorage.removeItem("github_token");
909
+ localStorage.removeItem("github_user");
910
+ clearSessionToken();
911
+ setIsAuthenticated(false);
912
+ setUserInfo(null);
913
+ clearAllContext();
914
+ };
915
+
916
+ // In-workspace "Connect GitHub": let an already-signed-in account user run
917
+ // the GitHub device flow to link their repos, then return to the workspace.
918
+ // This renders even when authenticated (unlike the sign-in screen below).
919
+ if (typeof window !== "undefined") {
920
+ const qs = new URLSearchParams(window.location.search);
921
+ if (window.location.pathname.startsWith("/auth") && qs.get("connect") === "github") {
922
+ return (
923
+ <AuthPage
924
+ onAuthenticated={handleAuthenticated}
925
+ backendReady={!!startupStatusSnapshot}
926
+ connectMode
927
+ />
928
+ );
929
+ }
930
+ }
931
+
932
+ // Public pages must render instantly — never gated behind backend startup.
933
+ // (A marketing landing page that shows "Connecting to backend…" is bad for
934
+ // users and for SEO crawlers.) Only a returning GitHub-token session, which
935
+ // startup is about to validate into the workspace, defers to the loader.
936
+ if (!isAuthenticated) {
937
+ const path = typeof window !== "undefined" ? window.location.pathname : "/";
938
+ const hasGithubToken =
939
+ typeof window !== "undefined" && !!localStorage.getItem("github_token");
940
+
941
+ // The auth/device-flow screen lives at "/auth"; it manages its own backend
942
+ // readiness via the backendReady prop, so render it immediately.
943
+ if (path.startsWith("/auth")) {
944
+ return (
945
+ <AuthPage
946
+ onAuthenticated={handleAuthenticated}
947
+ backendReady={!!startupStatusSnapshot}
948
+ />
949
+ );
950
+ }
951
+
952
+ // Public landing page at "/". Render instantly for anonymous visitors;
953
+ // only show the loader if a stored GitHub session is still resolving.
954
+ if (!hasGithubToken || !isLoading) {
955
+ return <LandingPage />;
956
+ }
957
+ }
958
+
959
+ if (isLoading) {
960
+ return (
961
+ <StartupScreen
962
+ appName="GitPilot"
963
+ subtitle="Enterprise Workspace Copilot"
964
+ frontendVersion={frontendVersion}
965
+ backendVersion={getBackendVersion(startupStatusSnapshot)}
966
+ provider={getProviderLabel(startupStatusSnapshot)}
967
+ statusMessage={startupStatusMessage}
968
+ detailMessage={startupDetailMessage}
969
+ phase={startupPhase}
970
+ />
971
+ );
972
+ }
973
+
974
+ const hasContext = contextRepos.length > 0;
975
+
976
+ return (
977
+ <div className="app-root">
978
+ <div className="main-wrapper">
979
+ <aside className={`sidebar${sidebarCollapsed ? " sidebar--collapsed" : ""}`}>
980
+ <div
981
+ className="sidebar-top-row"
982
+ >
983
+ <div
984
+ className="logo-row"
985
+ onClick={sidebarCollapsed ? toggleSidebar : undefined}
986
+ style={sidebarCollapsed ? { cursor: "pointer" } : undefined}
987
+ >
988
+ <div className="logo-square">GP</div>
989
+ {!sidebarCollapsed && (
990
+ <div>
991
+ <div className="logo-title">GitPilot</div>
992
+ <div className="logo-subtitle">Agentic GitHub Copilot</div>
993
+ </div>
994
+ )}
995
+ </div>
996
+
997
+ {!sidebarCollapsed && (
998
+ <button
999
+ className="sidebar-toggle-btn"
1000
+ onClick={toggleSidebar}
1001
+ title="Collapse sidebar (Ctrl+B)"
1002
+ >
1003
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
1004
+ <path
1005
+ d="M10 3L5 8L10 13"
1006
+ stroke="currentColor"
1007
+ strokeWidth="1.5"
1008
+ strokeLinecap="round"
1009
+ strokeLinejoin="round"
1010
+ />
1011
+ </svg>
1012
+ </button>
1013
+ )}
1014
+ </div>
1015
+
1016
+ <div className="main-nav">
1017
+ <button
1018
+ className={"nav-btn" + (activePage === "workspace" ? " nav-btn-active" : "")}
1019
+ onClick={() => setActivePage("workspace")}
1020
+ title="Workspace"
1021
+ >
1022
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
1023
+ <rect x="2" y="2" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.3" />
1024
+ <rect x="9" y="2" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.3" />
1025
+ <rect x="2" y="9" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.3" />
1026
+ <rect x="9" y="9" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.3" />
1027
+ </svg>
1028
+ {!sidebarCollapsed && <span>Workspace</span>}
1029
+ </button>
1030
+
1031
+ <button
1032
+ className={"nav-btn" + (activePage === "flow" ? " nav-btn-active" : "")}
1033
+ onClick={() => setActivePage("flow")}
1034
+ title="Agent Workflow"
1035
+ >
1036
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
1037
+ <circle cx="4" cy="4" r="2" stroke="currentColor" strokeWidth="1.3" />
1038
+ <circle cx="12" cy="4" r="2" stroke="currentColor" strokeWidth="1.3" />
1039
+ <circle cx="8" cy="12" r="2" stroke="currentColor" strokeWidth="1.3" />
1040
+ <path d="M5.5 5.5L7 10.5" stroke="currentColor" strokeWidth="1.3" />
1041
+ <path d="M10.5 5.5L9 10.5" stroke="currentColor" strokeWidth="1.3" />
1042
+ </svg>
1043
+ {!sidebarCollapsed && <span>Agent Workflow</span>}
1044
+ </button>
1045
+
1046
+ <button
1047
+ className={"nav-btn" + (activePage === "admin" ? " nav-btn-active" : "")}
1048
+ onClick={() => setActivePage("admin")}
1049
+ title="Admin"
1050
+ >
1051
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
1052
+ <path
1053
+ d="M8 2C8 2 9.5 4 9.5 6C9.5 6.8 9.2 7.5 8.7 8L10 14H6L7.3 8C6.8 7.5 6.5 6.8 6.5 6C6.5 4 8 2 8 2Z"
1054
+ stroke="currentColor"
1055
+ strokeWidth="1.3"
1056
+ strokeLinejoin="round"
1057
+ />
1058
+ <circle cx="8" cy="6" r="1.5" stroke="currentColor" strokeWidth="1.3" />
1059
+ </svg>
1060
+ {!sidebarCollapsed && <span>Admin</span>}
1061
+ </button>
1062
+ </div>
1063
+
1064
+ {!sidebarCollapsed && (
1065
+ <>
1066
+ {!hasContext && (
1067
+ <RepoSelector
1068
+ onSelect={(r) => addRepoToContext(r)}
1069
+ workspace={startupStatusSnapshot?.workspace}
1070
+ onOpenLocal={async (payload) => {
1071
+ const result = await startSession(payload);
1072
+ setActiveSessionId(result.session_id);
1073
+ setSessionRefreshNonce((n) => n + 1);
1074
+ setActivePage("workspace");
1075
+ showToast?.("Workspace ready", "Local project opened.");
1076
+ return result;
1077
+ }}
1078
+ />
1079
+ )}
1080
+
1081
+ {repo && (
1082
+ <SessionSidebar
1083
+ repo={repo}
1084
+ activeSessionId={activeSessionId}
1085
+ onSelectSession={handleSelectSession}
1086
+ onNewSession={handleNewSession}
1087
+ onDeleteSession={handleDeleteSession}
1088
+ refreshNonce={sessionRefreshNonce}
1089
+ />
1090
+ )}
1091
+ </>
1092
+ )}
1093
+
1094
+ {userInfo && (
1095
+ <div className="user-profile">
1096
+ <UserMenu
1097
+ userInfo={userInfo}
1098
+ sidebarCollapsed={sidebarCollapsed}
1099
+ onOpenAccount={() => {
1100
+ setActivePage("admin");
1101
+ setAdminTab("account");
1102
+ }}
1103
+ onOpenSettings={() => {
1104
+ setActivePage("admin");
1105
+ setAdminTab("advanced");
1106
+ }}
1107
+ onOpenAbout={() => setAboutOpen(true)}
1108
+ onLogout={handleLogout}
1109
+ />
1110
+ </div>
1111
+ )}
1112
+ </aside>
1113
+
1114
+ <main className="workspace">
1115
+ {activePage === "admin" && (
1116
+ <div
1117
+ style={{
1118
+ flex: 1,
1119
+ minHeight: 0,
1120
+ overflowY: "auto",
1121
+ padding: "24px",
1122
+ maxWidth: "960px",
1123
+ width: "100%",
1124
+ margin: "0 auto",
1125
+ boxSizing: "border-box",
1126
+ }}
1127
+ >
1128
+ <div style={{ display: "flex", gap: "8px", marginBottom: "24px", flexWrap: "wrap" }}>
1129
+ {["overview", "account", "providers", "workspace-modes", "integrations", "mcp-servers", "sandbox", "sessions", "skills", "security", "advanced"].map((tab) => (
1130
+ <button
1131
+ key={tab}
1132
+ onClick={() => setAdminTab(tab)}
1133
+ style={{
1134
+ padding: "8px 16px",
1135
+ borderRadius: "6px",
1136
+ border: adminTab === tab ? "1px solid #3B82F6" : "1px solid #333",
1137
+ background: adminTab === tab ? "#1e3a5f" : "#1a1b26",
1138
+ color: adminTab === tab ? "#93c5fd" : "#a0a0b0",
1139
+ cursor: "pointer",
1140
+ fontSize: "13px",
1141
+ textTransform: "capitalize",
1142
+ }}
1143
+ >
1144
+ {tab.replace("-", " ")}
1145
+ </button>
1146
+ ))}
1147
+ </div>
1148
+
1149
+ {adminTab === "overview" && (
1150
+ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px" }}>
1151
+ <div style={{ background: "#1a1b26", borderRadius: "8px", padding: "16px", border: "1px solid #2a2b36" }}>
1152
+ <div style={{ fontSize: "12px", opacity: 0.6, marginBottom: "8px" }}>Server</div>
1153
+ <div style={{ fontSize: "16px", fontWeight: 600 }}>
1154
+ {adminStatus?.server_ready ? "Connected" : "Checking..."}
1155
+ </div>
1156
+ <div style={{ fontSize: "12px", opacity: 0.5 }}>127.0.0.1:8000</div>
1157
+ </div>
1158
+
1159
+ <div style={{ background: "#1a1b26", borderRadius: "8px", padding: "16px", border: "1px solid #2a2b36" }}>
1160
+ <div style={{ fontSize: "12px", opacity: 0.6, marginBottom: "8px" }}>Provider</div>
1161
+ <div style={{ fontSize: "16px", fontWeight: 600 }}>
1162
+ {adminStatus?.provider?.name || "Loading..."}
1163
+ </div>
1164
+ <div style={{ fontSize: "12px", opacity: 0.5 }}>
1165
+ {adminStatus?.provider?.configured
1166
+ ? `${adminStatus.provider.model || "Ready"}`
1167
+ : "Not configured"}
1168
+ </div>
1169
+ </div>
1170
+
1171
+ <div style={{ background: "#1a1b26", borderRadius: "8px", padding: "16px", border: "1px solid #2a2b36" }}>
1172
+ <div style={{ fontSize: "12px", opacity: 0.6, marginBottom: "8px" }}>Workspace Modes</div>
1173
+ <div style={{ fontSize: "12px" }}>
1174
+ Folder: {adminStatus?.workspace?.folder_mode_available ? "Yes" : "—"}
1175
+ </div>
1176
+ <div style={{ fontSize: "12px" }}>
1177
+ Local Git: {adminStatus?.workspace?.local_git_available ? "Yes" : "—"}
1178
+ </div>
1179
+ <div style={{ fontSize: "12px" }}>
1180
+ GitHub: {adminStatus?.workspace?.github_mode_available ? "Yes" : "Optional"}
1181
+ </div>
1182
+ </div>
1183
+
1184
+ <div style={{ background: "#1a1b26", borderRadius: "8px", padding: "16px", border: "1px solid #2a2b36" }}>
1185
+ <div style={{ fontSize: "12px", opacity: 0.6, marginBottom: "8px" }}>GitHub</div>
1186
+ <div style={{ fontSize: "14px" }}>
1187
+ {adminStatus?.github?.connected ? "Connected" : "Optional"}
1188
+ </div>
1189
+ <div style={{ fontSize: "12px", opacity: 0.5 }}>
1190
+ {adminStatus?.github?.username || "Not linked"}
1191
+ </div>
1192
+ </div>
1193
+
1194
+ <div style={{ background: "#1a1b26", borderRadius: "8px", padding: "16px", border: "1px solid #2a2b36" }}>
1195
+ <div style={{ fontSize: "12px", opacity: 0.6, marginBottom: "8px" }}>Sessions</div>
1196
+ <div style={{ fontSize: "14px" }}>—</div>
1197
+ </div>
1198
+
1199
+ <div style={{ background: "#1a1b26", borderRadius: "8px", padding: "16px", border: "1px solid #2a2b36" }}>
1200
+ <div style={{ fontSize: "12px", opacity: 0.6, marginBottom: "8px" }}>Get Started</div>
1201
+ <button
1202
+ onClick={() => setAdminTab("providers")}
1203
+ style={{
1204
+ padding: "6px 12px",
1205
+ background: "#3B82F6",
1206
+ color: "#fff",
1207
+ border: "none",
1208
+ borderRadius: "4px",
1209
+ cursor: "pointer",
1210
+ fontSize: "12px",
1211
+ marginRight: "4px",
1212
+ }}
1213
+ >
1214
+ Configure Provider
1215
+ </button>
1216
+ </div>
1217
+ </div>
1218
+ )}
1219
+
1220
+ {adminTab === "account" && (
1221
+ <AccountTab onLogout={handleLogout} />
1222
+ )}
1223
+
1224
+ {adminTab === "providers" && (
1225
+ <div>
1226
+ <h3 style={{ marginBottom: "16px" }}>AI Providers</h3>
1227
+ <LlmSettings />
1228
+ </div>
1229
+ )}
1230
+
1231
+ {adminTab === "workspace-modes" && (
1232
+ <WorkspaceModesTab
1233
+ showToast={showToast}
1234
+ runtime={startupStatusSnapshot?.workspace?.runtime}
1235
+ onSessionStarted={(result) => {
1236
+ setActiveSessionId(result.session_id);
1237
+ setSessionRefreshNonce((n) => n + 1);
1238
+ setActivePage("workspace");
1239
+ }}
1240
+ />
1241
+ )}
1242
+
1243
+ {adminTab === "integrations" && (
1244
+ <IntegrationsTab
1245
+ userInfo={userInfo}
1246
+ onDisconnect={handleLogout}
1247
+ showToast={showToast}
1248
+ />
1249
+ )}
1250
+
1251
+ {adminTab === "mcp-servers" && (
1252
+ <MCPServersTab showToast={showToast} />
1253
+ )}
1254
+
1255
+ {adminTab === "sandbox" && (
1256
+ <SandboxTab showToast={showToast} />
1257
+ )}
1258
+
1259
+ {adminTab === "security" && (
1260
+ <SecurityTab showToast={showToast} />
1261
+ )}
1262
+
1263
+ {adminTab === "sessions" && (
1264
+ <SessionsTab
1265
+ showToast={showToast}
1266
+ onSelectSession={(s) => {
1267
+ handleSelectSession(s);
1268
+ setActivePage("workspace");
1269
+ }}
1270
+ />
1271
+ )}
1272
+
1273
+ {adminTab === "skills" && <SkillsTab showToast={showToast} />}
1274
+
1275
+ {adminTab === "advanced" && (
1276
+ <AdvancedTab
1277
+ showToast={showToast}
1278
+ onOpenFullSettings={() => setSettingsOpen(true)}
1279
+ />
1280
+ )}
1281
+ </div>
1282
+ )}
1283
+
1284
+ {activePage === "flow" && <FlowViewer />}
1285
+
1286
+ {activePage === "workspace" &&
1287
+ (repo ? (
1288
+ <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
1289
+ <ContextBar
1290
+ contextRepos={contextRepos}
1291
+ activeRepoKey={activeRepoKey}
1292
+ repoStateByKey={repoStateByKey}
1293
+ onActivate={setActiveRepoKey}
1294
+ onRemove={removeRepoFromContext}
1295
+ onAdd={() => setAddRepoOpen(true)}
1296
+ onBranchChange={handleContextBranchChange}
1297
+ />
1298
+
1299
+ <div className="workspace-grid" style={{ flex: 1 }}>
1300
+ <aside className="gp-context-column">
1301
+ <ProjectContextPanel
1302
+ repo={repo}
1303
+ defaultBranch={defaultBranch}
1304
+ currentBranch={currentBranch}
1305
+ sessionBranches={sessionBranches}
1306
+ onBranchChange={handleBranchChange}
1307
+ pulseNonce={pulseNonce}
1308
+ lastExecution={lastExecution}
1309
+ runtime={startupStatusSnapshot?.workspace?.runtime}
1310
+ onSettingsClick={() => setSettingsOpen(true)}
1311
+ />
1312
+ </aside>
1313
+
1314
+ <main className="gp-chat-column">
1315
+ <div className="panel-header">
1316
+ <span>GitPilot chat</span>
1317
+ </div>
1318
+
1319
+ <ChatPanel
1320
+ repo={repo}
1321
+ defaultBranch={defaultBranch}
1322
+ currentBranch={currentBranch}
1323
+ onExecutionComplete={handleExecutionComplete}
1324
+ sessionChatState={sessionChatState}
1325
+ onSessionChatStateChange={updateSessionChat}
1326
+ sessionId={activeSessionId}
1327
+ onEnsureSession={ensureSession}
1328
+ />
1329
+ </main>
1330
+ </div>
1331
+ </div>
1332
+ ) : (
1333
+ <div className="empty-state">
1334
+ <div className="empty-bot">🤖</div>
1335
+ <h1>Select a repository</h1>
1336
+ <p>Select a repo to begin agentic workflow.</p>
1337
+ </div>
1338
+ ))}
1339
+ </main>
1340
+ </div>
1341
+
1342
+ <Footer />
1343
+
1344
+ {repo && (
1345
+ <ProjectSettingsModal
1346
+ owner={repo.full_name?.split("/")[0] || repo.owner}
1347
+ repo={repo.full_name?.split("/")[1] || repo.name}
1348
+ isOpen={settingsOpen}
1349
+ onClose={() => setSettingsOpen(false)}
1350
+ activeEnvId={activeEnvId}
1351
+ onEnvChange={setActiveEnvId}
1352
+ />
1353
+ )}
1354
+
1355
+ <AddRepoModal
1356
+ isOpen={addRepoOpen}
1357
+ onSelect={addRepoToContext}
1358
+ onClose={() => setAddRepoOpen(false)}
1359
+ excludeKeys={contextRepos.map((e) => e.repoKey)}
1360
+ />
1361
+
1362
+ <AboutModal
1363
+ isOpen={aboutOpen}
1364
+ onClose={() => setAboutOpen(false)}
1365
+ />
1366
+
1367
+ {toast && (
1368
+ <div className="toast-notification">
1369
+ <div style={{ fontSize: 12, fontWeight: 700 }}>{toast.title}</div>
1370
+ <div style={{ fontSize: 12, opacity: 0.82 }}>{toast.message}</div>
1371
+ </div>
1372
+ )}
1373
+
1374
+ <style>{`
1375
+ .toast-notification {
1376
+ position: fixed;
1377
+ top: 72px;
1378
+ right: 18px;
1379
+ z-index: 9999;
1380
+ background: #0b0b0d;
1381
+ color: #EDEDED;
1382
+ border: 1px solid rgba(255,255,255,0.12);
1383
+ border-left: 3px solid #3B82F6;
1384
+ border-radius: 10px;
1385
+ padding: 12px 14px;
1386
+ min-width: 320px;
1387
+ box-shadow: 0 10px 30px rgba(0,0,0,0.4);
1388
+ }
1389
+ `}</style>
1390
+ </div>
1391
+ );
1392
+ }
frontend/components/AboutModal.jsx ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AboutModal.jsx
2
+ import React, { useEffect, useCallback, useState } from "react";
3
+ import { apiUrl, safeFetchJSON } from "../utils/api.js";
4
+
5
+ /**
6
+ * AboutModal — "About GitPilot" dialog shown from the user menu.
7
+ *
8
+ * Enterprise design goals:
9
+ * - Prominent brand mark matching docs/logo.svg (orange ring + GP monogram)
10
+ * - Clear identity: name, tagline, version (frontend + backend)
11
+ * - Credits the creator (Ruslan Magana Vsevolodovna) as a link to GitHub
12
+ * - Open-source positioning: Apache 2.0 license + GitHub repo link
13
+ * - Action row: View on GitHub, Report Issue, Documentation
14
+ * - Accessible: role="dialog", aria-modal, aria-labelledby, Escape to close,
15
+ * focus trap via initial focus on close button
16
+ * - Brand palette: #D95C3D accent, #1C1C1F card, #27272A border, #EDEDED text
17
+ */
18
+
19
+ const FRONTEND_VERSION =
20
+ typeof __APP_VERSION__ !== "undefined" ? __APP_VERSION__ : "0.1.5";
21
+
22
+ export default function AboutModal({ isOpen, onClose }) {
23
+ const [backendVersion, setBackendVersion] = useState(null);
24
+
25
+ // Fetch backend version when opened
26
+ useEffect(() => {
27
+ if (!isOpen) return;
28
+ let cancelled = false;
29
+ (async () => {
30
+ try {
31
+ const data = await safeFetchJSON(apiUrl("/api/ping"), { timeout: 4000 });
32
+ if (!cancelled) {
33
+ setBackendVersion(data?.version || null);
34
+ }
35
+ } catch {
36
+ if (!cancelled) setBackendVersion(null);
37
+ }
38
+ })();
39
+ return () => {
40
+ cancelled = true;
41
+ };
42
+ }, [isOpen]);
43
+
44
+ // Escape to close
45
+ useEffect(() => {
46
+ if (!isOpen) return;
47
+ const handleKey = (e) => {
48
+ if (e.key === "Escape") onClose?.();
49
+ };
50
+ document.addEventListener("keydown", handleKey);
51
+ return () => document.removeEventListener("keydown", handleKey);
52
+ }, [isOpen, onClose]);
53
+
54
+ // Lock body scroll while open
55
+ useEffect(() => {
56
+ if (!isOpen) return;
57
+ const prev = document.body.style.overflow;
58
+ document.body.style.overflow = "hidden";
59
+ return () => {
60
+ document.body.style.overflow = prev;
61
+ };
62
+ }, [isOpen]);
63
+
64
+ const handleBackdropClick = useCallback(
65
+ (e) => {
66
+ if (e.target === e.currentTarget) onClose?.();
67
+ },
68
+ [onClose]
69
+ );
70
+
71
+ if (!isOpen) return null;
72
+
73
+ return (
74
+ <div
75
+ role="dialog"
76
+ aria-modal="true"
77
+ aria-labelledby="about-modal-title"
78
+ onClick={handleBackdropClick}
79
+ style={{
80
+ position: "fixed",
81
+ inset: 0,
82
+ zIndex: 2000,
83
+ display: "flex",
84
+ alignItems: "center",
85
+ justifyContent: "center",
86
+ padding: 20,
87
+ background: "rgba(0, 0, 0, 0.65)",
88
+ backdropFilter: "blur(4px)",
89
+ WebkitBackdropFilter: "blur(4px)",
90
+ animation: "aboutBackdropIn 180ms ease-out",
91
+ }}
92
+ >
93
+ <div
94
+ style={{
95
+ position: "relative",
96
+ width: "100%",
97
+ maxWidth: 520,
98
+ background: "#1C1C1F",
99
+ border: "1px solid #27272A",
100
+ borderRadius: 16,
101
+ boxShadow:
102
+ "0 32px 64px -16px rgba(0, 0, 0, 0.8), 0 8px 24px rgba(0, 0, 0, 0.4)",
103
+ color: "#EDEDED",
104
+ fontFamily:
105
+ '"Söhne", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
106
+ letterSpacing: "-0.01em",
107
+ overflow: "hidden",
108
+ animation: "aboutCardIn 220ms cubic-bezier(0.16, 1, 0.3, 1)",
109
+ }}
110
+ >
111
+ {/* Close button */}
112
+ <button
113
+ type="button"
114
+ onClick={onClose}
115
+ aria-label="Close About dialog"
116
+ autoFocus
117
+ style={{
118
+ position: "absolute",
119
+ top: 14,
120
+ right: 14,
121
+ width: 32,
122
+ height: 32,
123
+ background: "transparent",
124
+ border: "1px solid transparent",
125
+ borderRadius: 8,
126
+ color: "#A1A1AA",
127
+ cursor: "pointer",
128
+ display: "inline-flex",
129
+ alignItems: "center",
130
+ justifyContent: "center",
131
+ transition: "all 120ms ease",
132
+ zIndex: 1,
133
+ }}
134
+ onMouseEnter={(e) => {
135
+ e.currentTarget.style.background = "#27272A";
136
+ e.currentTarget.style.color = "#EDEDED";
137
+ }}
138
+ onMouseLeave={(e) => {
139
+ e.currentTarget.style.background = "transparent";
140
+ e.currentTarget.style.color = "#A1A1AA";
141
+ }}
142
+ >
143
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
144
+ <path
145
+ d="M4 4l8 8M12 4l-8 8"
146
+ stroke="currentColor"
147
+ strokeWidth="1.5"
148
+ strokeLinecap="round"
149
+ />
150
+ </svg>
151
+ </button>
152
+
153
+ {/* Hero: brand mark + name */}
154
+ <div
155
+ style={{
156
+ padding: "40px 32px 24px",
157
+ textAlign: "center",
158
+ background:
159
+ "radial-gradient(circle at 50% 0%, rgba(217, 92, 61, 0.12), transparent 70%)",
160
+ }}
161
+ >
162
+ <BrandMark />
163
+
164
+ <h2
165
+ id="about-modal-title"
166
+ style={{
167
+ margin: "20px 0 6px",
168
+ fontSize: 24,
169
+ fontWeight: 700,
170
+ color: "#EDEDED",
171
+ letterSpacing: "-0.02em",
172
+ }}
173
+ >
174
+ GitPilot
175
+ </h2>
176
+ <div
177
+ style={{
178
+ fontSize: 13,
179
+ color: "#A1A1AA",
180
+ marginBottom: 10,
181
+ }}
182
+ >
183
+ Enterprise Workspace Copilot
184
+ </div>
185
+
186
+ <div
187
+ style={{
188
+ display: "inline-flex",
189
+ alignItems: "center",
190
+ gap: 8,
191
+ padding: "4px 12px",
192
+ background: "rgba(217, 92, 61, 0.12)",
193
+ border: "1px solid rgba(217, 92, 61, 0.25)",
194
+ borderRadius: 999,
195
+ fontSize: 11,
196
+ fontWeight: 600,
197
+ color: "#ff7a3c",
198
+ letterSpacing: "0.04em",
199
+ textTransform: "uppercase",
200
+ }}
201
+ >
202
+ <span
203
+ aria-hidden="true"
204
+ style={{
205
+ width: 6,
206
+ height: 6,
207
+ borderRadius: "50%",
208
+ background: "#ff7a3c",
209
+ boxShadow: "0 0 8px rgba(255, 122, 60, 0.8)",
210
+ }}
211
+ />
212
+ Open Source · Apache 2.0
213
+ </div>
214
+ </div>
215
+
216
+ {/* Body */}
217
+ <div style={{ padding: "8px 32px 0" }}>
218
+ <p
219
+ style={{
220
+ fontSize: 14,
221
+ lineHeight: 1.6,
222
+ color: "#A1A1AA",
223
+ textAlign: "center",
224
+ margin: "0 0 24px",
225
+ }}
226
+ >
227
+ An agentic AI coding companion for your repositories. Ask, plan,
228
+ code, and ship — with multi-LLM support, security scanning, and
229
+ VS Code integration.
230
+ </p>
231
+
232
+ {/* Meta table */}
233
+ <div
234
+ style={{
235
+ background: "#131316",
236
+ border: "1px solid #27272A",
237
+ borderRadius: 10,
238
+ padding: "4px 0",
239
+ marginBottom: 24,
240
+ }}
241
+ >
242
+ <MetaRow label="Version" value={`v${FRONTEND_VERSION}`} />
243
+ <MetaRow
244
+ label="Backend"
245
+ value={backendVersion ? `v${backendVersion}` : "—"}
246
+ />
247
+ <MetaRow label="License" value="Apache 2.0" />
248
+ <MetaRow
249
+ label="Created by"
250
+ value={
251
+ <a
252
+ href="https://github.com/ruslanmv"
253
+ target="_blank"
254
+ rel="noopener noreferrer"
255
+ style={{
256
+ color: "#ff7a3c",
257
+ textDecoration: "none",
258
+ fontWeight: 600,
259
+ }}
260
+ onMouseEnter={(e) =>
261
+ (e.currentTarget.style.textDecoration = "underline")
262
+ }
263
+ onMouseLeave={(e) =>
264
+ (e.currentTarget.style.textDecoration = "none")
265
+ }
266
+ >
267
+ Ruslan Magana Vsevolodovna
268
+ </a>
269
+ }
270
+ isLast
271
+ />
272
+ </div>
273
+ </div>
274
+
275
+ {/* Action row */}
276
+ <div
277
+ style={{
278
+ padding: "0 32px 32px",
279
+ display: "grid",
280
+ gridTemplateColumns: "1fr 1fr 1fr",
281
+ gap: 8,
282
+ }}
283
+ >
284
+ <ActionButton
285
+ href="https://github.com/ruslanmv/gitpilot"
286
+ icon={<GitHubIcon />}
287
+ label="GitHub"
288
+ />
289
+ <ActionButton
290
+ href="https://github.com/ruslanmv/gitpilot#readme"
291
+ icon={<DocsIcon />}
292
+ label="Docs"
293
+ />
294
+ <ActionButton
295
+ href="https://github.com/ruslanmv/gitpilot/issues"
296
+ icon={<BugIcon />}
297
+ label="Report"
298
+ />
299
+ </div>
300
+
301
+ {/* Footer */}
302
+ <div
303
+ style={{
304
+ padding: "16px 32px",
305
+ background: "#131316",
306
+ borderTop: "1px solid #27272A",
307
+ fontSize: 11,
308
+ color: "#71717a",
309
+ textAlign: "center",
310
+ lineHeight: 1.5,
311
+ }}
312
+ >
313
+ &copy; {new Date().getFullYear()} GitPilot · Made with care for
314
+ developers everywhere
315
+ </div>
316
+ </div>
317
+
318
+ <style>{`
319
+ @keyframes aboutBackdropIn {
320
+ from { opacity: 0; }
321
+ to { opacity: 1; }
322
+ }
323
+ @keyframes aboutCardIn {
324
+ from { opacity: 0; transform: translateY(12px) scale(0.97); }
325
+ to { opacity: 1; transform: translateY(0) scale(1); }
326
+ }
327
+ `}</style>
328
+ </div>
329
+ );
330
+ }
331
+
332
+ // ── Brand mark (mirrors docs/logo.svg) ──────────────────────────────
333
+ function BrandMark() {
334
+ return (
335
+ <div
336
+ aria-hidden="true"
337
+ style={{
338
+ position: "relative",
339
+ width: 88,
340
+ height: 88,
341
+ margin: "0 auto",
342
+ }}
343
+ >
344
+ {/* Outer subtle ring */}
345
+ <div
346
+ style={{
347
+ position: "absolute",
348
+ inset: 0,
349
+ borderRadius: "50%",
350
+ border: "2px solid rgba(255, 122, 60, 0.22)",
351
+ }}
352
+ />
353
+ {/* Active arc (top-right, uses conic gradient for smooth arc) */}
354
+ <div
355
+ style={{
356
+ position: "absolute",
357
+ inset: -2,
358
+ borderRadius: "50%",
359
+ background:
360
+ "conic-gradient(from -90deg, #ff7a3c 0deg, #D95C3D 90deg, transparent 91deg, transparent 360deg)",
361
+ mask: "radial-gradient(circle, transparent 40px, black 42px, black 44px, transparent 46px)",
362
+ WebkitMask:
363
+ "radial-gradient(circle, transparent 40px, black 42px, black 44px, transparent 46px)",
364
+ }}
365
+ />
366
+ {/* Soft core glow */}
367
+ <div
368
+ style={{
369
+ position: "absolute",
370
+ inset: 14,
371
+ borderRadius: "50%",
372
+ background:
373
+ "radial-gradient(circle, rgba(255, 122, 60, 0.22) 0%, rgba(255, 122, 60, 0.06) 60%, transparent 100%)",
374
+ }}
375
+ />
376
+ {/* GP monogram */}
377
+ <div
378
+ style={{
379
+ position: "absolute",
380
+ inset: 0,
381
+ display: "flex",
382
+ alignItems: "center",
383
+ justifyContent: "center",
384
+ fontSize: 28,
385
+ fontWeight: 700,
386
+ color: "#EDEDED",
387
+ letterSpacing: "-1px",
388
+ }}
389
+ >
390
+ GP
391
+ </div>
392
+ </div>
393
+ );
394
+ }
395
+
396
+ // ── Meta row ────────────────────────────────────────────────────────
397
+ function MetaRow({ label, value, isLast = false }) {
398
+ return (
399
+ <div
400
+ style={{
401
+ display: "flex",
402
+ justifyContent: "space-between",
403
+ alignItems: "center",
404
+ padding: "10px 16px",
405
+ borderBottom: isLast ? "none" : "1px solid #27272A",
406
+ fontSize: 13,
407
+ }}
408
+ >
409
+ <span style={{ color: "#71717a", fontWeight: 500 }}>{label}</span>
410
+ <span style={{ color: "#EDEDED", fontWeight: 600, textAlign: "right" }}>
411
+ {value}
412
+ </span>
413
+ </div>
414
+ );
415
+ }
416
+
417
+ // ── Action button ───────────────────────────────────────────────────
418
+ function ActionButton({ href, icon, label }) {
419
+ return (
420
+ <a
421
+ href={href}
422
+ target="_blank"
423
+ rel="noopener noreferrer"
424
+ style={{
425
+ display: "flex",
426
+ flexDirection: "column",
427
+ alignItems: "center",
428
+ justifyContent: "center",
429
+ gap: 6,
430
+ padding: "12px 8px",
431
+ background: "#131316",
432
+ border: "1px solid #27272A",
433
+ borderRadius: 10,
434
+ color: "#EDEDED",
435
+ fontSize: 12,
436
+ fontWeight: 600,
437
+ textDecoration: "none",
438
+ transition: "all 140ms ease",
439
+ }}
440
+ onMouseEnter={(e) => {
441
+ e.currentTarget.style.borderColor = "#D95C3D";
442
+ e.currentTarget.style.background = "rgba(217, 92, 61, 0.08)";
443
+ }}
444
+ onMouseLeave={(e) => {
445
+ e.currentTarget.style.borderColor = "#27272A";
446
+ e.currentTarget.style.background = "#131316";
447
+ }}
448
+ >
449
+ <span
450
+ aria-hidden="true"
451
+ style={{
452
+ color: "#ff7a3c",
453
+ display: "inline-flex",
454
+ }}
455
+ >
456
+ {icon}
457
+ </span>
458
+ <span>{label}</span>
459
+ </a>
460
+ );
461
+ }
462
+
463
+ // ── Icons ───────────────────────────────────────────────────────────
464
+ function GitHubIcon() {
465
+ return (
466
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
467
+ <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405 1.02 0 2.04.135 3 .405 2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
468
+ </svg>
469
+ );
470
+ }
471
+
472
+ function DocsIcon() {
473
+ return (
474
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
475
+ <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
476
+ <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
477
+ </svg>
478
+ );
479
+ }
480
+
481
+ function BugIcon() {
482
+ return (
483
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
484
+ <rect x="8" y="6" width="8" height="14" rx="4" />
485
+ <path d="M19 7l-3 2M5 7l3 2M19 13h-3M5 13h3M19 19l-3-2M5 19l3-2M12 6V2" />
486
+ </svg>
487
+ );
488
+ }
frontend/components/AddRepoModal.jsx ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useCallback, useEffect, useState } from "react";
2
+ import { createPortal } from "react-dom";
3
+ import { authFetch } from "../utils/api.js";
4
+
5
+ /**
6
+ * AddRepoModal — lightweight portal modal for adding repos to context.
7
+ *
8
+ * Embeds a minimal repo search/list (not the full RepoSelector) to keep
9
+ * the modal focused. Filters out repos already in context.
10
+ */
11
+ export default function AddRepoModal({ isOpen, onSelect, onClose, excludeKeys = [] }) {
12
+ const [query, setQuery] = useState("");
13
+ const [repos, setRepos] = useState([]);
14
+ const [loading, setLoading] = useState(false);
15
+
16
+ const fetchRepos = useCallback(
17
+ async (searchQuery) => {
18
+ setLoading(true);
19
+ try {
20
+ const params = new URLSearchParams({ per_page: "50" });
21
+ if (searchQuery) params.set("query", searchQuery);
22
+ const res = await authFetch(`/api/repos?${params}`);
23
+ if (!res.ok) return;
24
+ const data = await res.json();
25
+ setRepos(data.repositories || []);
26
+ } catch (err) {
27
+ console.warn("AddRepoModal: fetch failed:", err);
28
+ } finally {
29
+ setLoading(false);
30
+ }
31
+ },
32
+ []
33
+ );
34
+
35
+ useEffect(() => {
36
+ if (isOpen) {
37
+ setQuery("");
38
+ fetchRepos("");
39
+ }
40
+ }, [isOpen, fetchRepos]);
41
+
42
+ // Debounced search
43
+ useEffect(() => {
44
+ if (!isOpen) return;
45
+ const t = setTimeout(() => fetchRepos(query), 300);
46
+ return () => clearTimeout(t);
47
+ }, [query, isOpen, fetchRepos]);
48
+
49
+ const excludeSet = new Set(excludeKeys);
50
+ const filtered = repos.filter((r) => {
51
+ const key = r.full_name || `${r.owner}/${r.name}`;
52
+ return !excludeSet.has(key);
53
+ });
54
+
55
+ if (!isOpen) return null;
56
+
57
+ return createPortal(
58
+ <div
59
+ style={styles.overlay}
60
+ onMouseDown={(e) => {
61
+ if (e.target === e.currentTarget) onClose();
62
+ }}
63
+ >
64
+ <div style={styles.modal} onMouseDown={(e) => e.stopPropagation()}>
65
+ <div style={styles.header}>
66
+ <span style={styles.headerTitle}>Add Repository</span>
67
+ <button type="button" style={styles.closeBtn} onClick={onClose}>
68
+ &times;
69
+ </button>
70
+ </div>
71
+
72
+ <div style={styles.searchBox}>
73
+ <input
74
+ type="text"
75
+ placeholder="Search repositories..."
76
+ value={query}
77
+ onChange={(e) => setQuery(e.target.value)}
78
+ style={styles.searchInput}
79
+ autoFocus
80
+ onKeyDown={(e) => {
81
+ if (e.key === "Escape") onClose();
82
+ }}
83
+ />
84
+ </div>
85
+
86
+ <div style={styles.list}>
87
+ {loading && filtered.length === 0 && (
88
+ <div style={styles.statusRow}>Loading...</div>
89
+ )}
90
+ {!loading && filtered.length === 0 && (
91
+ <div style={styles.statusRow}>
92
+ {excludeKeys.length > 0 && repos.length > 0
93
+ ? "All matching repos are already in context"
94
+ : "No repositories found"}
95
+ </div>
96
+ )}
97
+ {filtered.map((r) => {
98
+ const key = r.full_name || `${r.owner}/${r.name}`;
99
+ return (
100
+ <button
101
+ key={r.id || key}
102
+ type="button"
103
+ style={styles.repoRow}
104
+ onClick={() => onSelect(r)}
105
+ >
106
+ <div style={styles.repoInfo}>
107
+ <span style={styles.repoName}>{r.name}</span>
108
+ <span style={styles.repoOwner}>{r.owner}</span>
109
+ </div>
110
+ <div style={styles.repoMeta}>
111
+ {r.private && <span style={styles.privateBadge}>Private</span>}
112
+ <span style={styles.branchHint}>{r.default_branch || "main"}</span>
113
+ </div>
114
+ </button>
115
+ );
116
+ })}
117
+ {loading && filtered.length > 0 && (
118
+ <div style={styles.statusRow}>Updating...</div>
119
+ )}
120
+ </div>
121
+ </div>
122
+ </div>,
123
+ document.body
124
+ );
125
+ }
126
+
127
+ const styles = {
128
+ overlay: {
129
+ position: "fixed",
130
+ top: 0,
131
+ left: 0,
132
+ right: 0,
133
+ bottom: 0,
134
+ backgroundColor: "rgba(0, 0, 0, 0.6)",
135
+ zIndex: 10000,
136
+ display: "flex",
137
+ alignItems: "center",
138
+ justifyContent: "center",
139
+ },
140
+ modal: {
141
+ width: 440,
142
+ maxHeight: "70vh",
143
+ backgroundColor: "#131316",
144
+ border: "1px solid #27272A",
145
+ borderRadius: 12,
146
+ display: "flex",
147
+ flexDirection: "column",
148
+ overflow: "hidden",
149
+ boxShadow: "0 12px 40px rgba(0,0,0,0.5)",
150
+ },
151
+ header: {
152
+ display: "flex",
153
+ justifyContent: "space-between",
154
+ alignItems: "center",
155
+ padding: "12px 14px",
156
+ borderBottom: "1px solid #27272A",
157
+ backgroundColor: "#18181B",
158
+ },
159
+ headerTitle: {
160
+ fontSize: 14,
161
+ fontWeight: 600,
162
+ color: "#E4E4E7",
163
+ },
164
+ closeBtn: {
165
+ width: 26,
166
+ height: 26,
167
+ borderRadius: 6,
168
+ border: "1px solid #3F3F46",
169
+ background: "transparent",
170
+ color: "#A1A1AA",
171
+ fontSize: 16,
172
+ cursor: "pointer",
173
+ display: "flex",
174
+ alignItems: "center",
175
+ justifyContent: "center",
176
+ },
177
+ searchBox: {
178
+ padding: "10px 12px",
179
+ borderBottom: "1px solid #27272A",
180
+ },
181
+ searchInput: {
182
+ width: "100%",
183
+ padding: "8px 10px",
184
+ borderRadius: 6,
185
+ border: "1px solid #3F3F46",
186
+ background: "#18181B",
187
+ color: "#E4E4E7",
188
+ fontSize: 13,
189
+ outline: "none",
190
+ fontFamily: "monospace",
191
+ boxSizing: "border-box",
192
+ },
193
+ list: {
194
+ flex: 1,
195
+ overflowY: "auto",
196
+ maxHeight: 360,
197
+ },
198
+ statusRow: {
199
+ padding: "16px 12px",
200
+ textAlign: "center",
201
+ fontSize: 12,
202
+ color: "#71717A",
203
+ },
204
+ repoRow: {
205
+ display: "flex",
206
+ alignItems: "center",
207
+ justifyContent: "space-between",
208
+ width: "100%",
209
+ padding: "10px 14px",
210
+ border: "none",
211
+ borderBottom: "1px solid rgba(39, 39, 42, 0.5)",
212
+ background: "transparent",
213
+ color: "#E4E4E7",
214
+ cursor: "pointer",
215
+ textAlign: "left",
216
+ transition: "background-color 0.1s",
217
+ },
218
+ repoInfo: {
219
+ display: "flex",
220
+ flexDirection: "column",
221
+ gap: 2,
222
+ minWidth: 0,
223
+ },
224
+ repoName: {
225
+ fontSize: 13,
226
+ fontWeight: 600,
227
+ fontFamily: "monospace",
228
+ overflow: "hidden",
229
+ textOverflow: "ellipsis",
230
+ whiteSpace: "nowrap",
231
+ },
232
+ repoOwner: {
233
+ fontSize: 11,
234
+ color: "#71717A",
235
+ },
236
+ repoMeta: {
237
+ display: "flex",
238
+ alignItems: "center",
239
+ gap: 8,
240
+ flexShrink: 0,
241
+ },
242
+ privateBadge: {
243
+ fontSize: 9,
244
+ padding: "1px 5px",
245
+ borderRadius: 8,
246
+ backgroundColor: "rgba(239, 68, 68, 0.12)",
247
+ color: "#F87171",
248
+ fontWeight: 600,
249
+ textTransform: "uppercase",
250
+ },
251
+ branchHint: {
252
+ fontSize: 10,
253
+ color: "#52525B",
254
+ fontFamily: "monospace",
255
+ },
256
+ };
frontend/components/AdminTabs/AccountTab.jsx ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useState } from "react";
2
+ import { apiUrl, getAuthHeaders, clearSessionToken } from "../../utils/api.js";
3
+
4
+ // Account settings — the GitPilot account (your email/password identity).
5
+ // This is intentionally separate from the GitHub connection, which only grants
6
+ // access to repositories. Here you manage who you are; GitHub manages what you
7
+ // can touch.
8
+ export default function AccountTab({ onLogout }) {
9
+ const [account, setAccount] = useState(null);
10
+ const [loading, setLoading] = useState(true);
11
+ const [loadError, setLoadError] = useState("");
12
+
13
+ // Profile
14
+ const [name, setName] = useState("");
15
+ const [savingProfile, setSavingProfile] = useState(false);
16
+ const [profileMsg, setProfileMsg] = useState("");
17
+
18
+ // Password
19
+ const [curPw, setCurPw] = useState("");
20
+ const [newPw, setNewPw] = useState("");
21
+ const [confirmPw, setConfirmPw] = useState("");
22
+ const [savingPw, setSavingPw] = useState(false);
23
+ const [pwMsg, setPwMsg] = useState(null); // {kind, text}
24
+
25
+ // Delete (danger zone)
26
+ const [confirmDelete, setConfirmDelete] = useState(false);
27
+ const [delPw, setDelPw] = useState("");
28
+ const [deleting, setDeleting] = useState(false);
29
+ const [delErr, setDelErr] = useState("");
30
+
31
+ const jsonHeaders = () => ({ "Content-Type": "application/json", ...getAuthHeaders() });
32
+
33
+ const loadAccount = async () => {
34
+ setLoading(true);
35
+ setLoadError("");
36
+ try {
37
+ const res = await fetch(apiUrl("/api/account/me"), {
38
+ credentials: "include",
39
+ headers: getAuthHeaders(),
40
+ });
41
+ if (res.status === 401) {
42
+ setAccount(null);
43
+ return;
44
+ }
45
+ const data = await res.json();
46
+ if (!res.ok) throw new Error(data.detail || "Could not load your account.");
47
+ setAccount(data);
48
+ setName(data.name || "");
49
+ } catch (e) {
50
+ setLoadError(e.message || "Could not load your account.");
51
+ } finally {
52
+ setLoading(false);
53
+ }
54
+ };
55
+
56
+ useEffect(() => {
57
+ loadAccount();
58
+ }, []);
59
+
60
+ const isPasswordAccount = account?.provider === "password";
61
+
62
+ const saveProfile = async () => {
63
+ setSavingProfile(true);
64
+ setProfileMsg("");
65
+ try {
66
+ const res = await fetch(apiUrl("/api/account/profile"), {
67
+ method: "PATCH",
68
+ credentials: "include",
69
+ headers: jsonHeaders(),
70
+ body: JSON.stringify({ name: name.trim() || null }),
71
+ });
72
+ const data = await res.json();
73
+ if (!res.ok) throw new Error(data.detail || "Could not save your profile.");
74
+ setAccount(data);
75
+ setProfileMsg("Saved.");
76
+ setTimeout(() => setProfileMsg(""), 3000);
77
+ } catch (e) {
78
+ setProfileMsg(e.message || "Could not save your profile.");
79
+ } finally {
80
+ setSavingProfile(false);
81
+ }
82
+ };
83
+
84
+ const changePassword = async () => {
85
+ setPwMsg(null);
86
+ if (newPw.length < 8) {
87
+ setPwMsg({ kind: "err", text: "New password must be at least 8 characters." });
88
+ return;
89
+ }
90
+ if (newPw !== confirmPw) {
91
+ setPwMsg({ kind: "err", text: "New password and confirmation don't match." });
92
+ return;
93
+ }
94
+ setSavingPw(true);
95
+ try {
96
+ const res = await fetch(apiUrl("/api/account/password/change"), {
97
+ method: "POST",
98
+ credentials: "include",
99
+ headers: jsonHeaders(),
100
+ body: JSON.stringify({ current_password: curPw, new_password: newPw }),
101
+ });
102
+ const data = await res.json();
103
+ if (!res.ok) throw new Error(data.detail || "Could not change your password.");
104
+ setPwMsg({ kind: "ok", text: "Password changed successfully." });
105
+ setCurPw(""); setNewPw(""); setConfirmPw("");
106
+ } catch (e) {
107
+ setPwMsg({ kind: "err", text: e.message || "Could not change your password." });
108
+ } finally {
109
+ setSavingPw(false);
110
+ }
111
+ };
112
+
113
+ const deleteAccount = async () => {
114
+ setDeleting(true);
115
+ setDelErr("");
116
+ try {
117
+ const res = await fetch(apiUrl("/api/account/delete"), {
118
+ method: "POST",
119
+ credentials: "include",
120
+ headers: jsonHeaders(),
121
+ body: JSON.stringify({ password: delPw || null }),
122
+ });
123
+ const data = await res.json().catch(() => ({}));
124
+ if (!res.ok) throw new Error(data.detail || "Could not delete your account.");
125
+ // Gone for good — clear local session and return to a signed-out state.
126
+ clearSessionToken();
127
+ if (typeof onLogout === "function") onLogout();
128
+ window.location.href = "/";
129
+ } catch (e) {
130
+ setDelErr(e.message || "Could not delete your account.");
131
+ setDeleting(false);
132
+ }
133
+ };
134
+
135
+ if (loading) {
136
+ return (
137
+ <div className="settings-root">
138
+ <h1>Account</h1>
139
+ <p className="settings-muted">Loading your account…</p>
140
+ </div>
141
+ );
142
+ }
143
+
144
+ // Signed in with GitHub only (no GitPilot email account) — explain the split.
145
+ if (!account) {
146
+ return (
147
+ <div className="settings-root">
148
+ <h1>Account</h1>
149
+ <p className="settings-muted">
150
+ This is your <strong>GitPilot account</strong> — your email/password identity,
151
+ separate from the GitHub connection that grants repository access.
152
+ </p>
153
+ <div className="settings-card">
154
+ <div className="settings-title">You're signed in with GitHub</div>
155
+ <div className="settings-hint">
156
+ {loadError
157
+ ? loadError
158
+ : "You don't have a GitPilot email account yet. GitHub sign-in gives you repository access; create a GitPilot account to manage a profile, password, and account settings here."}
159
+ </div>
160
+ </div>
161
+ </div>
162
+ );
163
+ }
164
+
165
+ return (
166
+ <div className="settings-root">
167
+ <h1>Account</h1>
168
+ <p className="settings-muted">
169
+ Your <strong>GitPilot account</strong> — your identity and sign-in. This is
170
+ separate from the GitHub connection, which only grants repository access.
171
+ </p>
172
+
173
+ {/* Profile */}
174
+ <div className="settings-card">
175
+ <div className="settings-title">Profile</div>
176
+
177
+ <label className="settings-label">Email</label>
178
+ <input className="settings-input" value={account.email} disabled readOnly />
179
+ <div className="settings-hint" style={{ marginTop: 6, marginBottom: 12 }}>
180
+ {account.email_verified ? "✓ Verified" : "Not verified"}
181
+ {" · "}Sign-in method: {account.provider}
182
+ </div>
183
+
184
+ <label className="settings-label">Display name</label>
185
+ <input
186
+ className="settings-input"
187
+ value={name}
188
+ onChange={(e) => setName(e.target.value)}
189
+ placeholder="Your name"
190
+ />
191
+
192
+ <div className="settings-actions" style={{ marginTop: 14 }}>
193
+ <button type="button" className="settings-save-btn" onClick={saveProfile} disabled={savingProfile}>
194
+ {savingProfile ? "Saving…" : "Save profile"}
195
+ </button>
196
+ {profileMsg && <span className="settings-muted" style={{ alignSelf: "center" }}>{profileMsg}</span>}
197
+ </div>
198
+ </div>
199
+
200
+ {/* Password */}
201
+ {isPasswordAccount && (
202
+ <div className="settings-card">
203
+ <div className="settings-title">Change password</div>
204
+
205
+ {pwMsg && (
206
+ <div className={pwMsg.kind === "ok" ? "settings-success-banner" : "settings-error-banner"}>
207
+ {pwMsg.text}
208
+ </div>
209
+ )}
210
+
211
+ <label className="settings-label">Current password</label>
212
+ <input
213
+ className="settings-input"
214
+ type="password"
215
+ value={curPw}
216
+ onChange={(e) => setCurPw(e.target.value)}
217
+ placeholder="Current password"
218
+ autoComplete="current-password"
219
+ />
220
+
221
+ <label className="settings-label">New password</label>
222
+ <input
223
+ className="settings-input"
224
+ type="password"
225
+ value={newPw}
226
+ onChange={(e) => setNewPw(e.target.value)}
227
+ placeholder="At least 8 characters"
228
+ autoComplete="new-password"
229
+ />
230
+
231
+ <label className="settings-label">Confirm new password</label>
232
+ <input
233
+ className="settings-input"
234
+ type="password"
235
+ value={confirmPw}
236
+ onChange={(e) => setConfirmPw(e.target.value)}
237
+ placeholder="Re-enter new password"
238
+ autoComplete="new-password"
239
+ />
240
+
241
+ <div className="settings-actions" style={{ marginTop: 14 }}>
242
+ <button
243
+ type="button"
244
+ className="settings-save-btn"
245
+ onClick={changePassword}
246
+ disabled={savingPw || !curPw || !newPw || !confirmPw}
247
+ >
248
+ {savingPw ? "Updating…" : "Update password"}
249
+ </button>
250
+ </div>
251
+ </div>
252
+ )}
253
+
254
+ {/* Danger zone */}
255
+ <div className="settings-danger-card">
256
+ <div className="settings-danger-title">Danger zone</div>
257
+ <div className="settings-hint" style={{ marginBottom: 12 }}>
258
+ Permanently delete your GitPilot account and all of its data. This cannot be undone.
259
+ </div>
260
+
261
+ {!confirmDelete ? (
262
+ <button type="button" className="settings-danger-btn" onClick={() => setConfirmDelete(true)}>
263
+ Delete account
264
+ </button>
265
+ ) : (
266
+ <div className="settings-danger-confirm">
267
+ <div className="settings-hint" style={{ marginBottom: 10 }}>
268
+ This is permanent. {isPasswordAccount ? "Enter your password to confirm." : "Confirm to proceed."}
269
+ </div>
270
+ {delErr && <div className="settings-error-banner">{delErr}</div>}
271
+ {isPasswordAccount && (
272
+ <input
273
+ className="settings-input"
274
+ type="password"
275
+ value={delPw}
276
+ onChange={(e) => setDelPw(e.target.value)}
277
+ placeholder="Your password"
278
+ autoComplete="current-password"
279
+ style={{ marginBottom: 12 }}
280
+ />
281
+ )}
282
+ <div className="settings-actions">
283
+ <button
284
+ type="button"
285
+ className="settings-danger-btn"
286
+ onClick={deleteAccount}
287
+ disabled={deleting || (isPasswordAccount && !delPw)}
288
+ >
289
+ {deleting ? "Deleting…" : "Permanently delete my account"}
290
+ </button>
291
+ <button
292
+ type="button"
293
+ className="settings-secondary-btn"
294
+ onClick={() => { setConfirmDelete(false); setDelPw(""); setDelErr(""); }}
295
+ disabled={deleting}
296
+ >
297
+ Cancel
298
+ </button>
299
+ </div>
300
+ </div>
301
+ )}
302
+ </div>
303
+ </div>
304
+ );
305
+ }
frontend/components/AdminTabs/AdvancedTab.jsx ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/AdvancedTab.jsx
2
+ import React, { useEffect, useState, useCallback } from "react";
3
+ import { apiUrl, safeFetchJSON } from "../../utils/api.js";
4
+
5
+ /**
6
+ * Advanced tab — inline toggles for:
7
+ * - Lite Mode (via /api/settings/topology — sets topology to "lite_mode")
8
+ * - Permission Mode (normal | auto | plan via /api/permissions/mode)
9
+ * - Link to full Settings modal for power users
10
+ *
11
+ * Best practices applied:
12
+ * - Optimistic UI with rollback on error
13
+ * - Each setting has its own loading indicator (no global lock)
14
+ * - Descriptions explain what each mode does
15
+ * - ARIA-labeled toggle switches for accessibility
16
+ */
17
+
18
+ const PERMISSION_MODES = [
19
+ {
20
+ value: "normal",
21
+ label: "Normal",
22
+ description:
23
+ "Ask before writing files or running commands (recommended).",
24
+ },
25
+ {
26
+ value: "auto",
27
+ label: "Auto",
28
+ description:
29
+ "Approve all tool calls automatically. Use only when you trust the agent.",
30
+ },
31
+ {
32
+ value: "plan",
33
+ label: "Plan Only",
34
+ description:
35
+ "Read-only mode. Agent cannot write files or run commands.",
36
+ },
37
+ ];
38
+
39
+ function ToggleSwitch({ checked, onChange, disabled, ariaLabel }) {
40
+ return (
41
+ <button
42
+ type="button"
43
+ role="switch"
44
+ aria-checked={checked}
45
+ aria-label={ariaLabel}
46
+ onClick={() => !disabled && onChange(!checked)}
47
+ disabled={disabled}
48
+ style={{
49
+ position: "relative",
50
+ width: "44px",
51
+ height: "24px",
52
+ borderRadius: "12px",
53
+ background: checked ? "#3B82F6" : "#374151",
54
+ border: "none",
55
+ cursor: disabled ? "not-allowed" : "pointer",
56
+ transition: "background 150ms ease",
57
+ padding: 0,
58
+ opacity: disabled ? 0.5 : 1,
59
+ }}
60
+ >
61
+ <div
62
+ style={{
63
+ position: "absolute",
64
+ top: "2px",
65
+ left: checked ? "22px" : "2px",
66
+ width: "20px",
67
+ height: "20px",
68
+ borderRadius: "50%",
69
+ background: "#fff",
70
+ transition: "left 150ms ease",
71
+ boxShadow: "0 1px 3px rgba(0,0,0,0.3)",
72
+ }}
73
+ />
74
+ </button>
75
+ );
76
+ }
77
+
78
+ export default function AdvancedTab({ showToast, onOpenFullSettings }) {
79
+ const [liteMode, setLiteMode] = useState(false);
80
+ const [permissionMode, setPermissionMode] = useState("normal");
81
+ const [loading, setLoading] = useState(true);
82
+ const [updatingLite, setUpdatingLite] = useState(false);
83
+ const [updatingPerm, setUpdatingPerm] = useState(false);
84
+ const [error, setError] = useState(null);
85
+
86
+ // Initial fetch: topology preference + permission mode
87
+ useEffect(() => {
88
+ let cancelled = false;
89
+ (async () => {
90
+ try {
91
+ const [topo, perms] = await Promise.all([
92
+ safeFetchJSON(apiUrl("/api/settings/topology"), { timeout: 5000 })
93
+ .catch(() => ({ topology: null })),
94
+ safeFetchJSON(apiUrl("/api/permissions"), { timeout: 5000 })
95
+ .catch(() => ({ mode: "normal" })),
96
+ ]);
97
+ if (cancelled) return;
98
+ setLiteMode(topo?.topology === "lite_mode");
99
+ setPermissionMode(perms?.mode || perms?.policy?.mode || "normal");
100
+ } catch (err) {
101
+ if (!cancelled) setError(err?.message || "Failed to load settings");
102
+ } finally {
103
+ if (!cancelled) setLoading(false);
104
+ }
105
+ })();
106
+ return () => {
107
+ cancelled = true;
108
+ };
109
+ }, []);
110
+
111
+ const handleLiteToggle = useCallback(async (next) => {
112
+ setUpdatingLite(true);
113
+ setError(null);
114
+ const previous = liteMode;
115
+ setLiteMode(next); // optimistic
116
+ try {
117
+ await safeFetchJSON(apiUrl("/api/settings/topology"), {
118
+ method: "POST",
119
+ headers: { "Content-Type": "application/json" },
120
+ body: JSON.stringify({ topology: next ? "lite_mode" : null }),
121
+ timeout: 5000,
122
+ });
123
+ showToast?.(
124
+ "Lite Mode " + (next ? "enabled" : "disabled"),
125
+ next
126
+ ? "Single-agent path — better for small local models."
127
+ : "Multi-agent path — uses full CrewAI orchestration."
128
+ );
129
+ } catch (err) {
130
+ setLiteMode(previous); // rollback
131
+ setError(err?.message || "Failed to update lite mode");
132
+ } finally {
133
+ setUpdatingLite(false);
134
+ }
135
+ }, [liteMode, showToast]);
136
+
137
+ const handlePermissionChange = useCallback(async (next) => {
138
+ setUpdatingPerm(true);
139
+ setError(null);
140
+ const previous = permissionMode;
141
+ setPermissionMode(next); // optimistic
142
+ try {
143
+ const res = await fetch(apiUrl("/api/permissions/mode"), {
144
+ method: "PUT",
145
+ headers: { "Content-Type": "application/json" },
146
+ body: JSON.stringify({ mode: next }),
147
+ });
148
+ if (!res.ok) {
149
+ const body = await res.json().catch(() => ({}));
150
+ throw new Error(body.detail || `HTTP ${res.status}`);
151
+ }
152
+ showToast?.(
153
+ "Permission mode updated",
154
+ `Set to ${next}.`
155
+ );
156
+ } catch (err) {
157
+ setPermissionMode(previous); // rollback
158
+ setError(err?.message || "Failed to update permission mode");
159
+ } finally {
160
+ setUpdatingPerm(false);
161
+ }
162
+ }, [permissionMode, showToast]);
163
+
164
+ if (loading) {
165
+ return (
166
+ <div>
167
+ <h3 style={{ marginBottom: "16px" }}>Advanced</h3>
168
+ <div
169
+ style={{
170
+ background: "#1a1b26",
171
+ borderRadius: "8px",
172
+ padding: "40px 20px",
173
+ textAlign: "center",
174
+ border: "1px solid #2a2b36",
175
+ fontSize: "12px",
176
+ opacity: 0.6,
177
+ }}
178
+ >
179
+ Loading advanced settings...
180
+ </div>
181
+ </div>
182
+ );
183
+ }
184
+
185
+ return (
186
+ <div>
187
+ <h3 style={{ marginBottom: "16px" }}>Advanced</h3>
188
+ <p style={{ fontSize: "12px", opacity: 0.7, marginBottom: "16px" }}>
189
+ Fine-tune GitPilot's agent behavior and safety settings.
190
+ </p>
191
+
192
+ {error && (
193
+ <div
194
+ role="alert"
195
+ style={{
196
+ background: "#7f1d1d",
197
+ color: "#fecaca",
198
+ border: "1px solid #991b1b",
199
+ borderRadius: "8px",
200
+ padding: "12px",
201
+ fontSize: "12px",
202
+ marginBottom: "16px",
203
+ }}
204
+ >
205
+ {error}
206
+ </div>
207
+ )}
208
+
209
+ {/* Lite Mode toggle */}
210
+ <div
211
+ style={{
212
+ background: "#1a1b26",
213
+ borderRadius: "8px",
214
+ padding: "16px",
215
+ border: "1px solid #2a2b36",
216
+ marginBottom: "12px",
217
+ }}
218
+ >
219
+ <div
220
+ style={{
221
+ display: "flex",
222
+ justifyContent: "space-between",
223
+ alignItems: "flex-start",
224
+ gap: "16px",
225
+ }}
226
+ >
227
+ <div style={{ flex: 1 }}>
228
+ <h4 style={{ marginBottom: "4px", fontSize: "14px" }}>Lite Mode</h4>
229
+ <p style={{ fontSize: "12px", opacity: 0.7, lineHeight: 1.5 }}>
230
+ Use a simplified single-agent prompt instead of the multi-agent
231
+ CrewAI pipeline. Recommended for small local models
232
+ (qwen2.5:1.5b, deepseek-r1, phi3:mini) that struggle with the
233
+ ReAct format.
234
+ </p>
235
+ </div>
236
+ <ToggleSwitch
237
+ checked={liteMode}
238
+ onChange={handleLiteToggle}
239
+ disabled={updatingLite}
240
+ ariaLabel="Toggle Lite Mode"
241
+ />
242
+ </div>
243
+ </div>
244
+
245
+ {/* Permission Mode selector */}
246
+ <div
247
+ style={{
248
+ background: "#1a1b26",
249
+ borderRadius: "8px",
250
+ padding: "16px",
251
+ border: "1px solid #2a2b36",
252
+ marginBottom: "12px",
253
+ }}
254
+ >
255
+ <h4 style={{ marginBottom: "4px", fontSize: "14px" }}>Permission Mode</h4>
256
+ <p style={{ fontSize: "12px", opacity: 0.7, marginBottom: "12px" }}>
257
+ Controls when the agent needs your approval before writing files or
258
+ running commands.
259
+ </p>
260
+
261
+ <div style={{ display: "grid", gap: "8px" }}>
262
+ {PERMISSION_MODES.map((mode) => {
263
+ const selected = permissionMode === mode.value;
264
+ return (
265
+ <label
266
+ key={mode.value}
267
+ style={{
268
+ display: "flex",
269
+ alignItems: "flex-start",
270
+ gap: "10px",
271
+ padding: "10px 12px",
272
+ background: selected ? "#1e3a5f" : "#0d0e15",
273
+ border: selected ? "1px solid #3B82F6" : "1px solid #2a2b36",
274
+ borderRadius: "6px",
275
+ cursor: updatingPerm ? "not-allowed" : "pointer",
276
+ opacity: updatingPerm && !selected ? 0.5 : 1,
277
+ }}
278
+ >
279
+ <input
280
+ type="radio"
281
+ name="permission-mode"
282
+ value={mode.value}
283
+ checked={selected}
284
+ onChange={() => handlePermissionChange(mode.value)}
285
+ disabled={updatingPerm}
286
+ style={{ marginTop: "2px", cursor: "inherit" }}
287
+ />
288
+ <div>
289
+ <div
290
+ style={{
291
+ fontSize: "13px",
292
+ fontWeight: 600,
293
+ color: selected ? "#93c5fd" : "#fff",
294
+ }}
295
+ >
296
+ {mode.label}
297
+ </div>
298
+ <div
299
+ style={{
300
+ fontSize: "11px",
301
+ opacity: 0.7,
302
+ marginTop: "2px",
303
+ }}
304
+ >
305
+ {mode.description}
306
+ </div>
307
+ </div>
308
+ </label>
309
+ );
310
+ })}
311
+ </div>
312
+ </div>
313
+
314
+ {/* Link to full settings modal */}
315
+ <div
316
+ style={{
317
+ background: "#1a1b26",
318
+ borderRadius: "8px",
319
+ padding: "16px",
320
+ border: "1px solid #2a2b36",
321
+ }}
322
+ >
323
+ <div
324
+ style={{
325
+ display: "flex",
326
+ justifyContent: "space-between",
327
+ alignItems: "center",
328
+ gap: "16px",
329
+ }}
330
+ >
331
+ <div>
332
+ <h4 style={{ marginBottom: "4px", fontSize: "14px" }}>
333
+ Full Settings
334
+ </h4>
335
+ <p style={{ fontSize: "12px", opacity: 0.7 }}>
336
+ Server URL, telemetry, debug logs, environment variables, and more.
337
+ </p>
338
+ </div>
339
+ <button
340
+ type="button"
341
+ onClick={onOpenFullSettings}
342
+ style={{
343
+ padding: "8px 16px",
344
+ background: "transparent",
345
+ color: "#93c5fd",
346
+ border: "1px solid #3B82F6",
347
+ borderRadius: "4px",
348
+ cursor: "pointer",
349
+ fontSize: "12px",
350
+ fontWeight: 600,
351
+ whiteSpace: "nowrap",
352
+ }}
353
+ >
354
+ Open Settings Modal
355
+ </button>
356
+ </div>
357
+ </div>
358
+ </div>
359
+ );
360
+ }
frontend/components/AdminTabs/IntegrationsTab.jsx ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/IntegrationsTab.jsx
2
+ import React, { useEffect, useState } from "react";
3
+ import { apiUrl, safeFetchJSON } from "../../utils/api.js";
4
+
5
+ /**
6
+ * Integrations tab — shows connection status for GitHub (and future
7
+ * third-party integrations) with Connect/Disconnect actions.
8
+ *
9
+ * Best practices applied:
10
+ * - Fetch current status on mount via /api/auth/status
11
+ * - Show connected user info if already authenticated
12
+ * - "Connect GitHub" button opens /api/auth/url in the same window
13
+ * (OAuth flow will redirect back with ?code=...)
14
+ * - Disconnect clears localStorage token and re-fetches status
15
+ * - Handles both Web OAuth and Device Flow modes
16
+ */
17
+
18
+ export default function IntegrationsTab({ userInfo, onDisconnect, showToast }) {
19
+ const [authStatus, setAuthStatus] = useState(null);
20
+ const [loading, setLoading] = useState(true);
21
+ const [connecting, setConnecting] = useState(false);
22
+ const [error, setError] = useState(null);
23
+
24
+ useEffect(() => {
25
+ let cancelled = false;
26
+ (async () => {
27
+ try {
28
+ const data = await safeFetchJSON(apiUrl("/api/auth/status"), { timeout: 5000 });
29
+ if (!cancelled) setAuthStatus(data);
30
+ } catch (err) {
31
+ if (!cancelled) setError(err?.message || "Failed to check auth status");
32
+ } finally {
33
+ if (!cancelled) setLoading(false);
34
+ }
35
+ })();
36
+ return () => {
37
+ cancelled = true;
38
+ };
39
+ }, []);
40
+
41
+ const handleConnect = () => {
42
+ // Link GitHub without leaving the account: the in-workspace connect flow
43
+ // runs the GitHub device flow (or web OAuth if a secret is configured) and
44
+ // returns here. Works the same whether or not an account is already signed
45
+ // in. See App.jsx (?connect=github) and AuthPage connectMode.
46
+ setConnecting(true);
47
+ setError(null);
48
+ window.location.href = "/auth?connect=github&view=github";
49
+ };
50
+
51
+ const handleDisconnect = () => {
52
+ if (!window.confirm("Disconnect GitHub? You will be signed out.")) return;
53
+ localStorage.removeItem("github_token");
54
+ localStorage.removeItem("github_user");
55
+ onDisconnect?.();
56
+ showToast?.("Disconnected", "GitHub token removed.");
57
+ };
58
+
59
+ const isConnected = !!(userInfo && userInfo.login);
60
+
61
+ return (
62
+ <div>
63
+ <h3 style={{ marginBottom: "16px" }}>Integrations</h3>
64
+ <p style={{ fontSize: "12px", opacity: 0.7, marginBottom: "16px" }}>
65
+ Connect third-party services to unlock additional GitPilot features.
66
+ </p>
67
+
68
+ {/* GitHub integration card */}
69
+ <div
70
+ style={{
71
+ background: "#1a1b26",
72
+ borderRadius: "8px",
73
+ padding: "20px",
74
+ border: "1px solid #2a2b36",
75
+ marginBottom: "16px",
76
+ }}
77
+ >
78
+ <div
79
+ style={{
80
+ display: "flex",
81
+ justifyContent: "space-between",
82
+ alignItems: "flex-start",
83
+ marginBottom: "12px",
84
+ }}
85
+ >
86
+ <div>
87
+ <h4 style={{ marginBottom: "4px" }}>GitHub</h4>
88
+ <p style={{ fontSize: "12px", opacity: 0.7 }}>
89
+ Pull requests, issues, and remote repository workflows.
90
+ </p>
91
+ </div>
92
+ <span
93
+ style={{
94
+ padding: "2px 10px",
95
+ borderRadius: "10px",
96
+ fontSize: "11px",
97
+ fontWeight: 600,
98
+ background: isConnected ? "#064e3b" : "#374151",
99
+ color: isConnected ? "#a7f3d0" : "#9ca3af",
100
+ border: `1px solid ${isConnected ? "#065f46" : "#4b5563"}`,
101
+ }}
102
+ >
103
+ {loading ? "CHECKING..." : isConnected ? "CONNECTED" : "NOT CONNECTED"}
104
+ </span>
105
+ </div>
106
+
107
+ {isConnected && userInfo && (
108
+ <div
109
+ style={{
110
+ display: "flex",
111
+ alignItems: "center",
112
+ gap: "12px",
113
+ padding: "12px",
114
+ background: "#0d0e15",
115
+ borderRadius: "6px",
116
+ marginBottom: "12px",
117
+ }}
118
+ >
119
+ {userInfo.avatar_url && (
120
+ <img
121
+ src={userInfo.avatar_url}
122
+ alt={userInfo.login}
123
+ style={{ width: "36px", height: "36px", borderRadius: "50%" }}
124
+ />
125
+ )}
126
+ <div>
127
+ <div style={{ fontSize: "13px", fontWeight: 600 }}>
128
+ {userInfo.name || userInfo.login}
129
+ </div>
130
+ <div style={{ fontSize: "11px", opacity: 0.6 }}>@{userInfo.login}</div>
131
+ </div>
132
+ </div>
133
+ )}
134
+
135
+ {error && (
136
+ <div
137
+ role="alert"
138
+ style={{
139
+ padding: "8px 12px",
140
+ background: "#7f1d1d",
141
+ color: "#fecaca",
142
+ border: "1px solid #991b1b",
143
+ borderRadius: "4px",
144
+ fontSize: "11px",
145
+ marginBottom: "12px",
146
+ }}
147
+ >
148
+ {error}
149
+ </div>
150
+ )}
151
+
152
+ <div style={{ display: "flex", gap: "8px" }}>
153
+ {isConnected ? (
154
+ <button
155
+ type="button"
156
+ onClick={handleDisconnect}
157
+ style={{
158
+ padding: "8px 16px",
159
+ background: "transparent",
160
+ color: "#f87171",
161
+ border: "1px solid #991b1b",
162
+ borderRadius: "4px",
163
+ cursor: "pointer",
164
+ fontSize: "12px",
165
+ fontWeight: 600,
166
+ }}
167
+ >
168
+ Disconnect
169
+ </button>
170
+ ) : (
171
+ <button
172
+ type="button"
173
+ onClick={handleConnect}
174
+ disabled={connecting || loading}
175
+ style={{
176
+ padding: "8px 16px",
177
+ background: connecting ? "#555" : "#3B82F6",
178
+ color: "#fff",
179
+ border: "none",
180
+ borderRadius: "4px",
181
+ cursor: connecting || loading ? "not-allowed" : "pointer",
182
+ fontSize: "12px",
183
+ fontWeight: 600,
184
+ display: "inline-flex",
185
+ alignItems: "center",
186
+ gap: "6px",
187
+ }}
188
+ >
189
+ {connecting ? "Connecting..." : "Connect GitHub"}
190
+ </button>
191
+ )}
192
+ </div>
193
+
194
+ {authStatus && !isConnected && (
195
+ <div style={{ fontSize: "10px", opacity: 0.5, marginTop: "10px" }}>
196
+ Auth mode: {authStatus.mode || "unknown"}
197
+ {authStatus.oauth_configured && " (Web OAuth)"}
198
+ {authStatus.pat_configured && " (Personal Access Token)"}
199
+ </div>
200
+ )}
201
+ </div>
202
+
203
+ {/* Placeholder for future integrations */}
204
+ <div
205
+ style={{
206
+ background: "#1a1b26",
207
+ borderRadius: "8px",
208
+ padding: "20px",
209
+ border: "1px dashed #2a2b36",
210
+ opacity: 0.5,
211
+ textAlign: "center",
212
+ }}
213
+ >
214
+ <p style={{ fontSize: "12px", margin: 0 }}>
215
+ More integrations coming soon (GitLab, Bitbucket, Jira, Slack)
216
+ </p>
217
+ </div>
218
+ </div>
219
+ );
220
+ }
frontend/components/AdminTabs/MCPServersTab.jsx ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/MCPServersTab.jsx
2
+ //
3
+ // Settings tab for managing MCP Context Forge servers.
4
+ //
5
+ // UX layout (mirrors industry-standard plugin/extension managers):
6
+ //
7
+ // ┌─ Header ─ gateway pill, totals, global "MCP enabled" toggle ─┐
8
+ // ├─ Sub-tabs: Installed · Catalog · Custom · Gateway ──────────┤
9
+ // ├─ ServerCard list (Installed) │
10
+ // │ ▸ status / description / tags / tool count │
11
+ // │ ▸ Test · Configure · Disable · Uninstall │
12
+ // │ ▸ Expandable per-tool list with risk badges + toggles │
13
+ // └──────────────────────────────────────────────────────────────┘
14
+
15
+ import React, { useCallback, useEffect, useMemo, useState } from "react";
16
+ import { apiUrl, safeFetchJSON } from "../../utils/api.js";
17
+
18
+ import ServerCard from "./mcp/ServerCard.jsx";
19
+ import CatalogList from "./mcp/CatalogList.jsx";
20
+ import CustomInstallForm from "./mcp/CustomInstallForm.jsx";
21
+ import GatewayHeader from "./mcp/GatewayHeader.jsx";
22
+ import GatewayForm from "./mcp/GatewayForm.jsx";
23
+ import SyncReport from "./mcp/SyncReport.jsx";
24
+
25
+ const TAB_INSTALLED = "installed";
26
+ const TAB_CATALOG = "catalog";
27
+ const TAB_CUSTOM = "custom";
28
+ const TAB_GATEWAY = "gateway";
29
+
30
+ export default function MCPServersTab({ showToast }) {
31
+ const [activeSubTab, setActiveSubTab] = useState(TAB_INSTALLED);
32
+ const [status, setStatus] = useState(null);
33
+ const [servers, setServers] = useState([]);
34
+ const [catalog, setCatalog] = useState([]);
35
+ const [loading, setLoading] = useState(true);
36
+ const [error, setError] = useState(null);
37
+ const [syncing, setSyncing] = useState(false);
38
+ const [syncReport, setSyncReport] = useState(null);
39
+
40
+ const refresh = useCallback(async () => {
41
+ setLoading(true);
42
+ setError(null);
43
+ try {
44
+ const [statusData, serversData, catalogData] = await Promise.all([
45
+ safeFetchJSON(apiUrl("/api/mcp/status"), { timeout: 5000 }),
46
+ safeFetchJSON(apiUrl("/api/mcp/servers"), { timeout: 5000 }),
47
+ safeFetchJSON(apiUrl("/api/mcp/catalog"), { timeout: 5000 }),
48
+ ]);
49
+ setStatus(statusData);
50
+ setServers(serversData?.servers || []);
51
+ setCatalog(catalogData?.items || []);
52
+ } catch (err) {
53
+ setError(err?.message || "Failed to load MCP server state");
54
+ } finally {
55
+ setLoading(false);
56
+ }
57
+ }, []);
58
+
59
+ useEffect(() => {
60
+ refresh();
61
+ }, [refresh]);
62
+
63
+ const post = useCallback(
64
+ async (path, body) => {
65
+ try {
66
+ const res = await fetch(apiUrl(path), {
67
+ method: "POST",
68
+ headers: { "Content-Type": "application/json" },
69
+ body: body ? JSON.stringify(body) : undefined,
70
+ });
71
+ if (!res.ok) {
72
+ const detail = await res.json().catch(() => ({}));
73
+ throw new Error(detail?.detail || `HTTP ${res.status}`);
74
+ }
75
+ return await res.json();
76
+ } catch (err) {
77
+ showToast?.("MCP error", err?.message || String(err));
78
+ throw err;
79
+ }
80
+ },
81
+ [showToast]
82
+ );
83
+
84
+ // ---- Server actions -----------------------------------------------------
85
+ const onEnableServer = async (id) => {
86
+ await post(`/api/mcp/servers/${id}/enable`);
87
+ showToast?.("Server enabled", id);
88
+ await refresh();
89
+ };
90
+ const onDisableServer = async (id) => {
91
+ await post(`/api/mcp/servers/${id}/disable`);
92
+ showToast?.("Server disabled", id);
93
+ await refresh();
94
+ };
95
+ const onUninstallServer = async (id) => {
96
+ if (
97
+ !window.confirm(
98
+ `Uninstall ${id}? GitPilot will stop calling its tools immediately.`
99
+ )
100
+ )
101
+ return;
102
+ await post(`/api/mcp/servers/${id}/uninstall`);
103
+ showToast?.("Server uninstalled", id);
104
+ await refresh();
105
+ };
106
+ const onTestServer = async (id) => {
107
+ const result = await post(`/api/mcp/servers/${id}/test`);
108
+ if (result?.ok) {
109
+ showToast?.("Server healthy", id);
110
+ } else {
111
+ showToast?.(
112
+ "Server unreachable",
113
+ result?.reason || result?.error || "Unknown error"
114
+ );
115
+ }
116
+ return result;
117
+ };
118
+ const onSync = useCallback(async () => {
119
+ setSyncing(true);
120
+ setSyncReport(null);
121
+ try {
122
+ const report = await post("/api/mcp/sync", {});
123
+ setSyncReport(report);
124
+ const total =
125
+ (report.added?.length || 0) +
126
+ (report.kept?.length || 0) +
127
+ (report.orphaned?.length || 0);
128
+ showToast?.(
129
+ report.forge_unreachable ? "Sync failed" : "Sync complete",
130
+ report.forge_unreachable
131
+ ? report.error || "forge unreachable"
132
+ : `+${report.added?.length || 0} added · ${total} total`
133
+ );
134
+ await refresh();
135
+ } catch {
136
+ // post() already toasted; nothing more to do.
137
+ } finally {
138
+ setSyncing(false);
139
+ }
140
+ }, [post, refresh, showToast]);
141
+
142
+ const onForgetOrphan = async (id) => {
143
+ if (
144
+ !window.confirm(
145
+ `Forget ${id}? It will be removed from the local list.\n` +
146
+ "Re-attach it to MCP Context Forge then click Sync to bring it back."
147
+ )
148
+ )
149
+ return;
150
+ await post(`/api/mcp/servers/${id}/forget`);
151
+ showToast?.("Server forgotten", id);
152
+ await refresh();
153
+ };
154
+
155
+ const onToggleTool = async (serverId, toolName, enabled) => {
156
+ await post(
157
+ `/api/mcp/servers/${serverId}/tools/${encodeURIComponent(
158
+ toolName
159
+ )}/toggle`,
160
+ { enabled }
161
+ );
162
+ await refresh();
163
+ };
164
+
165
+ const onInstallFromCatalog = async (serverId) => {
166
+ await post("/api/mcp/servers/install", { server_id: serverId });
167
+ showToast?.("Installed", `${serverId} (disabled until you enable it)`);
168
+ await refresh();
169
+ setActiveSubTab(TAB_INSTALLED);
170
+ };
171
+
172
+ const onInstallCustom = async (registerJson) => {
173
+ await post("/api/mcp/servers/install-custom", {
174
+ register_json: registerJson,
175
+ });
176
+ showToast?.("Custom server added", registerJson.name);
177
+ await refresh();
178
+ setActiveSubTab(TAB_INSTALLED);
179
+ };
180
+
181
+ // ---- Derived totals -----------------------------------------------------
182
+ const installedCount = servers.filter((s) => s.installed).length;
183
+ const enabledCount = servers.filter((s) => s.installed && s.enabled).length;
184
+ const totalTools = useMemo(
185
+ () => servers.reduce((acc, s) => acc + (s.tool_count || 0), 0),
186
+ [servers]
187
+ );
188
+
189
+ return (
190
+ <div>
191
+ <GatewayHeader
192
+ status={status}
193
+ installedCount={installedCount}
194
+ enabledCount={enabledCount}
195
+ totalTools={totalTools}
196
+ onRefresh={refresh}
197
+ onSync={onSync}
198
+ syncing={syncing}
199
+ />
200
+
201
+ {syncReport && (
202
+ <SyncReport
203
+ report={syncReport}
204
+ onDismiss={() => setSyncReport(null)}
205
+ />
206
+ )}
207
+
208
+ {/* Sub-tab strip */}
209
+ <div
210
+ role="tablist"
211
+ style={{
212
+ display: "flex",
213
+ gap: "4px",
214
+ marginBottom: "16px",
215
+ borderBottom: "1px solid #2a2b36",
216
+ }}
217
+ >
218
+ {[
219
+ { id: TAB_INSTALLED, label: `Installed (${installedCount})` },
220
+ { id: TAB_CATALOG, label: `Catalog (${catalog.length})` },
221
+ { id: TAB_CUSTOM, label: "Custom" },
222
+ { id: TAB_GATEWAY, label: "Gateway" },
223
+ ].map((t) => (
224
+ <button
225
+ key={t.id}
226
+ role="tab"
227
+ aria-selected={activeSubTab === t.id}
228
+ onClick={() => setActiveSubTab(t.id)}
229
+ style={{
230
+ padding: "10px 16px",
231
+ border: "none",
232
+ background: "transparent",
233
+ color: activeSubTab === t.id ? "#93c5fd" : "#a0a0b0",
234
+ borderBottom:
235
+ activeSubTab === t.id
236
+ ? "2px solid #3B82F6"
237
+ : "2px solid transparent",
238
+ cursor: "pointer",
239
+ fontSize: "13px",
240
+ fontWeight: activeSubTab === t.id ? 600 : 400,
241
+ }}
242
+ >
243
+ {t.label}
244
+ </button>
245
+ ))}
246
+ </div>
247
+
248
+ {error && (
249
+ <div
250
+ role="alert"
251
+ style={{
252
+ padding: "12px",
253
+ background: "#5c1a1a",
254
+ border: "1px solid #8a2a2a",
255
+ borderRadius: "6px",
256
+ marginBottom: "16px",
257
+ color: "#fecaca",
258
+ fontSize: "13px",
259
+ }}
260
+ >
261
+ {error}
262
+ </div>
263
+ )}
264
+
265
+ {loading && !servers.length && (
266
+ <p style={{ color: "#a0a0b0", fontSize: "13px" }}>Loading…</p>
267
+ )}
268
+
269
+ {activeSubTab === TAB_INSTALLED && !loading && (
270
+ <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
271
+ {servers.length === 0 && (
272
+ <EmptyState
273
+ title="No MCP servers installed"
274
+ hint="Browse the catalog or paste a register.json under Custom."
275
+ actionLabel="Browse catalog"
276
+ onAction={() => setActiveSubTab(TAB_CATALOG)}
277
+ />
278
+ )}
279
+ {servers.map((s) => (
280
+ <ServerCard
281
+ key={s.id}
282
+ server={s}
283
+ onEnable={() => onEnableServer(s.id)}
284
+ onDisable={() => onDisableServer(s.id)}
285
+ onUninstall={() => onUninstallServer(s.id)}
286
+ onTest={() => onTestServer(s.id)}
287
+ onForget={s.orphan ? () => onForgetOrphan(s.id) : undefined}
288
+ onToggleTool={(tool, enabled) =>
289
+ onToggleTool(s.id, tool, enabled)
290
+ }
291
+ />
292
+ ))}
293
+ </div>
294
+ )}
295
+
296
+ {activeSubTab === TAB_CATALOG && !loading && (
297
+ <CatalogList items={catalog} onInstall={onInstallFromCatalog} />
298
+ )}
299
+
300
+ {activeSubTab === TAB_CUSTOM && (
301
+ <CustomInstallForm onSubmit={onInstallCustom} />
302
+ )}
303
+
304
+ {activeSubTab === TAB_GATEWAY && (
305
+ <GatewayForm
306
+ showToast={showToast}
307
+ // A new gateway means a different registry: reload so the Installed
308
+ // list describes the gateway you just pointed at, not the old one.
309
+ onSaved={refresh}
310
+ />
311
+ )}
312
+ </div>
313
+ );
314
+ }
315
+
316
+ function EmptyState({ title, hint, actionLabel, onAction }) {
317
+ return (
318
+ <div
319
+ style={{
320
+ padding: "32px",
321
+ background: "#1a1b26",
322
+ border: "1px dashed #2a2b36",
323
+ borderRadius: "8px",
324
+ textAlign: "center",
325
+ }}
326
+ >
327
+ <h4 style={{ margin: "0 0 8px 0", color: "#e0e0e7" }}>{title}</h4>
328
+ <p style={{ margin: "0 0 16px 0", color: "#a0a0b0", fontSize: "13px" }}>
329
+ {hint}
330
+ </p>
331
+ {actionLabel && (
332
+ <button
333
+ onClick={onAction}
334
+ style={{
335
+ padding: "8px 16px",
336
+ background: "#3B82F6",
337
+ color: "#fff",
338
+ border: "none",
339
+ borderRadius: "6px",
340
+ cursor: "pointer",
341
+ fontSize: "13px",
342
+ }}
343
+ >
344
+ {actionLabel}
345
+ </button>
346
+ )}
347
+ </div>
348
+ );
349
+ }
frontend/components/AdminTabs/MatrixLabInstallModal.jsx ADDED
@@ -0,0 +1,1013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/MatrixLabInstallModal.jsx
2
+ import React, { useCallback, useEffect, useState } from "react";
3
+ import { apiUrl } from "../../utils/api.js";
4
+
5
+ /**
6
+ * MatrixLab install modal — the "addon store" experience.
7
+ *
8
+ * Drives a single state machine off /api/matrixlab/* so the user sees
9
+ * one coherent state at a time (not "Unreachable" + "Running" + raw
10
+ * stack-trace at once). Default view exposes a single primary button;
11
+ * Runner URL / token / image / network / timeout live behind an
12
+ * Advanced disclosure.
13
+ *
14
+ * Status names mirror the backend MatrixLabStatus enum:
15
+ * not_installed | installing | starting | stopping | checking |
16
+ * ready | needs_attention | failed
17
+ */
18
+
19
+ // Progress checklists vary by which lifecycle the operator launched.
20
+ // The active "current step" key is set on the busy state so the
21
+ // checklist tracks the user's chosen journey, not a generic install.
22
+ const PROGRESS_STEPS = {
23
+ install: [
24
+ { key: "system", label: "Checking system" },
25
+ { key: "install", label: "Downloading MatrixLab" },
26
+ { key: "start", label: "Starting runner" },
27
+ { key: "test", label: "Testing connection" },
28
+ { key: "activate", label: "Activating MatrixLab" },
29
+ ],
30
+ repair: [
31
+ { key: "system", label: "Checking runner URL" },
32
+ { key: "repair", label: "Restarting runner" },
33
+ { key: "test", label: "Testing connection" },
34
+ { key: "activate", label: "Activating MatrixLab" },
35
+ ],
36
+ reinstall: [
37
+ { key: "system", label: "Stopping current runner" },
38
+ { key: "remove", label: "Removing old addon" },
39
+ { key: "install", label: "Downloading fresh version" },
40
+ { key: "start", label: "Starting runner" },
41
+ { key: "test", label: "Testing connection" },
42
+ { key: "activate", label: "Activating MatrixLab" },
43
+ ],
44
+ };
45
+
46
+ // Primary action label and the journey it triggers, keyed by the
47
+ // addon's normalised status. Mapping is exhaustive so the modal
48
+ // always has a clear "next thing to do" button.
49
+ const PRIMARY_BY_STATUS = {
50
+ not_installed: { label: "Install and Start", action: "install" },
51
+ installing: { label: "Installing…", action: null },
52
+ starting: { label: "Starting…", action: null },
53
+ stopping: { label: "Stopping…", action: null },
54
+ checking: { label: "Checking…", action: null },
55
+ needs_attention: { label: "Repair connection", action: "repair" },
56
+ failed: { label: "Retry installation", action: "install" },
57
+ ready: { label: "Done", action: "done" },
58
+ };
59
+
60
+ function statusPill(status) {
61
+ const map = {
62
+ not_installed: { label: "Not installed", bg: "#374151", fg: "#d1d5db" },
63
+ installing: { label: "Installing", bg: "#0d3320", fg: "#86efac" },
64
+ starting: { label: "Starting", bg: "#0d3320", fg: "#86efac" },
65
+ stopping: { label: "Stopping", bg: "#3d2d11", fg: "#fde68a" },
66
+ checking: { label: "Checking", bg: "#0d3320", fg: "#86efac" },
67
+ ready: { label: "Ready", bg: "#0d3320", fg: "#86efac" },
68
+ needs_attention: { label: "Needs attention", bg: "#3d2d11", fg: "#fde68a" },
69
+ failed: { label: "Failed", bg: "#3d1111", fg: "#fca5a5" },
70
+ };
71
+ return map[status] || map.not_installed;
72
+ }
73
+
74
+ export default function MatrixLabInstallModal({ onClose, onActivated }) {
75
+ const [status, setStatus] = useState(null); // MatrixLabStatus from backend
76
+ const [busy, setBusy] = useState(false);
77
+ // Which journey is currently in flight ("install" | "repair" |
78
+ // "reinstall") — drives the progress checklist's stage list.
79
+ const [journey, setJourney] = useState(null);
80
+ const [progressStep, setProgressStep] = useState(null);
81
+ const [showAdvanced, setShowAdvanced] = useState(false);
82
+ const [showDetails, setShowDetails] = useState(false);
83
+ const [logs, setLogs] = useState(null);
84
+ const [showLogs, setShowLogs] = useState(false);
85
+ // Reinstall confirmation prompt + the destructive "wipe images" opt-in.
86
+ const [reinstallConfirm, setReinstallConfirm] = useState(false);
87
+ const [reinstallWipe, setReinstallWipe] = useState(false);
88
+
89
+ // Mirror of /api/sandbox/status for the Advanced panel.
90
+ const [advanced, setAdvanced] = useState(null);
91
+ const [tokenInput, setTokenInput] = useState("");
92
+
93
+ const refresh = useCallback(async () => {
94
+ try {
95
+ const r = await fetch(apiUrl("/api/matrixlab/status"));
96
+ const data = await r.json();
97
+ setStatus(data);
98
+ } catch (err) {
99
+ setStatus({
100
+ status: "failed",
101
+ message: "GitPilot backend could not return a MatrixLab status.",
102
+ errorCode: "BACKEND_UNREACHABLE",
103
+ technicalDetails: { rawError: err?.message || String(err) },
104
+ });
105
+ }
106
+ }, []);
107
+
108
+ const refreshAdvanced = useCallback(async () => {
109
+ try {
110
+ const r = await fetch(apiUrl("/api/sandbox/status"));
111
+ const data = await r.json();
112
+ setAdvanced(data);
113
+ } catch (err) {
114
+ // Non-fatal — Advanced just stays empty.
115
+ }
116
+ }, []);
117
+
118
+ useEffect(() => {
119
+ refresh();
120
+ refreshAdvanced();
121
+ }, [refresh, refreshAdvanced]);
122
+
123
+ // Run a sequence of phased POSTs against /api/matrixlab/* and walk
124
+ // the progress checklist as each one returns. Used for install,
125
+ // repair, and reinstall — they differ only in which endpoint kicks
126
+ // off the journey.
127
+ const runJourney = useCallback(async (journeyKey, kickoffPath, kickoffBody) => {
128
+ setBusy(true);
129
+ setJourney(journeyKey);
130
+ setShowDetails(false);
131
+ try {
132
+ // Phase 1: kickoff (install / repair / reinstall). Each backend
133
+ // endpoint is itself idempotent and aggregates several docker
134
+ // commands; the modal walks the checklist on the way.
135
+ setProgressStep(journeyKey === "reinstall" ? "system" : journeyKey);
136
+ let r = await fetch(apiUrl(kickoffPath), {
137
+ method: "POST",
138
+ headers: kickoffBody ? { "Content-Type": "application/json" } : undefined,
139
+ body: kickoffBody ? JSON.stringify(kickoffBody) : undefined,
140
+ });
141
+ let data = await r.json();
142
+ setStatus(data);
143
+ if (data.status === "failed") return;
144
+
145
+ // Phase 2: explicit connection test so we never claim "ready"
146
+ // without a green health probe.
147
+ setProgressStep("test");
148
+ r = await fetch(apiUrl("/api/matrixlab/test"), { method: "POST" });
149
+ data = await r.json();
150
+ setStatus(data);
151
+ if (data.status !== "ready") return;
152
+
153
+ // Phase 3: activate (always safe to call when ready).
154
+ setProgressStep("activate");
155
+ r = await fetch(apiUrl("/api/matrixlab/activate"), { method: "POST" });
156
+ data = await r.json();
157
+ setStatus(data);
158
+ if (data.status === "ready" && data.activeSandbox === "matrixlab") {
159
+ onActivated?.(data);
160
+ }
161
+ } catch (err) {
162
+ setStatus({
163
+ status: "failed",
164
+ message: `MatrixLab ${journeyKey} could not complete.`,
165
+ errorCode: "NETWORK_ERROR",
166
+ technicalDetails: { rawError: err?.message || String(err) },
167
+ });
168
+ } finally {
169
+ setBusy(false);
170
+ setProgressStep(null);
171
+ setJourney(null);
172
+ refreshAdvanced();
173
+ }
174
+ }, [onActivated, refreshAdvanced]);
175
+
176
+ const runInstall = useCallback(() => runJourney("install", "/api/matrixlab/install"), [runJourney]);
177
+ const runRepair = useCallback(() => runJourney("repair", "/api/matrixlab/repair"), [runJourney]);
178
+ const runReinstall = useCallback((removeData) => runJourney(
179
+ "reinstall", "/api/matrixlab/reinstall", { remove_data: !!removeData },
180
+ ), [runJourney]);
181
+ // Cheap recovery: persist the discovered URL without restarting the
182
+ // runner. Most "needs_attention" cases are stale URLs from the
183
+ // :8000 → :8765 port move, and this resolves them in <1s.
184
+ const runUrlAutoDetect = useCallback(
185
+ () => runJourney("repair", "/api/matrixlab/url/auto-detect"),
186
+ [runJourney],
187
+ );
188
+
189
+ const openLogs = useCallback(async () => {
190
+ setShowLogs(true);
191
+ try {
192
+ const r = await fetch(apiUrl("/api/matrixlab/logs?tail=200"));
193
+ const data = await r.json();
194
+ setLogs(data);
195
+ } catch (err) {
196
+ setLogs({ ok: false, error: err?.message || String(err), lines: [] });
197
+ }
198
+ }, []);
199
+
200
+ const onPrimary = () => {
201
+ if (!status) return;
202
+ const next = (PRIMARY_BY_STATUS[status.status] || PRIMARY_BY_STATUS.not_installed).action;
203
+ if (!next) return; // in-flight states have no primary action
204
+ if (next === "done") return onClose?.();
205
+ if (next === "install") return runInstall();
206
+ if (next === "repair") return runRepair();
207
+ };
208
+
209
+ const updateAdvanced = async (patch) => {
210
+ try {
211
+ const r = await fetch(apiUrl("/api/sandbox/config"), {
212
+ method: "PUT",
213
+ headers: { "Content-Type": "application/json" },
214
+ body: JSON.stringify(patch),
215
+ });
216
+ const data = await r.json();
217
+ if (r.ok) {
218
+ setAdvanced((prev) => ({ ...(prev || {}), ...data }));
219
+ if ("matrixlab_token" in patch) setTokenInput("");
220
+ // Re-probe the addon status — URL / token changes may make us
221
+ // reachable again.
222
+ refresh();
223
+ }
224
+ } catch (err) {
225
+ // surfaced through the next refresh
226
+ }
227
+ };
228
+
229
+ if (!status) {
230
+ return (
231
+ <Backdrop onClose={onClose}>
232
+ <ModalShell title="Install MatrixLab Addon" subtitle="Loading…" onClose={onClose}>
233
+ <div style={{ padding: 40, textAlign: "center", opacity: 0.6 }}>
234
+ Checking MatrixLab status…
235
+ </div>
236
+ </ModalShell>
237
+ </Backdrop>
238
+ );
239
+ }
240
+
241
+ const pill = statusPill(status.status);
242
+
243
+ return (
244
+ <Backdrop onClose={onClose}>
245
+ <ModalShell
246
+ title="Install MatrixLab Addon"
247
+ subtitle="Run code safely in isolated, temporary containers."
248
+ onClose={onClose}
249
+ >
250
+ {/* Status row */}
251
+ <div style={{
252
+ display: "flex", alignItems: "center", gap: 10,
253
+ padding: "12px 14px", background: "#0e0f24",
254
+ border: "1px solid #2c2d46", borderRadius: 6, marginBottom: 14,
255
+ }}>
256
+ <span style={{
257
+ display: "inline-flex", alignItems: "center", gap: 6,
258
+ fontSize: 11, fontWeight: 600, padding: "2px 10px", borderRadius: 12,
259
+ background: pill.bg, color: pill.fg,
260
+ }}>
261
+ <span style={{ width: 6, height: 6, borderRadius: "50%", background: pill.fg }} />
262
+ {pill.label}
263
+ </span>
264
+ <div style={{ flex: 1 }}>
265
+ <div style={{ fontSize: 13, color: "#e6e8ff" }}>{status.message}</div>
266
+ {status.runnerUrl && status.status !== "ready" && (
267
+ <div style={{ fontSize: 11, color: "#9092b5", marginTop: 2 }}>
268
+ Runner URL: <code style={{ color: "#c3c5dd" }}>{status.runnerUrl}</code>
269
+ </div>
270
+ )}
271
+ {/* Stale-URL recovery: backend probes candidate ports
272
+ when the configured URL is down. When a live one is
273
+ found we offer a one-click switch — this fixes the
274
+ very common "MatrixLab is installed but GitPilot
275
+ cannot connect" after the :8000 → :8765 port move. */}
276
+ {status.discoveredUrl && status.discoveredUrl !== status.runnerUrl && (
277
+ <div style={{
278
+ marginTop: 6, padding: "6px 10px", fontSize: 12,
279
+ background: "#0d3320", color: "#86efac",
280
+ border: "1px solid #166534", borderRadius: 4,
281
+ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap",
282
+ }}>
283
+ <span>
284
+ Found a live runner at{" "}
285
+ <code style={{ background: "#000", padding: "1px 4px", borderRadius: 3 }}>
286
+ {status.discoveredUrl}
287
+ </code>
288
+ </span>
289
+ <button
290
+ type="button"
291
+ onClick={runUrlAutoDetect}
292
+ disabled={busy}
293
+ style={{
294
+ padding: "3px 10px", fontSize: 11, fontWeight: 600,
295
+ background: "#10B981", color: "#052e1c",
296
+ border: "0", borderRadius: 4, cursor: "pointer",
297
+ }}
298
+ >
299
+ Use this URL
300
+ </button>
301
+ </div>
302
+ )}
303
+ </div>
304
+ </div>
305
+
306
+ {/* Inline body — copy depends on state */}
307
+ {status.status === "not_installed" && (
308
+ <p style={{ fontSize: 13, opacity: 0.8, lineHeight: 1.55, marginBottom: 16 }}>
309
+ MatrixLab gives GitPilot an isolated sandbox for running code,
310
+ testing snippets, and executing agent actions safely. It will be
311
+ downloaded, started, and connected automatically.
312
+ </p>
313
+ )}
314
+
315
+ {(busy || progressStep) && (
316
+ <ProgressChecklist journey={journey} current={progressStep} />
317
+ )}
318
+
319
+ {status.status === "ready" && (
320
+ <Checklist
321
+ items={[
322
+ ["Installed", true],
323
+ ["Running", true],
324
+ ["Connection verified", true],
325
+ ["Set as active sandbox", status.activeSandbox === "matrixlab"],
326
+ ]}
327
+ />
328
+ )}
329
+
330
+ {/* Lifecycle disabled hint — friendly copy, admin detail under disclosure */}
331
+ {status.errorCode === "LIFECYCLE_DISABLED" && (
332
+ <div style={{
333
+ background: "#2a210d", border: "1px solid #854d0e",
334
+ borderRadius: 6, padding: 10, fontSize: 12,
335
+ color: "#fde68a", marginBottom: 12,
336
+ }}>
337
+ MatrixLab lifecycle automation is disabled. This GitPilot backend
338
+ was started with{" "}
339
+ <code style={{ background: "#1a1b26", padding: "1px 4px", borderRadius: 3 }}>
340
+ GITPILOT_ENABLE_MATRIXLAB_LIFECYCLE=0
341
+ </code>{" "}
342
+ — restart it without that variable (the default is enabled), or
343
+ use Manual setup under Advanced options.
344
+ </div>
345
+ )}
346
+
347
+ {/* Technical details disclosure — only visible when there's an error */}
348
+ {status.technicalDetails && (status.status === "needs_attention" || status.status === "failed") && (
349
+ <details
350
+ open={showDetails}
351
+ onToggle={(e) => setShowDetails(e.target.open)}
352
+ style={{ marginBottom: 12 }}
353
+ >
354
+ <summary style={{ cursor: "pointer", fontSize: 12, color: "#9092b5" }}>
355
+ Technical details
356
+ </summary>
357
+ <pre style={{
358
+ marginTop: 8, padding: 10, background: "#000",
359
+ border: "1px solid #2c2d46", borderRadius: 4,
360
+ fontSize: 11, color: "#fca5a5",
361
+ fontFamily: "ui-monospace, monospace",
362
+ whiteSpace: "pre-wrap", overflow: "auto", maxHeight: 200,
363
+ }}>
364
+ {status.technicalDetails.expected &&
365
+ `Expected: ${status.technicalDetails.expected}\n`}
366
+ {status.technicalDetails.actual &&
367
+ `Actual: ${status.technicalDetails.actual}\n`}
368
+ {status.technicalDetails.rawError &&
369
+ `\n${status.technicalDetails.rawError}`}
370
+ </pre>
371
+ </details>
372
+ )}
373
+
374
+ {/* Action buttons — state-aware. Reinstall is offered as a
375
+ normal recovery action (not buried in Advanced) once the
376
+ addon exists in some form; Open logs surfaces only when
377
+ there's something to diagnose. */}
378
+ {(() => {
379
+ const primary = PRIMARY_BY_STATUS[status.status] || PRIMARY_BY_STATUS.not_installed;
380
+ const canReinstall = status.installed === true ||
381
+ ["needs_attention", "failed", "ready"].includes(status.status);
382
+ const canSeeLogs = ["needs_attention", "failed"].includes(status.status);
383
+ return (
384
+ <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
385
+ <button
386
+ type="button"
387
+ onClick={onPrimary}
388
+ disabled={busy || primary.action === null}
389
+ style={{
390
+ padding: "10px 20px", fontSize: 13, fontWeight: 600,
391
+ background: busy ? "#1e3a5f" : "#3B82F6",
392
+ color: "#fff", border: "none", borderRadius: 6,
393
+ cursor: busy ? "wait" : "pointer",
394
+ minWidth: 180,
395
+ }}
396
+ >
397
+ {primary.label}
398
+ </button>
399
+
400
+ {canReinstall && (
401
+ <button
402
+ type="button"
403
+ onClick={() => setReinstallConfirm(true)}
404
+ disabled={busy}
405
+ style={status.status === "ready" ? btnDanger : btnSecondary}
406
+ title="Stop, remove, and pull a fresh copy of MatrixLab"
407
+ >
408
+ Reinstall addon
409
+ </button>
410
+ )}
411
+
412
+ {canSeeLogs && (
413
+ <button type="button" onClick={openLogs} disabled={busy} style={btnSecondary}>
414
+ Open logs
415
+ </button>
416
+ )}
417
+
418
+ {status.status === "ready" && (
419
+ <button type="button" onClick={runRepair} disabled={busy} style={btnSecondary}>
420
+ Run test snippet
421
+ </button>
422
+ )}
423
+ </div>
424
+ );
425
+ })()}
426
+
427
+ {/* Logs viewer */}
428
+ {showLogs && (
429
+ <div style={{ marginTop: 14 }}>
430
+ <div style={{
431
+ display: "flex", justifyContent: "space-between",
432
+ alignItems: "baseline", marginBottom: 6,
433
+ }}>
434
+ <div style={{ fontSize: 12, fontWeight: 600, color: "#c3c5dd" }}>
435
+ MatrixLab logs
436
+ {logs?.container && (
437
+ <span style={{
438
+ marginLeft: 8, fontSize: 11, color: "#9092b5",
439
+ fontFamily: "ui-monospace, monospace", fontWeight: 400,
440
+ }}>
441
+ · {logs.container}
442
+ </span>
443
+ )}
444
+ </div>
445
+ <button
446
+ type="button"
447
+ onClick={openLogs}
448
+ disabled={busy}
449
+ style={{
450
+ fontSize: 11, padding: "2px 8px",
451
+ background: "transparent", color: "#9092b5",
452
+ border: "1px solid #2c2d46", borderRadius: 4, cursor: "pointer",
453
+ }}
454
+ >
455
+ ↻ Refresh
456
+ </button>
457
+ </div>
458
+
459
+ {/* Friendly error + hint when the backend can't read logs.
460
+ We show the hint as an actionable next step (run
461
+ "make install-matrixlab") and list any matrixlab-
462
+ shaped containers we found so the user can see whether
463
+ the runner is up under a different name. */}
464
+ {logs?.ok === false && (
465
+ <div style={{
466
+ marginBottom: 6, padding: 10,
467
+ background: "#2a210d", border: "1px solid #854d0e",
468
+ borderRadius: 4, fontSize: 12, color: "#fde68a",
469
+ }}>
470
+ <div style={{ fontWeight: 600 }}>{logs.error || "Could not read MatrixLab logs."}</div>
471
+ {logs.hint && (
472
+ <div style={{ marginTop: 4, fontSize: 11, color: "#fcd34d" }}>
473
+ Next step:{" "}
474
+ <code style={{
475
+ background: "#000", padding: "1px 6px",
476
+ borderRadius: 3, color: "#86efac",
477
+ }}>
478
+ {logs.hint}
479
+ </code>
480
+ </div>
481
+ )}
482
+ {Array.isArray(logs.candidates) && logs.candidates.length > 0 && (
483
+ <div style={{ marginTop: 6, fontSize: 11 }}>
484
+ Found other matrixlab-shaped containers:
485
+ <ul style={{ margin: "4px 0 0", paddingLeft: 18 }}>
486
+ {logs.candidates.map((c, i) => (
487
+ <li key={i}>
488
+ <code style={{ color: "#c3c5dd" }}>{c}</code>
489
+ </li>
490
+ ))}
491
+ </ul>
492
+ <div style={{ marginTop: 4, fontSize: 10, color: "#a1a1aa" }}>
493
+ Set <code>GITPILOT_MATRIXLAB_CONTAINER</code> to use one of these,
494
+ or run Reinstall to recreate the expected container.
495
+ </div>
496
+ </div>
497
+ )}
498
+ {logs.rawError && (
499
+ <details style={{ marginTop: 6 }}>
500
+ <summary style={{ cursor: "pointer", fontSize: 11, color: "#fbbf24" }}>
501
+ docker stderr
502
+ </summary>
503
+ <pre style={{
504
+ marginTop: 4, padding: 6, fontSize: 10,
505
+ background: "#000", color: "#fca5a5",
506
+ borderRadius: 4, whiteSpace: "pre-wrap",
507
+ }}>
508
+ {logs.rawError}
509
+ </pre>
510
+ </details>
511
+ )}
512
+ </div>
513
+ )}
514
+
515
+ <pre style={{
516
+ margin: 0, padding: 10, background: "#000",
517
+ border: "1px solid #2c2d46", borderRadius: 4,
518
+ fontSize: 11, color: "#D4D4D8",
519
+ fontFamily: "ui-monospace, monospace",
520
+ maxHeight: 220, overflow: "auto", whiteSpace: "pre-wrap",
521
+ }}>
522
+ {logs == null
523
+ ? "Loading logs…"
524
+ : (logs.lines && logs.lines.length > 0)
525
+ ? logs.lines.join("\n")
526
+ : (logs.ok === false ? "(no log output captured)" : "Loading logs…")}
527
+ </pre>
528
+ </div>
529
+ )}
530
+
531
+ {/* Advanced options — collapsed by default so first-time
532
+ users see the install/repair flow, not a wall of knobs.
533
+ Operators who need runner URL / token / image / network /
534
+ timeout / manual setup / local clone install / unsafe
535
+ modes click the disclosure to expand. */}
536
+ <details
537
+ open={showAdvanced}
538
+ onToggle={(e) => setShowAdvanced(e.target.open)}
539
+ style={{ marginTop: 14 }}
540
+ >
541
+ <summary style={{
542
+ cursor: "pointer", fontSize: 12, color: "#9092b5",
543
+ padding: "6px 0", listStyle: "none",
544
+ }}>
545
+ Advanced options
546
+ </summary>
547
+ <AdvancedOptions
548
+ advanced={advanced}
549
+ tokenInput={tokenInput}
550
+ setTokenInput={setTokenInput}
551
+ onUpdate={updateAdvanced}
552
+ disabled={busy}
553
+ onLocalStatus={(data) => {
554
+ setStatus(data);
555
+ refreshAdvanced();
556
+ }}
557
+ />
558
+ </details>
559
+
560
+ {reinstallConfirm && (
561
+ <ReinstallConfirm
562
+ wipe={reinstallWipe}
563
+ setWipe={setReinstallWipe}
564
+ onCancel={() => {
565
+ setReinstallConfirm(false);
566
+ setReinstallWipe(false);
567
+ }}
568
+ onConfirm={() => {
569
+ const wipe = reinstallWipe;
570
+ setReinstallConfirm(false);
571
+ setReinstallWipe(false);
572
+ runReinstall(wipe);
573
+ }}
574
+ />
575
+ )}
576
+ </ModalShell>
577
+ </Backdrop>
578
+ );
579
+ }
580
+
581
+ function ReinstallConfirm({ wipe, setWipe, onCancel, onConfirm }) {
582
+ // Modal-in-modal stacked at zIndex 110 (Backdrop is 100). Apes
583
+ // GitHub's "Are you absolutely sure?" pattern: explicit destructive
584
+ // checkbox stays off by default so a misclick can't wipe images.
585
+ return (
586
+ <div onClick={onCancel} style={{
587
+ position: "fixed", inset: 0, background: "rgba(0,0,0,0.65)",
588
+ display: "flex", alignItems: "center", justifyContent: "center",
589
+ zIndex: 110,
590
+ }}>
591
+ <div onClick={(e) => e.stopPropagation()} style={{
592
+ width: "min(440px, 92vw)", background: "#1a1b26",
593
+ border: "1px solid #2a2b36", borderRadius: 10, padding: 20,
594
+ color: "#e6e8ff",
595
+ }}>
596
+ <h4 style={{ margin: "0 0 6px", fontSize: 15 }}>Reinstall MatrixLab Addon?</h4>
597
+ <p style={{ fontSize: 13, opacity: 0.8, lineHeight: 1.55, marginBottom: 14 }}>
598
+ This will stop MatrixLab, remove the current addon container, download a
599
+ fresh copy, start it again, and reconnect GitPilot. Your GitPilot
600
+ settings will be kept.
601
+ </p>
602
+ <label style={{
603
+ display: "flex", gap: 8, alignItems: "flex-start",
604
+ padding: "8px 10px", borderRadius: 6, marginBottom: 14,
605
+ border: "1px solid #2c2d46", background: "#0e0f24",
606
+ fontSize: 12, cursor: "pointer",
607
+ }}>
608
+ <input
609
+ type="checkbox"
610
+ checked={wipe}
611
+ onChange={(e) => setWipe(e.target.checked)}
612
+ style={{ marginTop: 2 }}
613
+ />
614
+ <span>
615
+ <strong style={{ color: "#fde68a" }}>Also remove local MatrixLab data</strong>
616
+ <span style={{ display: "block", color: "#9092b5", marginTop: 2 }}>
617
+ Deletes the cached MatrixLab runner image. Sandbox images and
618
+ workspace data are preserved.
619
+ </span>
620
+ </span>
621
+ </label>
622
+ <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
623
+ <button type="button" onClick={onCancel} style={btnSecondary}>Cancel</button>
624
+ <button type="button" onClick={onConfirm} style={wipe ? btnDanger : btnPrimary}>
625
+ {wipe ? "Reinstall and remove data" : "Reinstall MatrixLab"}
626
+ </button>
627
+ </div>
628
+ </div>
629
+ </div>
630
+ );
631
+ }
632
+
633
+ function ProgressChecklist({ journey, current }) {
634
+ // Pick the right stage list for the journey in flight; default to
635
+ // the install list (the most informative one) when no journey is
636
+ // active yet. Once ``current`` advances past the kickoff key, the
637
+ // visited rows render with a ✓.
638
+ const steps = PROGRESS_STEPS[journey] || PROGRESS_STEPS.install;
639
+ const phaseIndex = current ? Math.max(0, steps.findIndex(s => s.key === current)) : 0;
640
+ return (
641
+ <div style={{ marginBottom: 14 }}>
642
+ {steps.map((s, i) => {
643
+ const done = i < phaseIndex;
644
+ const active = i === phaseIndex;
645
+ return (
646
+ <div key={s.key} style={{
647
+ display: "flex", alignItems: "center", gap: 8,
648
+ fontSize: 12, padding: "3px 0",
649
+ color: done ? "#86efac" : active ? "#e6e8ff" : "#9092b5",
650
+ }}>
651
+ <span style={{ width: 16, textAlign: "center" }}>
652
+ {done ? "✓" : active ? "⏳" : "○"}
653
+ </span>
654
+ {s.label}
655
+ </div>
656
+ );
657
+ })}
658
+ </div>
659
+ );
660
+ }
661
+
662
+ function Checklist({ items }) {
663
+ return (
664
+ <div style={{ marginBottom: 14 }}>
665
+ {items.map(([label, ok]) => (
666
+ <div key={label} style={{
667
+ display: "flex", alignItems: "center", gap: 8,
668
+ fontSize: 12, padding: "3px 0",
669
+ color: ok ? "#86efac" : "#9092b5",
670
+ }}>
671
+ <span style={{ width: 16, textAlign: "center" }}>{ok ? "✓" : "○"}</span>
672
+ {label}
673
+ </div>
674
+ ))}
675
+ </div>
676
+ );
677
+ }
678
+
679
+ function LocalCloneSection({ disabled, onStatus }) {
680
+ const [native, setNative] = useState(null);
681
+ const [busy, setBusy] = useState(null); // "install" | "start" | "stop"
682
+
683
+ const refresh = useCallback(async () => {
684
+ try {
685
+ const r = await fetch(apiUrl("/api/matrixlab/native/status"));
686
+ setNative(await r.json());
687
+ } catch (err) {
688
+ // non-fatal — leave section empty
689
+ }
690
+ }, []);
691
+
692
+ useEffect(() => {
693
+ refresh();
694
+ }, [refresh]);
695
+
696
+ const runAction = useCallback(async (action) => {
697
+ setBusy(action);
698
+ try {
699
+ const path = {
700
+ install: "/api/matrixlab/install_local",
701
+ start: "/api/matrixlab/start_local",
702
+ stop: "/api/matrixlab/stop_local",
703
+ }[action];
704
+ const r = await fetch(apiUrl(path), { method: "POST" });
705
+ const data = await r.json();
706
+ onStatus?.(data);
707
+ } finally {
708
+ setBusy(null);
709
+ refresh();
710
+ }
711
+ }, [onStatus, refresh]);
712
+
713
+ if (!native) return null;
714
+
715
+ return (
716
+ <details style={{ marginTop: 12 }}>
717
+ <summary style={{ cursor: "pointer", fontSize: 11, color: "#9092b5" }}>
718
+ Local clone install (no Docker for the runner itself)
719
+ </summary>
720
+ <div style={{ marginTop: 8, fontSize: 11, color: "#9092b5", lineHeight: 1.6 }}>
721
+ Clones MatrixLab into <code style={{ color: "#c3c5dd" }}>{native.local_dir}</code>,
722
+ creates a dedicated Python virtualenv, and runs <code style={{ color: "#c3c5dd" }}>uvicorn app.main:app</code>
723
+ from the runner directory. The Runner still spawns per-language sandboxes
724
+ via Docker, so the host needs <code style={{ color: "#c3c5dd" }}>docker</code>{" "}
725
+ on PATH for code execution.
726
+ </div>
727
+ <div style={{ marginTop: 10, display: "flex", flexWrap: "wrap", gap: 8 }}>
728
+ <span style={{
729
+ display: "inline-flex", alignItems: "center", gap: 6,
730
+ fontSize: 11, padding: "2px 10px", borderRadius: 10,
731
+ background: native.running ? "#0d3320" : native.installed ? "#3d2d11" : "#374151",
732
+ color: native.running ? "#86efac" : native.installed ? "#fde68a" : "#d1d5db",
733
+ }}>
734
+ <span style={{
735
+ width: 6, height: 6, borderRadius: "50%",
736
+ background: native.running ? "#10B981" : native.installed ? "#f59e0b" : "#9ca3af",
737
+ }} />
738
+ {native.running ? "Running (PID " + native.pid + ")"
739
+ : native.installed ? "Installed · stopped"
740
+ : "Not installed"}
741
+ </span>
742
+ {!native.installed && (
743
+ <button
744
+ type="button"
745
+ disabled={disabled || busy != null || !native.lifecycleEnabled}
746
+ onClick={() => runAction("install")}
747
+ style={btnPrimarySmall}
748
+ >
749
+ {busy === "install" ? "Cloning + installing…" : "Clone and install"}
750
+ </button>
751
+ )}
752
+ {native.installed && !native.running && (
753
+ <button
754
+ type="button"
755
+ disabled={disabled || busy != null || !native.lifecycleEnabled}
756
+ onClick={() => runAction("start")}
757
+ style={btnPrimarySmall}
758
+ >
759
+ {busy === "start" ? "Starting…" : "Start runner"}
760
+ </button>
761
+ )}
762
+ {native.running && (
763
+ <button
764
+ type="button"
765
+ disabled={disabled || busy != null || !native.lifecycleEnabled}
766
+ onClick={() => runAction("stop")}
767
+ style={btnSecondarySmall}
768
+ >
769
+ {busy === "stop" ? "Stopping…" : "Stop runner"}
770
+ </button>
771
+ )}
772
+ <button
773
+ type="button"
774
+ disabled={busy != null}
775
+ onClick={refresh}
776
+ style={btnSecondarySmall}
777
+ >
778
+ Refresh
779
+ </button>
780
+ </div>
781
+ {!native.lifecycleEnabled && (
782
+ <div style={{
783
+ marginTop: 8, padding: "6px 8px",
784
+ background: "#2a210d", border: "1px solid #854d0e",
785
+ borderRadius: 4, fontSize: 11, color: "#fde68a",
786
+ }}>
787
+ Local clone install needs lifecycle automation enabled on the GitPilot
788
+ backend.
789
+ </div>
790
+ )}
791
+ </details>
792
+ );
793
+ }
794
+
795
+ function AdvancedOptions({ advanced, tokenInput, setTokenInput, onUpdate, disabled, onLocalStatus }) {
796
+ if (!advanced) return null;
797
+ return (
798
+ <div style={{
799
+ marginTop: 14, padding: 12,
800
+ background: "#0e0f24", border: "1px solid #2c2d46",
801
+ borderRadius: 6,
802
+ }}>
803
+ <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 10, color: "#c3c5dd" }}>
804
+ Advanced options
805
+ </div>
806
+ <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 8, alignItems: "center" }}>
807
+ <label style={fieldLabel}>Runner URL</label>
808
+ <input
809
+ type="text"
810
+ defaultValue={advanced.matrixlab_url || ""}
811
+ onBlur={(e) => onUpdate({ matrixlab_url: e.target.value })}
812
+ placeholder="http://localhost:8765"
813
+ disabled={disabled}
814
+ style={fieldInput}
815
+ />
816
+
817
+ <label style={fieldLabel}>Bearer token</label>
818
+ <div style={{ display: "flex", gap: 6 }}>
819
+ <input
820
+ type="password"
821
+ value={tokenInput}
822
+ onChange={(e) => setTokenInput(e.target.value)}
823
+ placeholder={advanced.has_token ? "•••••••• (saved)" : "Optional"}
824
+ disabled={disabled}
825
+ style={{ ...fieldInput, flex: 1 }}
826
+ />
827
+ <button
828
+ type="button"
829
+ onClick={() => onUpdate({ matrixlab_token: tokenInput })}
830
+ disabled={disabled}
831
+ style={btnSecondary}
832
+ >
833
+ Save token
834
+ </button>
835
+ </div>
836
+
837
+ <label style={fieldLabel}>Default image</label>
838
+ <input
839
+ type="text"
840
+ defaultValue={advanced.matrixlab_image || ""}
841
+ onBlur={(e) => onUpdate({ matrixlab_image: e.target.value })}
842
+ placeholder="matrixlab-python"
843
+ disabled={disabled}
844
+ style={fieldInput}
845
+ />
846
+
847
+ <label style={fieldLabel}>Network access</label>
848
+ <label style={{ display: "flex", gap: 6, alignItems: "center", fontSize: 12, color: "#c3c5dd" }}>
849
+ <input
850
+ type="checkbox"
851
+ checked={!!advanced.allow_network}
852
+ disabled={disabled}
853
+ onChange={(e) => onUpdate({ allow_network: e.target.checked })}
854
+ />
855
+ Allow network egress
856
+ </label>
857
+
858
+ <label style={fieldLabel}>Timeout</label>
859
+ <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
860
+ <input
861
+ type="number"
862
+ min={1}
863
+ max={600}
864
+ defaultValue={advanced.timeout_sec || 120}
865
+ onBlur={(e) => onUpdate({ timeout_sec: Number(e.target.value) || 120 })}
866
+ disabled={disabled}
867
+ style={{ ...fieldInput, width: 80 }}
868
+ />
869
+ <span style={{ fontSize: 11, color: "#9092b5" }}>seconds</span>
870
+ </div>
871
+ </div>
872
+
873
+ <LocalCloneSection disabled={disabled} onStatus={onLocalStatus} />
874
+
875
+ <details style={{ marginTop: 12 }}>
876
+ <summary style={{ cursor: "pointer", fontSize: 11, color: "#9092b5" }}>
877
+ Manual setup
878
+ </summary>
879
+ <pre style={{
880
+ margin: "8px 0 0", padding: 10, background: "#000",
881
+ border: "1px solid #2c2d46", borderRadius: 4,
882
+ fontSize: 11, color: "#D4D4D8",
883
+ fontFamily: "ui-monospace, monospace",
884
+ }}>{`# In a MatrixLab checkout:
885
+ docker compose up -d
886
+
887
+ # Or directly:
888
+ docker run -d --name gitpilot-matrixlab \\
889
+ -p 8000:8000 \\
890
+ -v /var/run/docker.sock:/var/run/docker.sock \\
891
+ ruslanmv/matrixlab-runner:latest`}</pre>
892
+ </details>
893
+
894
+ <details style={{ marginTop: 12 }}>
895
+ <summary style={{ cursor: "pointer", fontSize: 11, color: "#9092b5" }}>
896
+ Developer options · Unsafe modes
897
+ </summary>
898
+ <div style={{ marginTop: 8, fontSize: 11, color: "#fca5a5" }}>
899
+ Pass-through runs code directly on the host without isolation. Use
900
+ only for local development.
901
+ </div>
902
+ </details>
903
+ </div>
904
+ );
905
+ }
906
+
907
+ function Backdrop({ children, onClose }) {
908
+ return (
909
+ <div
910
+ onClick={onClose}
911
+ style={{
912
+ position: "fixed", inset: 0,
913
+ background: "rgba(0,0,0,0.6)",
914
+ display: "flex", alignItems: "center", justifyContent: "center",
915
+ zIndex: 100,
916
+ }}
917
+ >
918
+ <div onClick={(e) => e.stopPropagation()}>{children}</div>
919
+ </div>
920
+ );
921
+ }
922
+
923
+ function ModalShell({ title, subtitle, onClose, children }) {
924
+ return (
925
+ <div style={{
926
+ width: "min(640px, 92vw)",
927
+ maxHeight: "90vh", overflow: "auto",
928
+ background: "#1a1b26",
929
+ border: "1px solid #2a2b36",
930
+ borderRadius: 10,
931
+ padding: 20,
932
+ color: "#e6e8ff",
933
+ }}>
934
+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 }}>
935
+ <h3 style={{ margin: 0, fontSize: 18 }}>{title}</h3>
936
+ <button
937
+ type="button"
938
+ onClick={onClose}
939
+ style={{
940
+ background: "transparent", border: "none",
941
+ color: "#9092b5", cursor: "pointer", fontSize: 18,
942
+ }}
943
+ aria-label="Close"
944
+ >
945
+ ✕
946
+ </button>
947
+ </div>
948
+ <div style={{ fontSize: 12, color: "#9092b5", marginBottom: 16 }}>{subtitle}</div>
949
+ {children}
950
+ </div>
951
+ );
952
+ }
953
+
954
+ const btnSecondary = {
955
+ padding: "8px 14px",
956
+ fontSize: 12,
957
+ background: "transparent",
958
+ color: "#c3c5dd",
959
+ border: "1px solid #2c2d46",
960
+ borderRadius: 6,
961
+ cursor: "pointer",
962
+ };
963
+
964
+ const btnPrimary = {
965
+ padding: "8px 14px",
966
+ fontSize: 12,
967
+ fontWeight: 600,
968
+ background: "#3B82F6",
969
+ color: "#fff",
970
+ border: "none",
971
+ borderRadius: 6,
972
+ cursor: "pointer",
973
+ };
974
+
975
+ // "Reinstall and remove data" is destructive — surface it with a
976
+ // danger tone so the operator pauses before clicking.
977
+ const btnDanger = {
978
+ padding: "8px 14px",
979
+ fontSize: 12,
980
+ fontWeight: 600,
981
+ background: "#7f1d1d",
982
+ color: "#fecaca",
983
+ border: "1px solid #991b1b",
984
+ borderRadius: 6,
985
+ cursor: "pointer",
986
+ };
987
+
988
+ const btnGhost = {
989
+ padding: "8px 14px",
990
+ fontSize: 12,
991
+ background: "transparent",
992
+ color: "#9092b5",
993
+ border: "none",
994
+ cursor: "pointer",
995
+ };
996
+
997
+ const fieldLabel = { fontSize: 12, color: "#c3c5dd" };
998
+ const fieldInput = {
999
+ fontSize: 12, padding: "4px 6px",
1000
+ background: "#14152a", color: "#e6e8ff",
1001
+ border: "1px solid #2c2d46", borderRadius: 4,
1002
+ };
1003
+
1004
+ const btnPrimarySmall = {
1005
+ padding: "4px 10px", fontSize: 11, fontWeight: 600,
1006
+ background: "#3B82F6", color: "#fff",
1007
+ border: "none", borderRadius: 4, cursor: "pointer",
1008
+ };
1009
+ const btnSecondarySmall = {
1010
+ padding: "4px 10px", fontSize: 11,
1011
+ background: "transparent", color: "#c3c5dd",
1012
+ border: "1px solid #2c2d46", borderRadius: 4, cursor: "pointer",
1013
+ };
frontend/components/AdminTabs/SandboxTab.jsx ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/SandboxTab.jsx
2
+ import React, { useCallback, useEffect, useState } from "react";
3
+ import { apiUrl } from "../../utils/api.js";
4
+ import MatrixLabInstallModal from "./MatrixLabInstallModal.jsx";
5
+
6
+ /**
7
+ * Sandbox tab — enterprise default view.
8
+ *
9
+ * Surfaces a single MatrixLab addon card plus a clean Local-sandbox
10
+ * card. Implementation knobs (Runner URL, token, image, network,
11
+ * timeout, pass-through, lifecycle env flag) live behind the install
12
+ * modal's Advanced disclosure — the primary view never shows them.
13
+ *
14
+ * Status pill is driven off /api/matrixlab/status so we never end up
15
+ * with the "Unreachable + Running" contradiction the legacy panel
16
+ * produced.
17
+ */
18
+
19
+ function StatusPill({ status }) {
20
+ const map = {
21
+ not_installed: { label: "Not installed", bg: "#374151", fg: "#d1d5db" },
22
+ installing: { label: "Installing", bg: "#0d3320", fg: "#86efac" },
23
+ starting: { label: "Starting", bg: "#0d3320", fg: "#86efac" },
24
+ stopping: { label: "Stopping", bg: "#3d2d11", fg: "#fde68a" },
25
+ checking: { label: "Checking", bg: "#0d3320", fg: "#86efac" },
26
+ ready: { label: "Ready", bg: "#0d3320", fg: "#86efac" },
27
+ needs_attention: { label: "Needs attention", bg: "#3d2d11", fg: "#fde68a" },
28
+ failed: { label: "Failed", bg: "#3d1111", fg: "#fca5a5" },
29
+ };
30
+ const pill = map[status] || map.not_installed;
31
+ return (
32
+ <span style={{
33
+ display: "inline-flex", alignItems: "center", gap: 6,
34
+ fontSize: 11, fontWeight: 600, padding: "2px 10px", borderRadius: 12,
35
+ background: pill.bg, color: pill.fg,
36
+ }}>
37
+ <span style={{ width: 6, height: 6, borderRadius: "50%", background: pill.fg }} />
38
+ {pill.label}
39
+ </span>
40
+ );
41
+ }
42
+
43
+ export default function SandboxTab({ showToast }) {
44
+ const [matrixlab, setMatrixlab] = useState(null); // /api/matrixlab/status payload
45
+ const [sandbox, setSandbox] = useState(null); // /api/sandbox/status payload
46
+ const [loading, setLoading] = useState(true);
47
+ const [modalOpen, setModalOpen] = useState(false);
48
+
49
+ const load = useCallback(async () => {
50
+ try {
51
+ const [ml, sb] = await Promise.all([
52
+ fetch(apiUrl("/api/matrixlab/status")).then((r) => r.json()).catch(() => null),
53
+ fetch(apiUrl("/api/sandbox/status")).then((r) => r.json()).catch(() => null),
54
+ ]);
55
+ setMatrixlab(ml);
56
+ setSandbox(sb);
57
+ } finally {
58
+ setLoading(false);
59
+ }
60
+ }, []);
61
+
62
+ useEffect(() => {
63
+ load();
64
+ }, [load]);
65
+
66
+ const useLocal = useCallback(async () => {
67
+ try {
68
+ const r = await fetch(apiUrl("/api/sandbox/config"), {
69
+ method: "PUT",
70
+ headers: { "Content-Type": "application/json" },
71
+ body: JSON.stringify({ backend: "subprocess" }),
72
+ });
73
+ const data = await r.json();
74
+ if (r.ok) {
75
+ setSandbox(data);
76
+ showToast?.("Switched to Local sandbox", "Code runs in a host subprocess with a workspace jail.");
77
+ }
78
+ } catch (err) {
79
+ // surfaced through the next load()
80
+ }
81
+ }, [showToast]);
82
+
83
+ if (loading) {
84
+ return (
85
+ <div>
86
+ <h3 style={{ marginBottom: 16 }}>Sandbox</h3>
87
+ <div style={{
88
+ background: "#1a1b26", borderRadius: 8,
89
+ padding: "40px 20px", textAlign: "center",
90
+ border: "1px solid #2a2b36", fontSize: 12, opacity: 0.6,
91
+ }}>
92
+ Loading sandbox status…
93
+ </div>
94
+ </div>
95
+ );
96
+ }
97
+
98
+ const activeBackend = (sandbox?.backend || "subprocess").toLowerCase();
99
+ const mlStatus = matrixlab?.status || "not_installed";
100
+
101
+ return (
102
+ <div>
103
+ <h3 style={{ marginBottom: 8 }}>Sandbox</h3>
104
+ <p style={{ fontSize: 12, opacity: 0.7, marginBottom: 20 }}>
105
+ Pick where GitPilot executes code: the local subprocess sandbox or
106
+ the MatrixLab Runner. The choice applies to the Run button on chat
107
+ code blocks and the agent's EXECUTE action.
108
+ </p>
109
+
110
+ {/* MatrixLab addon card */}
111
+ <div style={cardStyle}>
112
+ <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
113
+ <div style={{ flex: 1 }}>
114
+ <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
115
+ <h4 style={{ margin: 0, fontSize: 15 }}>MatrixLab Addon</h4>
116
+ <StatusPill status={mlStatus} />
117
+ {activeBackend === "matrixlab" && (
118
+ <span style={{
119
+ fontSize: 10, fontWeight: 600,
120
+ padding: "1px 6px", borderRadius: 8,
121
+ background: "#1e3a5f", color: "#93c5fd",
122
+ border: "1px solid #3B82F6",
123
+ }}>ACTIVE</span>
124
+ )}
125
+ </div>
126
+ <p style={{ fontSize: 12, opacity: 0.75, margin: 0, lineHeight: 1.55 }}>
127
+ Run code safely in isolated, temporary containers. Recommended
128
+ for enterprise deployments and untrusted code.
129
+ </p>
130
+ {mlStatus !== "not_installed" && matrixlab?.message && (
131
+ <p style={{ fontSize: 11, opacity: 0.6, marginTop: 6, marginBottom: 0 }}>
132
+ {matrixlab.message}
133
+ </p>
134
+ )}
135
+ </div>
136
+ <button
137
+ type="button"
138
+ onClick={() => setModalOpen(true)}
139
+ style={{
140
+ padding: "8px 16px", fontSize: 12, fontWeight: 600,
141
+ background: mlStatus === "ready" ? "transparent" : "#3B82F6",
142
+ color: mlStatus === "ready" ? "#93c5fd" : "#fff",
143
+ border: mlStatus === "ready" ? "1px solid #3B82F6" : "none",
144
+ borderRadius: 6, cursor: "pointer",
145
+ whiteSpace: "nowrap",
146
+ }}
147
+ >
148
+ {mlStatus === "ready" ? "Manage" :
149
+ mlStatus === "needs_attention" ? "Fix connection" :
150
+ mlStatus === "failed" ? "Retry install" :
151
+ "Install and Start"}
152
+ </button>
153
+ </div>
154
+ </div>
155
+
156
+ {/* Local sandbox card */}
157
+ <div style={cardStyle}>
158
+ <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
159
+ <div style={{ flex: 1 }}>
160
+ <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
161
+ <h4 style={{ margin: 0, fontSize: 15 }}>Local sandbox</h4>
162
+ {activeBackend === "subprocess" && (
163
+ <span style={{
164
+ fontSize: 10, fontWeight: 600,
165
+ padding: "1px 6px", borderRadius: 8,
166
+ background: "#1e3a5f", color: "#93c5fd",
167
+ border: "1px solid #3B82F6",
168
+ }}>ACTIVE</span>
169
+ )}
170
+ </div>
171
+ <p style={{ fontSize: 12, opacity: 0.75, margin: 0, lineHeight: 1.55 }}>
172
+ Host subprocess with a workspace jail. No Docker required —
173
+ best for trying simple snippets quickly.
174
+ </p>
175
+ </div>
176
+ <button
177
+ type="button"
178
+ onClick={useLocal}
179
+ disabled={activeBackend === "subprocess"}
180
+ style={{
181
+ padding: "8px 16px", fontSize: 12, fontWeight: 600,
182
+ background: activeBackend === "subprocess" ? "transparent" : "#374151",
183
+ color: activeBackend === "subprocess" ? "#9092b5" : "#fff",
184
+ border: activeBackend === "subprocess" ? "1px solid #2c2d46" : "none",
185
+ borderRadius: 6,
186
+ cursor: activeBackend === "subprocess" ? "default" : "pointer",
187
+ whiteSpace: "nowrap",
188
+ }}
189
+ >
190
+ {activeBackend === "subprocess" ? "Active" : "Use Local"}
191
+ </button>
192
+ </div>
193
+ </div>
194
+
195
+ {modalOpen && (
196
+ <MatrixLabInstallModal
197
+ onClose={() => {
198
+ setModalOpen(false);
199
+ load();
200
+ }}
201
+ onActivated={(data) => {
202
+ showToast?.("MatrixLab ready", "Code now runs in MatrixLab sandboxes.");
203
+ // Refresh both panels so the ACTIVE badge moves to the addon card.
204
+ load();
205
+ }}
206
+ />
207
+ )}
208
+ </div>
209
+ );
210
+ }
211
+
212
+ const cardStyle = {
213
+ background: "#1a1b26",
214
+ borderRadius: 8,
215
+ padding: 16,
216
+ border: "1px solid #2a2b36",
217
+ marginBottom: 12,
218
+ };
frontend/components/AdminTabs/SecurityTab.jsx ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/SecurityTab.jsx
2
+ import React, { useState } from "react";
3
+ import { scanWorkspace } from "../../utils/api.js";
4
+
5
+ /**
6
+ * Security tab — runs a workspace scan via /api/security/scan-workspace
7
+ * and renders findings grouped by severity.
8
+ *
9
+ * Best practices applied:
10
+ * - Custom path input (defaults to ".")
11
+ * - Loading spinner while scanning
12
+ * - Error state with retry
13
+ * - Empty state ("No findings") with green checkmark
14
+ * - Findings grouped by severity (critical → info)
15
+ * - Each finding shows file, line, CWE, recommendation
16
+ * - Color-coded severity badges
17
+ */
18
+
19
+ const SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
20
+
21
+ const SEVERITY_COLORS = {
22
+ critical: { bg: "#7f1d1d", text: "#fecaca", border: "#991b1b" },
23
+ high: { bg: "#9a3412", text: "#fed7aa", border: "#c2410c" },
24
+ medium: { bg: "#78350f", text: "#fde68a", border: "#a16207" },
25
+ low: { bg: "#164e63", text: "#a5f3fc", border: "#0e7490" },
26
+ info: { bg: "#1e3a5f", text: "#93c5fd", border: "#3B82F6" },
27
+ };
28
+
29
+ function SeverityBadge({ severity }) {
30
+ const c = SEVERITY_COLORS[severity] || SEVERITY_COLORS.info;
31
+ return (
32
+ <span
33
+ style={{
34
+ display: "inline-block",
35
+ padding: "2px 8px",
36
+ background: c.bg,
37
+ color: c.text,
38
+ border: `1px solid ${c.border}`,
39
+ borderRadius: "10px",
40
+ fontSize: "10px",
41
+ fontWeight: 700,
42
+ textTransform: "uppercase",
43
+ letterSpacing: "0.5px",
44
+ }}
45
+ >
46
+ {severity}
47
+ </span>
48
+ );
49
+ }
50
+
51
+ export default function SecurityTab({ showToast }) {
52
+ const [path, setPath] = useState(".");
53
+ const [scanning, setScanning] = useState(false);
54
+ const [result, setResult] = useState(null);
55
+ const [error, setError] = useState(null);
56
+
57
+ const handleScan = async () => {
58
+ setScanning(true);
59
+ setError(null);
60
+ setResult(null);
61
+ try {
62
+ const data = await scanWorkspace(path.trim() || ".");
63
+ setResult(data);
64
+ const findingsCount = data.findings?.length || 0;
65
+ showToast?.(
66
+ "Scan complete",
67
+ findingsCount === 0
68
+ ? "No security findings."
69
+ : `Found ${findingsCount} issue${findingsCount !== 1 ? "s" : ""}.`
70
+ );
71
+ } catch (err) {
72
+ setError(err?.message || "Scan failed");
73
+ } finally {
74
+ setScanning(false);
75
+ }
76
+ };
77
+
78
+ // Group findings by severity
79
+ const grouped = React.useMemo(() => {
80
+ const out = {};
81
+ if (result?.findings) {
82
+ for (const f of result.findings) {
83
+ const sev = f.severity || "info";
84
+ if (!out[sev]) out[sev] = [];
85
+ out[sev].push(f);
86
+ }
87
+ }
88
+ return out;
89
+ }, [result]);
90
+
91
+ const totalFindings = result?.findings?.length || 0;
92
+
93
+ return (
94
+ <div>
95
+ <h3 style={{ marginBottom: "16px" }}>Security Scanning</h3>
96
+ <p style={{ fontSize: "12px", opacity: 0.7, marginBottom: "16px" }}>
97
+ Scan your workspace for vulnerabilities, secrets, and insecure patterns (OWASP Top 10).
98
+ </p>
99
+
100
+ {/* Scan controls */}
101
+ <div
102
+ style={{
103
+ background: "#1a1b26",
104
+ borderRadius: "8px",
105
+ padding: "16px",
106
+ border: "1px solid #2a2b36",
107
+ marginBottom: "16px",
108
+ display: "flex",
109
+ gap: "8px",
110
+ alignItems: "flex-end",
111
+ }}
112
+ >
113
+ <div style={{ flex: 1 }}>
114
+ <label
115
+ htmlFor="security-scan-path"
116
+ style={{
117
+ fontSize: "11px",
118
+ opacity: 0.7,
119
+ display: "block",
120
+ marginBottom: "4px",
121
+ }}
122
+ >
123
+ Path to scan (relative or absolute)
124
+ </label>
125
+ <input
126
+ id="security-scan-path"
127
+ type="text"
128
+ value={path}
129
+ onChange={(e) => setPath(e.target.value)}
130
+ disabled={scanning}
131
+ placeholder="."
132
+ style={{
133
+ width: "100%",
134
+ padding: "8px 10px",
135
+ background: "#0d0e15",
136
+ border: "1px solid #2a2b36",
137
+ borderRadius: "4px",
138
+ color: "#fff",
139
+ fontSize: "12px",
140
+ fontFamily: "monospace",
141
+ }}
142
+ />
143
+ </div>
144
+ <button
145
+ type="button"
146
+ onClick={handleScan}
147
+ disabled={scanning}
148
+ style={{
149
+ padding: "8px 16px",
150
+ background: scanning ? "#555" : "#3B82F6",
151
+ color: "#fff",
152
+ border: "none",
153
+ borderRadius: "4px",
154
+ cursor: scanning ? "not-allowed" : "pointer",
155
+ fontSize: "12px",
156
+ fontWeight: 600,
157
+ whiteSpace: "nowrap",
158
+ }}
159
+ >
160
+ {scanning ? "Scanning..." : "Scan Workspace"}
161
+ </button>
162
+ </div>
163
+
164
+ {/* Error state */}
165
+ {error && (
166
+ <div
167
+ role="alert"
168
+ style={{
169
+ background: "#7f1d1d",
170
+ color: "#fecaca",
171
+ border: "1px solid #991b1b",
172
+ borderRadius: "8px",
173
+ padding: "12px",
174
+ fontSize: "12px",
175
+ marginBottom: "16px",
176
+ }}
177
+ >
178
+ <strong>Scan failed: </strong>
179
+ {error}
180
+ </div>
181
+ )}
182
+
183
+ {/* Results summary */}
184
+ {result && (
185
+ <div
186
+ style={{
187
+ background: "#1a1b26",
188
+ borderRadius: "8px",
189
+ padding: "16px",
190
+ border: "1px solid #2a2b36",
191
+ marginBottom: "16px",
192
+ }}
193
+ >
194
+ <div style={{ display: "flex", gap: "24px", fontSize: "12px" }}>
195
+ <div>
196
+ <div style={{ opacity: 0.6 }}>Files Scanned</div>
197
+ <div style={{ fontSize: "18px", fontWeight: 600 }}>
198
+ {result.files_scanned ?? 0}
199
+ </div>
200
+ </div>
201
+ <div>
202
+ <div style={{ opacity: 0.6 }}>Total Findings</div>
203
+ <div
204
+ style={{
205
+ fontSize: "18px",
206
+ fontWeight: 600,
207
+ color: totalFindings === 0 ? "#4ade80" : "#fcd34d",
208
+ }}
209
+ >
210
+ {totalFindings}
211
+ </div>
212
+ </div>
213
+ <div>
214
+ <div style={{ opacity: 0.6 }}>Duration</div>
215
+ <div style={{ fontSize: "18px", fontWeight: 600 }}>
216
+ {result.scan_duration_ms ?? 0}ms
217
+ </div>
218
+ </div>
219
+ </div>
220
+ </div>
221
+ )}
222
+
223
+ {/* Empty state — no findings */}
224
+ {result && totalFindings === 0 && (
225
+ <div
226
+ style={{
227
+ background: "#064e3b",
228
+ color: "#a7f3d0",
229
+ border: "1px solid #065f46",
230
+ borderRadius: "8px",
231
+ padding: "20px",
232
+ textAlign: "center",
233
+ }}
234
+ >
235
+ <div style={{ fontSize: "32px", marginBottom: "8px" }}>✓</div>
236
+ <div style={{ fontSize: "14px", fontWeight: 600 }}>
237
+ No security issues found
238
+ </div>
239
+ <div style={{ fontSize: "12px", opacity: 0.8, marginTop: "4px" }}>
240
+ Your workspace passed all {result.files_scanned ?? 0} file checks.
241
+ </div>
242
+ </div>
243
+ )}
244
+
245
+ {/* Findings grouped by severity */}
246
+ {totalFindings > 0 &&
247
+ SEVERITY_ORDER.filter((sev) => grouped[sev]?.length > 0).map((sev) => (
248
+ <div key={sev} style={{ marginBottom: "16px" }}>
249
+ <h4
250
+ style={{
251
+ fontSize: "13px",
252
+ marginBottom: "8px",
253
+ display: "flex",
254
+ alignItems: "center",
255
+ gap: "8px",
256
+ }}
257
+ >
258
+ <SeverityBadge severity={sev} />
259
+ <span>
260
+ {grouped[sev].length} {sev} issue{grouped[sev].length !== 1 ? "s" : ""}
261
+ </span>
262
+ </h4>
263
+ <div style={{ display: "grid", gap: "8px" }}>
264
+ {grouped[sev].map((f, idx) => (
265
+ <div
266
+ key={`${f.rule_id}-${f.file_path}-${f.line_number}-${idx}`}
267
+ style={{
268
+ background: "#1a1b26",
269
+ borderRadius: "8px",
270
+ padding: "12px",
271
+ border: `1px solid ${SEVERITY_COLORS[sev]?.border || "#2a2b36"}`,
272
+ }}
273
+ >
274
+ <div
275
+ style={{
276
+ display: "flex",
277
+ justifyContent: "space-between",
278
+ alignItems: "flex-start",
279
+ marginBottom: "6px",
280
+ }}
281
+ >
282
+ <div style={{ fontSize: "13px", fontWeight: 600 }}>{f.title}</div>
283
+ {f.cwe_id && (
284
+ <span
285
+ style={{
286
+ fontSize: "10px",
287
+ opacity: 0.6,
288
+ fontFamily: "monospace",
289
+ }}
290
+ >
291
+ {f.cwe_id}
292
+ </span>
293
+ )}
294
+ </div>
295
+ <div
296
+ style={{
297
+ fontSize: "11px",
298
+ fontFamily: "monospace",
299
+ opacity: 0.7,
300
+ marginBottom: "6px",
301
+ }}
302
+ >
303
+ {f.file_path}:{f.line_number}
304
+ </div>
305
+ {f.snippet && (
306
+ <pre
307
+ style={{
308
+ fontSize: "11px",
309
+ background: "#0d0e15",
310
+ padding: "8px",
311
+ borderRadius: "4px",
312
+ overflowX: "auto",
313
+ margin: "6px 0",
314
+ color: "#e0e7ff",
315
+ }}
316
+ >
317
+ {f.snippet}
318
+ </pre>
319
+ )}
320
+ {f.recommendation && (
321
+ <div
322
+ style={{
323
+ fontSize: "11px",
324
+ opacity: 0.8,
325
+ marginTop: "6px",
326
+ paddingTop: "6px",
327
+ borderTop: "1px solid #2a2b36",
328
+ }}
329
+ >
330
+ <strong>Fix: </strong>
331
+ {f.recommendation}
332
+ </div>
333
+ )}
334
+ </div>
335
+ ))}
336
+ </div>
337
+ </div>
338
+ ))}
339
+ </div>
340
+ );
341
+ }
frontend/components/AdminTabs/SessionsTab.jsx ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/SessionsTab.jsx
2
+ import React, { useEffect, useMemo, useState, useCallback } from "react";
3
+ import { apiUrl, safeFetchJSON } from "../../utils/api.js";
4
+
5
+ /**
6
+ * Sessions tab — admin-level table view of all saved sessions with
7
+ * search, sort, and delete actions.
8
+ *
9
+ * Best practices applied:
10
+ * - Fetch all sessions on mount
11
+ * - Client-side search (useMemo for filtered list)
12
+ * - Confirmation dialog before delete
13
+ * - Row hover effect
14
+ * - Empty / loading / error states
15
+ * - Relative timestamps ("2 hours ago")
16
+ * - Click row to open in workspace view
17
+ */
18
+
19
+ function formatRelativeTime(iso) {
20
+ if (!iso) return "—";
21
+ try {
22
+ const d = new Date(iso);
23
+ const diff = Date.now() - d.getTime();
24
+ if (diff < 60_000) return "just now";
25
+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
26
+ if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
27
+ if (diff < 2_592_000_000) return `${Math.floor(diff / 86_400_000)}d ago`;
28
+ return d.toLocaleDateString();
29
+ } catch {
30
+ return "—";
31
+ }
32
+ }
33
+
34
+ export default function SessionsTab({ onSelectSession, showToast }) {
35
+ const [sessions, setSessions] = useState([]);
36
+ const [loading, setLoading] = useState(true);
37
+ const [error, setError] = useState(null);
38
+ const [query, setQuery] = useState("");
39
+ const [deletingId, setDeletingId] = useState(null);
40
+
41
+ const fetchSessions = useCallback(async () => {
42
+ setError(null);
43
+ try {
44
+ const data = await safeFetchJSON(apiUrl("/api/sessions"), { timeout: 10000 });
45
+ setSessions(Array.isArray(data.sessions) ? data.sessions : []);
46
+ } catch (err) {
47
+ setError(err?.message || "Failed to load sessions");
48
+ } finally {
49
+ setLoading(false);
50
+ }
51
+ }, []);
52
+
53
+ useEffect(() => {
54
+ fetchSessions();
55
+ }, [fetchSessions]);
56
+
57
+ const handleDelete = async (session) => {
58
+ if (
59
+ !window.confirm(
60
+ `Delete session "${session.name || session.id?.slice(0, 8)}"? This cannot be undone.`
61
+ )
62
+ ) {
63
+ return;
64
+ }
65
+
66
+ setDeletingId(session.id);
67
+ try {
68
+ const res = await fetch(apiUrl(`/api/sessions/${session.id}`), {
69
+ method: "DELETE",
70
+ });
71
+ if (!res.ok) {
72
+ throw new Error(`Delete failed (${res.status})`);
73
+ }
74
+ showToast?.("Session deleted", session.name || session.id);
75
+ // Optimistic removal
76
+ setSessions((prev) => prev.filter((s) => s.id !== session.id));
77
+ } catch (err) {
78
+ setError(err?.message || "Failed to delete session");
79
+ } finally {
80
+ setDeletingId(null);
81
+ }
82
+ };
83
+
84
+ const filtered = useMemo(() => {
85
+ if (!query.trim()) return sessions;
86
+ const q = query.toLowerCase();
87
+ return sessions.filter((s) => {
88
+ return (
89
+ (s.name || "").toLowerCase().includes(q) ||
90
+ (s.repo || "").toLowerCase().includes(q) ||
91
+ (s.branch || "").toLowerCase().includes(q) ||
92
+ (s.id || "").toLowerCase().includes(q)
93
+ );
94
+ });
95
+ }, [sessions, query]);
96
+
97
+ return (
98
+ <div>
99
+ <div
100
+ style={{
101
+ display: "flex",
102
+ justifyContent: "space-between",
103
+ alignItems: "center",
104
+ marginBottom: "16px",
105
+ gap: "12px",
106
+ flexWrap: "wrap",
107
+ }}
108
+ >
109
+ <div>
110
+ <h3 style={{ marginBottom: "4px" }}>Sessions</h3>
111
+ <p style={{ fontSize: "12px", opacity: 0.7 }}>
112
+ All saved chat sessions ({sessions.length} total
113
+ {query ? `, ${filtered.length} matching` : ""}).
114
+ </p>
115
+ </div>
116
+ <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
117
+ <input
118
+ type="text"
119
+ value={query}
120
+ onChange={(e) => setQuery(e.target.value)}
121
+ placeholder="Search sessions..."
122
+ style={{
123
+ padding: "6px 10px",
124
+ background: "#0d0e15",
125
+ border: "1px solid #2a2b36",
126
+ borderRadius: "4px",
127
+ color: "#fff",
128
+ fontSize: "12px",
129
+ width: "220px",
130
+ }}
131
+ />
132
+ <button
133
+ type="button"
134
+ onClick={fetchSessions}
135
+ disabled={loading}
136
+ style={{
137
+ padding: "6px 12px",
138
+ background: "transparent",
139
+ color: "#a0a0b0",
140
+ border: "1px solid #2a2b36",
141
+ borderRadius: "4px",
142
+ cursor: loading ? "not-allowed" : "pointer",
143
+ fontSize: "12px",
144
+ }}
145
+ >
146
+ Refresh
147
+ </button>
148
+ </div>
149
+ </div>
150
+
151
+ {/* Loading state */}
152
+ {loading && (
153
+ <div
154
+ style={{
155
+ background: "#1a1b26",
156
+ borderRadius: "8px",
157
+ padding: "40px 20px",
158
+ textAlign: "center",
159
+ border: "1px solid #2a2b36",
160
+ fontSize: "12px",
161
+ opacity: 0.6,
162
+ }}
163
+ >
164
+ Loading sessions...
165
+ </div>
166
+ )}
167
+
168
+ {/* Error state */}
169
+ {error && !loading && (
170
+ <div
171
+ role="alert"
172
+ style={{
173
+ background: "#7f1d1d",
174
+ color: "#fecaca",
175
+ border: "1px solid #991b1b",
176
+ borderRadius: "8px",
177
+ padding: "12px",
178
+ fontSize: "12px",
179
+ marginBottom: "12px",
180
+ }}
181
+ >
182
+ <strong>Error: </strong>
183
+ {error}
184
+ </div>
185
+ )}
186
+
187
+ {/* Empty state */}
188
+ {!loading && !error && sessions.length === 0 && (
189
+ <div
190
+ style={{
191
+ background: "#1a1b26",
192
+ borderRadius: "8px",
193
+ padding: "40px 20px",
194
+ textAlign: "center",
195
+ border: "1px dashed #2a2b36",
196
+ }}
197
+ >
198
+ <div style={{ fontSize: "32px", marginBottom: "8px" }}>💬</div>
199
+ <div style={{ fontSize: "14px", fontWeight: 600, marginBottom: "4px" }}>
200
+ No sessions yet
201
+ </div>
202
+ <div style={{ fontSize: "12px", opacity: 0.6 }}>
203
+ Start chatting with GitPilot to create your first session.
204
+ </div>
205
+ </div>
206
+ )}
207
+
208
+ {/* Table */}
209
+ {!loading && filtered.length > 0 && (
210
+ <div
211
+ style={{
212
+ background: "#1a1b26",
213
+ borderRadius: "8px",
214
+ border: "1px solid #2a2b36",
215
+ overflow: "hidden",
216
+ }}
217
+ >
218
+ <table
219
+ style={{
220
+ width: "100%",
221
+ borderCollapse: "collapse",
222
+ fontSize: "12px",
223
+ }}
224
+ >
225
+ <thead>
226
+ <tr style={{ background: "#0d0e15" }}>
227
+ <th style={thStyle}>Name</th>
228
+ <th style={thStyle}>Repository</th>
229
+ <th style={thStyle}>Branch</th>
230
+ <th style={thStyle}>Messages</th>
231
+ <th style={thStyle}>Status</th>
232
+ <th style={thStyle}>Updated</th>
233
+ <th style={{ ...thStyle, textAlign: "right" }}>Actions</th>
234
+ </tr>
235
+ </thead>
236
+ <tbody>
237
+ {filtered.map((s) => (
238
+ <tr
239
+ key={s.id}
240
+ style={{
241
+ borderTop: "1px solid #2a2b36",
242
+ cursor: onSelectSession ? "pointer" : "default",
243
+ }}
244
+ onMouseEnter={(e) =>
245
+ (e.currentTarget.style.background = "#22232e")
246
+ }
247
+ onMouseLeave={(e) =>
248
+ (e.currentTarget.style.background = "transparent")
249
+ }
250
+ onClick={() => onSelectSession?.(s)}
251
+ >
252
+ <td style={tdStyle}>
253
+ <div style={{ fontWeight: 600 }}>
254
+ {s.name || <span style={{ opacity: 0.4 }}>(unnamed)</span>}
255
+ </div>
256
+ <div
257
+ style={{
258
+ fontSize: "10px",
259
+ opacity: 0.4,
260
+ fontFamily: "monospace",
261
+ }}
262
+ >
263
+ {s.id?.slice(0, 12)}
264
+ </div>
265
+ </td>
266
+ <td style={{ ...tdStyle, fontFamily: "monospace" }}>
267
+ {s.repo || <span style={{ opacity: 0.4 }}>—</span>}
268
+ </td>
269
+ <td style={{ ...tdStyle, fontFamily: "monospace" }}>
270
+ {s.branch || <span style={{ opacity: 0.4 }}>—</span>}
271
+ </td>
272
+ <td style={tdStyle}>{s.message_count ?? 0}</td>
273
+ <td style={tdStyle}>
274
+ <span
275
+ style={{
276
+ padding: "2px 8px",
277
+ background:
278
+ s.status === "active"
279
+ ? "#064e3b"
280
+ : s.status === "completed"
281
+ ? "#1e3a5f"
282
+ : "#374151",
283
+ color:
284
+ s.status === "active"
285
+ ? "#a7f3d0"
286
+ : s.status === "completed"
287
+ ? "#93c5fd"
288
+ : "#9ca3af",
289
+ borderRadius: "10px",
290
+ fontSize: "10px",
291
+ fontWeight: 600,
292
+ textTransform: "uppercase",
293
+ }}
294
+ >
295
+ {s.status || "unknown"}
296
+ </span>
297
+ </td>
298
+ <td style={{ ...tdStyle, opacity: 0.7 }}>
299
+ {formatRelativeTime(s.updated_at)}
300
+ </td>
301
+ <td style={{ ...tdStyle, textAlign: "right" }}>
302
+ <button
303
+ type="button"
304
+ onClick={(e) => {
305
+ e.stopPropagation();
306
+ handleDelete(s);
307
+ }}
308
+ disabled={deletingId === s.id}
309
+ style={{
310
+ padding: "4px 10px",
311
+ background: "transparent",
312
+ color: "#f87171",
313
+ border: "1px solid #991b1b",
314
+ borderRadius: "4px",
315
+ cursor: deletingId === s.id ? "not-allowed" : "pointer",
316
+ fontSize: "11px",
317
+ }}
318
+ >
319
+ {deletingId === s.id ? "..." : "Delete"}
320
+ </button>
321
+ </td>
322
+ </tr>
323
+ ))}
324
+ </tbody>
325
+ </table>
326
+ </div>
327
+ )}
328
+
329
+ {/* No matches for search */}
330
+ {!loading && sessions.length > 0 && filtered.length === 0 && (
331
+ <div
332
+ style={{
333
+ background: "#1a1b26",
334
+ borderRadius: "8px",
335
+ padding: "20px",
336
+ textAlign: "center",
337
+ border: "1px dashed #2a2b36",
338
+ fontSize: "12px",
339
+ opacity: 0.7,
340
+ }}
341
+ >
342
+ No sessions match "{query}"
343
+ </div>
344
+ )}
345
+ </div>
346
+ );
347
+ }
348
+
349
+ const thStyle = {
350
+ padding: "10px 12px",
351
+ textAlign: "left",
352
+ fontSize: "11px",
353
+ fontWeight: 600,
354
+ textTransform: "uppercase",
355
+ letterSpacing: "0.5px",
356
+ opacity: 0.7,
357
+ };
358
+
359
+ const tdStyle = {
360
+ padding: "10px 12px",
361
+ verticalAlign: "middle",
362
+ };
frontend/components/AdminTabs/SkillsTab.jsx ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/SkillsTab.jsx
2
+ import React, { useEffect, useState, useCallback } from "react";
3
+ import { apiUrl, safeFetchJSON } from "../../utils/api.js";
4
+
5
+ /**
6
+ * Skills tab — lists all loaded skills from /api/skills and allows
7
+ * reloading them from disk via /api/skills/reload.
8
+ *
9
+ * Best practices applied:
10
+ * - Fetch on mount
11
+ * - Explicit reload button (skills are loaded from .md files on disk)
12
+ * - Loading / empty / error states
13
+ * - Auto-trigger indicator badge
14
+ * - Required tools list per skill
15
+ * - Source file path for debugging
16
+ */
17
+
18
+ export default function SkillsTab({ showToast }) {
19
+ const [skills, setSkills] = useState([]);
20
+ const [loading, setLoading] = useState(true);
21
+ const [reloading, setReloading] = useState(false);
22
+ const [error, setError] = useState(null);
23
+
24
+ const fetchSkills = useCallback(async () => {
25
+ setError(null);
26
+ try {
27
+ const data = await safeFetchJSON(apiUrl("/api/skills"), { timeout: 10000 });
28
+ setSkills(Array.isArray(data.skills) ? data.skills : []);
29
+ } catch (err) {
30
+ setError(err?.message || "Failed to load skills");
31
+ } finally {
32
+ setLoading(false);
33
+ }
34
+ }, []);
35
+
36
+ useEffect(() => {
37
+ fetchSkills();
38
+ }, [fetchSkills]);
39
+
40
+ const handleReload = async () => {
41
+ setReloading(true);
42
+ setError(null);
43
+ try {
44
+ const data = await safeFetchJSON(apiUrl("/api/skills/reload"), {
45
+ method: "POST",
46
+ timeout: 10000,
47
+ });
48
+ showToast?.(
49
+ "Skills reloaded",
50
+ `${data.count ?? 0} skill${data.count !== 1 ? "s" : ""} loaded from disk.`
51
+ );
52
+ await fetchSkills();
53
+ } catch (err) {
54
+ setError(err?.message || "Failed to reload skills");
55
+ } finally {
56
+ setReloading(false);
57
+ }
58
+ };
59
+
60
+ return (
61
+ <div>
62
+ <div
63
+ style={{
64
+ display: "flex",
65
+ justifyContent: "space-between",
66
+ alignItems: "flex-start",
67
+ marginBottom: "16px",
68
+ }}
69
+ >
70
+ <div>
71
+ <h3 style={{ marginBottom: "4px" }}>Skills</h3>
72
+ <p style={{ fontSize: "12px", opacity: 0.7 }}>
73
+ Reusable prompt templates loaded from{" "}
74
+ <code style={{ fontSize: "11px" }}>.gitpilot/skills/*.md</code> files.
75
+ </p>
76
+ </div>
77
+ <button
78
+ type="button"
79
+ onClick={handleReload}
80
+ disabled={reloading || loading}
81
+ style={{
82
+ padding: "6px 12px",
83
+ background: reloading ? "#555" : "#3B82F6",
84
+ color: "#fff",
85
+ border: "none",
86
+ borderRadius: "4px",
87
+ cursor: reloading || loading ? "not-allowed" : "pointer",
88
+ fontSize: "12px",
89
+ fontWeight: 600,
90
+ }}
91
+ >
92
+ {reloading ? "Reloading..." : "Reload Skills"}
93
+ </button>
94
+ </div>
95
+
96
+ {/* Loading state */}
97
+ {loading && (
98
+ <div
99
+ style={{
100
+ background: "#1a1b26",
101
+ borderRadius: "8px",
102
+ padding: "40px 20px",
103
+ textAlign: "center",
104
+ border: "1px solid #2a2b36",
105
+ fontSize: "12px",
106
+ opacity: 0.6,
107
+ }}
108
+ >
109
+ Loading skills...
110
+ </div>
111
+ )}
112
+
113
+ {/* Error state */}
114
+ {error && !loading && (
115
+ <div
116
+ role="alert"
117
+ style={{
118
+ background: "#7f1d1d",
119
+ color: "#fecaca",
120
+ border: "1px solid #991b1b",
121
+ borderRadius: "8px",
122
+ padding: "12px",
123
+ fontSize: "12px",
124
+ }}
125
+ >
126
+ <strong>Error: </strong>
127
+ {error}
128
+ </div>
129
+ )}
130
+
131
+ {/* Empty state */}
132
+ {!loading && !error && skills.length === 0 && (
133
+ <div
134
+ style={{
135
+ background: "#1a1b26",
136
+ borderRadius: "8px",
137
+ padding: "40px 20px",
138
+ textAlign: "center",
139
+ border: "1px dashed #2a2b36",
140
+ }}
141
+ >
142
+ <div style={{ fontSize: "32px", marginBottom: "8px" }}>📚</div>
143
+ <div style={{ fontSize: "14px", fontWeight: 600, marginBottom: "4px" }}>
144
+ No skills loaded
145
+ </div>
146
+ <div style={{ fontSize: "12px", opacity: 0.6 }}>
147
+ Create a <code>.gitpilot/skills/my-skill.md</code> file with YAML
148
+ frontmatter to add custom skills.
149
+ </div>
150
+ </div>
151
+ )}
152
+
153
+ {/* Skills grid */}
154
+ {!loading && skills.length > 0 && (
155
+ <div
156
+ style={{
157
+ display: "grid",
158
+ gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
159
+ gap: "12px",
160
+ }}
161
+ >
162
+ {skills.map((skill) => (
163
+ <div
164
+ key={skill.name}
165
+ style={{
166
+ background: "#1a1b26",
167
+ borderRadius: "8px",
168
+ padding: "16px",
169
+ border: "1px solid #2a2b36",
170
+ display: "flex",
171
+ flexDirection: "column",
172
+ gap: "8px",
173
+ }}
174
+ >
175
+ <div
176
+ style={{
177
+ display: "flex",
178
+ justifyContent: "space-between",
179
+ alignItems: "flex-start",
180
+ gap: "8px",
181
+ }}
182
+ >
183
+ <h4
184
+ style={{
185
+ fontSize: "14px",
186
+ fontWeight: 600,
187
+ margin: 0,
188
+ color: "#fff",
189
+ }}
190
+ >
191
+ {skill.name}
192
+ </h4>
193
+ {skill.auto_trigger && (
194
+ <span
195
+ title="Auto-triggered by matching context"
196
+ style={{
197
+ padding: "2px 8px",
198
+ background: "#1e3a5f",
199
+ color: "#93c5fd",
200
+ border: "1px solid #3B82F6",
201
+ borderRadius: "10px",
202
+ fontSize: "9px",
203
+ fontWeight: 700,
204
+ textTransform: "uppercase",
205
+ whiteSpace: "nowrap",
206
+ }}
207
+ >
208
+ Auto
209
+ </span>
210
+ )}
211
+ </div>
212
+
213
+ <p
214
+ style={{
215
+ fontSize: "12px",
216
+ opacity: 0.7,
217
+ lineHeight: 1.5,
218
+ margin: 0,
219
+ minHeight: "36px",
220
+ }}
221
+ >
222
+ {skill.description || "No description"}
223
+ </p>
224
+
225
+ {Array.isArray(skill.required_tools) && skill.required_tools.length > 0 && (
226
+ <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
227
+ {skill.required_tools.map((t) => (
228
+ <span
229
+ key={t}
230
+ style={{
231
+ padding: "2px 6px",
232
+ background: "#0d0e15",
233
+ border: "1px solid #2a2b36",
234
+ borderRadius: "4px",
235
+ fontSize: "10px",
236
+ fontFamily: "monospace",
237
+ opacity: 0.8,
238
+ }}
239
+ >
240
+ {t}
241
+ </span>
242
+ ))}
243
+ </div>
244
+ )}
245
+
246
+ {skill.source && (
247
+ <div
248
+ style={{
249
+ fontSize: "10px",
250
+ opacity: 0.4,
251
+ fontFamily: "monospace",
252
+ borderTop: "1px solid #2a2b36",
253
+ paddingTop: "8px",
254
+ wordBreak: "break-all",
255
+ }}
256
+ >
257
+ {skill.source}
258
+ </div>
259
+ )}
260
+ </div>
261
+ ))}
262
+ </div>
263
+ )}
264
+ </div>
265
+ );
266
+ }
frontend/components/AdminTabs/WorkspaceModesTab.jsx ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/WorkspaceModesTab.jsx
2
+ import React, { useState } from "react";
3
+ import { startSession } from "../../utils/api.js";
4
+
5
+ /**
6
+ * Workspace Modes tab — allows the user to start a session in one of
7
+ * three modes (folder, local_git, github). Calls POST /api/session/start.
8
+ *
9
+ * Best practices applied:
10
+ * - Loading state while the request is in flight
11
+ * - Per-mode error state (not a global error)
12
+ * - Disabled card during submission to prevent double-click
13
+ * - ARIA role="button" + aria-disabled for accessibility
14
+ * - Toast notification on success
15
+ * - Success callback so App.jsx can set activeSessionId and switch to workspace view
16
+ */
17
+
18
+ const MODES = [
19
+ {
20
+ id: "folder",
21
+ title: "Folder Mode",
22
+ description: "Work with any local folder. No Git required.",
23
+ requires: "A local folder path",
24
+ enables: "Chat, explain, review",
25
+ promptKey: "folder_path",
26
+ promptLabel: "Folder path (absolute)",
27
+ promptPlaceholder: "/home/you/myproject",
28
+ buildPayload: (value) => ({ mode: "folder", folder_path: value }),
29
+ },
30
+ {
31
+ id: "local_git",
32
+ title: "Local Git Mode",
33
+ description: "Full repo + branch context for AI assistance.",
34
+ requires: "A local Git repository",
35
+ enables: "All local features (branches, diff, commit)",
36
+ promptKey: "repo_root",
37
+ promptLabel: "Repository root (absolute path)",
38
+ promptPlaceholder: "/home/you/my-git-repo",
39
+ buildPayload: (value) => ({ mode: "local_git", repo_root: value }),
40
+ },
41
+ {
42
+ id: "github",
43
+ title: "GitHub Mode",
44
+ description: "PRs, issues, remote workflows via GitHub API.",
45
+ requires: "GitHub token (already signed in)",
46
+ enables: "Full platform features",
47
+ promptKey: "repo_full_name",
48
+ promptLabel: "Repository (owner/repo)",
49
+ promptPlaceholder: "octocat/hello-world",
50
+ buildPayload: (value) => ({ mode: "github", repo_full_name: value }),
51
+ },
52
+ ];
53
+
54
+ export default function WorkspaceModesTab({ onSessionStarted, showToast, runtime }) {
55
+ const [activeModeId, setActiveModeId] = useState(null);
56
+ const [inputValue, setInputValue] = useState("");
57
+ const [submittingId, setSubmittingId] = useState(null);
58
+ const [errorByMode, setErrorByMode] = useState({});
59
+
60
+ // In a cloud workspace there is no user-owned filesystem, so folder and
61
+ // local-Git modes can't work — only GitHub-sourced code makes sense.
62
+ const isCloud = runtime === "cloud";
63
+ const modes = isCloud ? MODES.filter((m) => m.id === "github") : MODES;
64
+
65
+ const handleCardClick = (mode) => {
66
+ if (submittingId) return;
67
+ setActiveModeId(mode.id);
68
+ setInputValue("");
69
+ setErrorByMode((prev) => ({ ...prev, [mode.id]: null }));
70
+ };
71
+
72
+ const handleStart = async (mode) => {
73
+ const trimmed = inputValue.trim();
74
+ if (!trimmed) {
75
+ setErrorByMode((prev) => ({
76
+ ...prev,
77
+ [mode.id]: `${mode.promptLabel} is required`,
78
+ }));
79
+ return;
80
+ }
81
+
82
+ setSubmittingId(mode.id);
83
+ setErrorByMode((prev) => ({ ...prev, [mode.id]: null }));
84
+
85
+ try {
86
+ const payload = mode.buildPayload(trimmed);
87
+ const result = await startSession(payload);
88
+
89
+ showToast?.(
90
+ `${mode.title} started`,
91
+ `Session ${result.session_id?.slice(0, 8) || ""} is now active.`
92
+ );
93
+
94
+ onSessionStarted?.(result);
95
+ setActiveModeId(null);
96
+ setInputValue("");
97
+ } catch (err) {
98
+ setErrorByMode((prev) => ({
99
+ ...prev,
100
+ [mode.id]: err?.message || "Failed to start session",
101
+ }));
102
+ } finally {
103
+ setSubmittingId(null);
104
+ }
105
+ };
106
+
107
+ const handleCancel = () => {
108
+ if (submittingId) return;
109
+ setActiveModeId(null);
110
+ setInputValue("");
111
+ };
112
+
113
+ return (
114
+ <div>
115
+ <h3 style={{ marginBottom: "16px" }}>Workspace Modes</h3>
116
+ <p style={{ fontSize: "12px", opacity: 0.7, marginBottom: "16px" }}>
117
+ {isCloud
118
+ ? "You're in a cloud workspace, so GitPilot works from a GitHub repository. Folder and Local Git modes are only available when running GitPilot on your own machine."
119
+ : "Choose how you want GitPilot to interact with your code. You can switch modes at any time."}
120
+ </p>
121
+
122
+ <div
123
+ style={{
124
+ display: "grid",
125
+ gridTemplateColumns: `repeat(${Math.min(modes.length, 3)}, 1fr)`,
126
+ gap: "16px",
127
+ }}
128
+ >
129
+ {modes.map((mode) => {
130
+ const isActive = activeModeId === mode.id;
131
+ const isSubmitting = submittingId === mode.id;
132
+ const error = errorByMode[mode.id];
133
+
134
+ return (
135
+ <div
136
+ key={mode.id}
137
+ role="button"
138
+ tabIndex={isSubmitting ? -1 : 0}
139
+ aria-disabled={!!submittingId && !isSubmitting}
140
+ onClick={() => !isActive && handleCardClick(mode)}
141
+ onKeyDown={(e) => {
142
+ if ((e.key === "Enter" || e.key === " ") && !isActive) {
143
+ e.preventDefault();
144
+ handleCardClick(mode);
145
+ }
146
+ }}
147
+ style={{
148
+ background: isActive ? "#1e3a5f" : "#1a1b26",
149
+ borderRadius: "8px",
150
+ padding: "20px",
151
+ border: isActive ? "1px solid #3B82F6" : "1px solid #2a2b36",
152
+ cursor: submittingId && !isSubmitting ? "not-allowed" : "pointer",
153
+ opacity: submittingId && !isSubmitting ? 0.5 : 1,
154
+ transition: "all 150ms ease",
155
+ }}
156
+ >
157
+ <h4 style={{ marginBottom: "8px", color: isActive ? "#93c5fd" : "#fff" }}>
158
+ {mode.title}
159
+ </h4>
160
+ <p style={{ fontSize: "12px", opacity: 0.7, marginBottom: "12px" }}>
161
+ {mode.description}
162
+ </p>
163
+ <div style={{ fontSize: "12px", marginBottom: "4px" }}>
164
+ <span style={{ opacity: 0.6 }}>Requires: </span>
165
+ {mode.requires}
166
+ </div>
167
+ <div style={{ fontSize: "12px", marginBottom: "12px" }}>
168
+ <span style={{ opacity: 0.6 }}>Enables: </span>
169
+ {mode.enables}
170
+ </div>
171
+
172
+ {isActive && (
173
+ <div onClick={(e) => e.stopPropagation()} style={{ marginTop: "12px" }}>
174
+ <label
175
+ htmlFor={`mode-input-${mode.id}`}
176
+ style={{
177
+ fontSize: "11px",
178
+ opacity: 0.7,
179
+ display: "block",
180
+ marginBottom: "4px",
181
+ }}
182
+ >
183
+ {mode.promptLabel}
184
+ </label>
185
+ <input
186
+ id={`mode-input-${mode.id}`}
187
+ type="text"
188
+ value={inputValue}
189
+ onChange={(e) => setInputValue(e.target.value)}
190
+ onKeyDown={(e) => {
191
+ if (e.key === "Enter") {
192
+ e.preventDefault();
193
+ handleStart(mode);
194
+ } else if (e.key === "Escape") {
195
+ handleCancel();
196
+ }
197
+ }}
198
+ placeholder={mode.promptPlaceholder}
199
+ disabled={isSubmitting}
200
+ autoFocus
201
+ style={{
202
+ width: "100%",
203
+ padding: "6px 8px",
204
+ background: "#0d0e15",
205
+ border: "1px solid #2a2b36",
206
+ borderRadius: "4px",
207
+ color: "#fff",
208
+ fontSize: "12px",
209
+ fontFamily: "monospace",
210
+ }}
211
+ />
212
+ {error && (
213
+ <div
214
+ style={{
215
+ fontSize: "11px",
216
+ color: "#f87171",
217
+ marginTop: "6px",
218
+ }}
219
+ role="alert"
220
+ >
221
+ {error}
222
+ </div>
223
+ )}
224
+ <div style={{ display: "flex", gap: "6px", marginTop: "10px" }}>
225
+ <button
226
+ type="button"
227
+ onClick={() => handleStart(mode)}
228
+ disabled={isSubmitting || !inputValue.trim()}
229
+ style={{
230
+ padding: "6px 12px",
231
+ background: isSubmitting ? "#555" : "#3B82F6",
232
+ color: "#fff",
233
+ border: "none",
234
+ borderRadius: "4px",
235
+ cursor: isSubmitting || !inputValue.trim() ? "not-allowed" : "pointer",
236
+ fontSize: "12px",
237
+ fontWeight: 600,
238
+ }}
239
+ >
240
+ {isSubmitting ? "Starting..." : "Start Session"}
241
+ </button>
242
+ <button
243
+ type="button"
244
+ onClick={handleCancel}
245
+ disabled={isSubmitting}
246
+ style={{
247
+ padding: "6px 12px",
248
+ background: "transparent",
249
+ color: "#a0a0b0",
250
+ border: "1px solid #2a2b36",
251
+ borderRadius: "4px",
252
+ cursor: isSubmitting ? "not-allowed" : "pointer",
253
+ fontSize: "12px",
254
+ }}
255
+ >
256
+ Cancel
257
+ </button>
258
+ </div>
259
+ </div>
260
+ )}
261
+ </div>
262
+ );
263
+ })}
264
+ </div>
265
+ </div>
266
+ );
267
+ }
frontend/components/AdminTabs/index.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/index.js
2
+ // Barrel export — all admin tab components in one place
3
+ export { default as WorkspaceModesTab } from "./WorkspaceModesTab.jsx";
4
+ export { default as SecurityTab } from "./SecurityTab.jsx";
5
+ export { default as IntegrationsTab } from "./IntegrationsTab.jsx";
6
+ export { default as MCPServersTab } from "./MCPServersTab.jsx";
7
+ export { default as SkillsTab } from "./SkillsTab.jsx";
8
+ export { default as SessionsTab } from "./SessionsTab.jsx";
9
+ export { default as AdvancedTab } from "./AdvancedTab.jsx";
10
+ export { default as SandboxTab } from "./SandboxTab.jsx";
11
+ export { default as AccountTab } from "./AccountTab.jsx";
frontend/components/AdminTabs/mcp/CatalogList.jsx ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/CatalogList.jsx
2
+ // Browse curated MCP servers shipped with GitPilot. Each item has a
3
+ // one-click "Install" that lands the server in the Installed tab,
4
+ // disabled by default.
5
+
6
+ import React from "react";
7
+
8
+ export default function CatalogList({ items, onInstall }) {
9
+ if (!items?.length) {
10
+ return (
11
+ <p style={{ color: "#a0a0b0", fontSize: "13px" }}>
12
+ No catalog entries shipped with this build.
13
+ </p>
14
+ );
15
+ }
16
+
17
+ return (
18
+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "1fr" }}>
19
+ {items.map((item) => (
20
+ <div
21
+ key={item.id}
22
+ style={{
23
+ background: "#1a1b26",
24
+ border: "1px solid #2a2b36",
25
+ borderRadius: "8px",
26
+ padding: "16px 20px",
27
+ display: "flex",
28
+ justifyContent: "space-between",
29
+ alignItems: "center",
30
+ gap: "16px",
31
+ }}
32
+ >
33
+ <div style={{ flex: "1 1 auto", minWidth: 0 }}>
34
+ <div
35
+ style={{
36
+ display: "flex",
37
+ gap: "8px",
38
+ alignItems: "center",
39
+ marginBottom: "4px",
40
+ }}
41
+ >
42
+ <strong style={{ fontSize: "14px", color: "#e0e0e7" }}>
43
+ {item.id}
44
+ </strong>
45
+ {item.installed && (
46
+ <span
47
+ style={{
48
+ padding: "2px 8px",
49
+ background: "#0f3a26",
50
+ color: "#86efac",
51
+ borderRadius: "4px",
52
+ fontSize: "10px",
53
+ fontWeight: 600,
54
+ }}
55
+ >
56
+ installed
57
+ </span>
58
+ )}
59
+ </div>
60
+ <div style={{ fontSize: "12px", color: "#a0a0b0", marginBottom: "6px" }}>
61
+ {item.description}
62
+ </div>
63
+ <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
64
+ {(item.tags || []).map((t) => (
65
+ <span
66
+ key={t}
67
+ style={{
68
+ padding: "1px 6px",
69
+ background: "#252634",
70
+ border: "1px solid #2a2b36",
71
+ borderRadius: "10px",
72
+ fontSize: "10px",
73
+ color: "#cdd0d8",
74
+ }}
75
+ >
76
+ {t}
77
+ </span>
78
+ ))}
79
+ </div>
80
+ </div>
81
+ <button
82
+ onClick={() => onInstall(item.id)}
83
+ disabled={item.installed}
84
+ style={{
85
+ padding: "6px 14px",
86
+ background: item.installed ? "#252634" : "#3B82F6",
87
+ color: item.installed ? "#7a7d8a" : "#fff",
88
+ border: "none",
89
+ borderRadius: "4px",
90
+ cursor: item.installed ? "not-allowed" : "pointer",
91
+ fontSize: "12px",
92
+ fontWeight: 600,
93
+ }}
94
+ >
95
+ {item.installed ? "Installed" : "Install"}
96
+ </button>
97
+ </div>
98
+ ))}
99
+ </div>
100
+ );
101
+ }
frontend/components/AdminTabs/mcp/CustomInstallForm.jsx ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/CustomInstallForm.jsx
2
+ // Paste-a-register.json form for installing a custom MCP server.
3
+
4
+ import React, { useState } from "react";
5
+
6
+ const SAMPLE = `{
7
+ "name": "mcp-neo4j-server",
8
+ "endpoint": "http://mcp-neo4j-server:8083/mcp",
9
+ "description": "Neo4j MCP server for graph schema discovery",
10
+ "tags": ["graph", "neo4j"],
11
+ "auth": { "type": "bearer", "env": "MCP_NEO4J_SERVER_TOKEN" }
12
+ }`;
13
+
14
+ export default function CustomInstallForm({ onSubmit }) {
15
+ const [text, setText] = useState(SAMPLE);
16
+ const [err, setErr] = useState(null);
17
+ const [submitting, setSubmitting] = useState(false);
18
+
19
+ const handleSubmit = async () => {
20
+ setErr(null);
21
+ let parsed;
22
+ try {
23
+ parsed = JSON.parse(text);
24
+ } catch (e) {
25
+ setErr("Invalid JSON: " + (e?.message || ""));
26
+ return;
27
+ }
28
+ if (!parsed.name || !parsed.endpoint) {
29
+ setErr("register.json must include 'name' and 'endpoint'.");
30
+ return;
31
+ }
32
+ setSubmitting(true);
33
+ try {
34
+ await onSubmit(parsed);
35
+ setText(SAMPLE);
36
+ } catch (e) {
37
+ setErr(e?.message || "Install failed");
38
+ } finally {
39
+ setSubmitting(false);
40
+ }
41
+ };
42
+
43
+ return (
44
+ <div
45
+ style={{
46
+ background: "#1a1b26",
47
+ border: "1px solid #2a2b36",
48
+ borderRadius: "8px",
49
+ padding: "20px",
50
+ }}
51
+ >
52
+ <h4 style={{ margin: "0 0 6px 0", color: "#e0e0e7" }}>Install custom server</h4>
53
+ <p style={{ margin: "0 0 12px 0", fontSize: "12px", color: "#a0a0b0" }}>
54
+ Paste a Context Forge <code>register.json</code>. The server lands
55
+ disabled — turn it on from the Installed tab once you have set its
56
+ auth token.
57
+ </p>
58
+ <textarea
59
+ value={text}
60
+ onChange={(e) => setText(e.target.value)}
61
+ rows={12}
62
+ spellCheck={false}
63
+ aria-label="register.json"
64
+ style={{
65
+ width: "100%",
66
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
67
+ fontSize: "12px",
68
+ background: "#0f1018",
69
+ color: "#cdd0d8",
70
+ border: "1px solid #2a2b36",
71
+ borderRadius: "6px",
72
+ padding: "12px",
73
+ resize: "vertical",
74
+ boxSizing: "border-box",
75
+ }}
76
+ />
77
+ {err && (
78
+ <div
79
+ role="alert"
80
+ style={{
81
+ marginTop: "8px",
82
+ padding: "8px 12px",
83
+ background: "#3a0f0f",
84
+ border: "1px solid #5a1f1f",
85
+ borderRadius: "6px",
86
+ color: "#fca5a5",
87
+ fontSize: "12px",
88
+ }}
89
+ >
90
+ {err}
91
+ </div>
92
+ )}
93
+ <div
94
+ style={{
95
+ display: "flex",
96
+ justifyContent: "flex-end",
97
+ gap: "8px",
98
+ marginTop: "12px",
99
+ }}
100
+ >
101
+ <button
102
+ onClick={() => setText(SAMPLE)}
103
+ style={{
104
+ padding: "6px 12px",
105
+ background: "transparent",
106
+ color: "#cdd0d8",
107
+ border: "1px solid #3a3b4a",
108
+ borderRadius: "4px",
109
+ cursor: "pointer",
110
+ fontSize: "12px",
111
+ }}
112
+ >
113
+ Reset
114
+ </button>
115
+ <button
116
+ onClick={handleSubmit}
117
+ disabled={submitting}
118
+ style={{
119
+ padding: "6px 14px",
120
+ background: "#3B82F6",
121
+ color: "#fff",
122
+ border: "none",
123
+ borderRadius: "4px",
124
+ cursor: submitting ? "not-allowed" : "pointer",
125
+ fontSize: "12px",
126
+ fontWeight: 600,
127
+ }}
128
+ >
129
+ {submitting ? "Installing…" : "Install server"}
130
+ </button>
131
+ </div>
132
+ </div>
133
+ );
134
+ }
frontend/components/AdminTabs/mcp/GatewayForm.jsx ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/GatewayForm.jsx
2
+ //
3
+ // "Which Context Forge, and how do we sign in to it."
4
+ //
5
+ // The design rules, in the order they matter:
6
+ //
7
+ // 1. Test before you commit. The primary action is "Test connection", not
8
+ // "Save" — a credential is proved against the real gateway here, rather
9
+ // than discovered to be wrong in the middle of a coding run. Save is
10
+ // enabled either way, because sometimes you are configuring a gateway
11
+ // that is not up yet.
12
+ // 2. A saved secret is never displayed. The server returns hasPassword /
13
+ // hasApiToken booleans and nothing else, so these fields render empty with
14
+ // a "saved" marker. Leaving them blank keeps what is stored; removing a
15
+ // credential is an explicit button, never a side effect of an empty box.
16
+ // 3. Say where a value came from. A URL set by the deployment's environment
17
+ // is labelled as such, so nobody wonders why their edit "did not stick".
18
+ //
19
+ // Layout is a single column that reflows on narrow screens, so the same
20
+ // component serves desktop and mobile without a second implementation.
21
+
22
+ import React, { useEffect, useState } from "react";
23
+ import { apiUrl, safeFetchJSON } from "../../../utils/api.js";
24
+
25
+ const AUTH_MODES = [
26
+ { id: "auto", label: "Automatic", hint: "Detect what the gateway accepts. Recommended." },
27
+ { id: "none", label: "No credential", hint: "For a gateway running with authentication disabled." },
28
+ { id: "token", label: "API token", hint: "A Forge API token. Revocable; best for shared gateways." },
29
+ { id: "login", label: "Email + password", hint: "Sign in as a Forge admin and use the token it returns." },
30
+ ];
31
+
32
+ const box = {
33
+ background: "#1a1b26",
34
+ border: "1px solid #2a2b36",
35
+ borderRadius: "8px",
36
+ padding: "20px",
37
+ };
38
+
39
+ const label = { display: "block", fontSize: "12px", color: "#a0a0b0", marginBottom: "6px" };
40
+
41
+ const input = {
42
+ width: "100%",
43
+ boxSizing: "border-box",
44
+ padding: "10px 12px",
45
+ background: "#12131c",
46
+ border: "1px solid #2a2b36",
47
+ borderRadius: "6px",
48
+ color: "#e0e0e7",
49
+ fontSize: "13px",
50
+ outline: "none",
51
+ };
52
+
53
+ const button = (variant) => ({
54
+ padding: "10px 16px",
55
+ borderRadius: "6px",
56
+ border: variant === "primary" ? "none" : "1px solid #2a2b36",
57
+ background: variant === "primary" ? "#3B82F6" : "transparent",
58
+ color: variant === "primary" ? "#fff" : "#a0a0b0",
59
+ cursor: "pointer",
60
+ fontSize: "13px",
61
+ fontWeight: variant === "primary" ? 600 : 400,
62
+ minHeight: "40px",
63
+ });
64
+
65
+ export default function GatewayForm({ showToast, onSaved }) {
66
+ const [config, setConfig] = useState(null);
67
+ const [draft, setDraft] = useState({ url: "", authMode: "auto", email: "", password: "", apiToken: "", label: "" });
68
+ const [busy, setBusy] = useState("");
69
+ const [result, setResult] = useState(null);
70
+ const [error, setError] = useState("");
71
+
72
+ useEffect(() => {
73
+ let live = true;
74
+ safeFetchJSON(apiUrl("/api/mcp/gateway"), { timeout: 5000 })
75
+ .then((data) => {
76
+ if (!live || !data) return;
77
+ setConfig(data);
78
+ setDraft((d) => ({
79
+ ...d,
80
+ url: data.savedUrl || data.url || "",
81
+ authMode: data.authMode || "auto",
82
+ email: data.email || "",
83
+ label: data.label || "",
84
+ }));
85
+ })
86
+ .catch((err) => live && setError(err?.message || "Could not load the gateway settings"));
87
+ return () => {
88
+ live = false;
89
+ };
90
+ }, []);
91
+
92
+ // Only send what the user actually filled in: a blank secret means "keep the
93
+ // one you have", so it must not be transmitted as an empty string.
94
+ const payload = () => {
95
+ const body = {
96
+ url: draft.url,
97
+ authMode: draft.authMode,
98
+ email: draft.email,
99
+ label: draft.label,
100
+ };
101
+ if (draft.password) body.password = draft.password;
102
+ if (draft.apiToken) body.apiToken = draft.apiToken;
103
+ return body;
104
+ };
105
+
106
+ const send = async (path, method, body) => {
107
+ const res = await fetch(apiUrl(path), {
108
+ method,
109
+ headers: { "Content-Type": "application/json" },
110
+ body: JSON.stringify(body),
111
+ });
112
+ const data = await res.json().catch(() => ({}));
113
+ if (!res.ok) throw new Error(data?.detail || `HTTP ${res.status}`);
114
+ return data;
115
+ };
116
+
117
+ const onTest = async () => {
118
+ setBusy("test");
119
+ setError("");
120
+ setResult(null);
121
+ try {
122
+ setResult(await send("/api/mcp/gateway/test", "POST", payload()));
123
+ } catch (err) {
124
+ setError(err?.message || "The test could not run");
125
+ } finally {
126
+ setBusy("");
127
+ }
128
+ };
129
+
130
+ const onSave = async () => {
131
+ setBusy("save");
132
+ setError("");
133
+ try {
134
+ const saved = await send("/api/mcp/gateway", "PUT", payload());
135
+ setConfig(saved);
136
+ // Clear the secret boxes: what is stored is now authoritative, and we
137
+ // never want a live credential sitting in component state.
138
+ setDraft((d) => ({ ...d, password: "", apiToken: "" }));
139
+ showToast?.("Gateway saved", saved.url);
140
+ onSaved?.(saved);
141
+ } catch (err) {
142
+ setError(err?.message || "Could not save the gateway settings");
143
+ } finally {
144
+ setBusy("");
145
+ }
146
+ };
147
+
148
+ const onClear = async (which) => {
149
+ const body = which === "password" ? { clearPassword: true } : { clearApiToken: true };
150
+ setBusy("clear");
151
+ try {
152
+ const saved = await send("/api/mcp/gateway", "PUT", body);
153
+ setConfig(saved);
154
+ showToast?.("Credential removed", which === "password" ? "Password" : "API token");
155
+ } catch (err) {
156
+ setError(err?.message || "Could not remove the credential");
157
+ } finally {
158
+ setBusy("");
159
+ }
160
+ };
161
+
162
+ const mode = AUTH_MODES.find((m) => m.id === draft.authMode) || AUTH_MODES[0];
163
+ const showToken = draft.authMode === "auto" || draft.authMode === "token";
164
+ const showLogin = draft.authMode === "auto" || draft.authMode === "login";
165
+
166
+ return (
167
+ <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
168
+ <div style={box}>
169
+ <h4 style={{ margin: "0 0 4px 0", color: "#e0e0e7", fontSize: "14px" }}>
170
+ Context Forge connection
171
+ </h4>
172
+ <p style={{ margin: "0 0 20px 0", color: "#a0a0b0", fontSize: "12px", lineHeight: 1.5 }}>
173
+ Point GitPilot at any MCP Context Forge — your own, a shared one, or the gateway
174
+ another app on this machine already started. Its servers become tools your coding
175
+ agents can call.
176
+ </p>
177
+
178
+ <div style={{ marginBottom: "16px" }}>
179
+ <label style={label} htmlFor="mcp-gateway-url">Gateway URL</label>
180
+ <input
181
+ id="mcp-gateway-url"
182
+ style={input}
183
+ value={draft.url}
184
+ onChange={(e) => setDraft({ ...draft, url: e.target.value })}
185
+ placeholder={config?.url || "http://localhost:4444"}
186
+ inputMode="url"
187
+ autoComplete="off"
188
+ spellCheck={false}
189
+ />
190
+ {config?.urlSource === "environment" && !draft.url && (
191
+ <small style={{ color: "#a0a0b0", fontSize: "11px" }}>
192
+ Currently <code>{config.url}</code>, set by this deployment's environment.
193
+ Type a URL here to override it.
194
+ </small>
195
+ )}
196
+ </div>
197
+
198
+ <div style={{ marginBottom: "16px" }}>
199
+ <label style={label} htmlFor="mcp-gateway-label">Name (optional)</label>
200
+ <input
201
+ id="mcp-gateway-label"
202
+ style={input}
203
+ value={draft.label}
204
+ onChange={(e) => setDraft({ ...draft, label: e.target.value })}
205
+ placeholder="Team gateway"
206
+ />
207
+ </div>
208
+
209
+ <div style={{ marginBottom: "16px" }}>
210
+ <label style={label} htmlFor="mcp-gateway-auth">Sign-in method</label>
211
+ <select
212
+ id="mcp-gateway-auth"
213
+ style={input}
214
+ value={draft.authMode}
215
+ onChange={(e) => setDraft({ ...draft, authMode: e.target.value })}
216
+ >
217
+ {AUTH_MODES.map((m) => (
218
+ <option key={m.id} value={m.id}>{m.label}</option>
219
+ ))}
220
+ </select>
221
+ <small style={{ color: "#a0a0b0", fontSize: "11px" }}>{mode.hint}</small>
222
+ </div>
223
+
224
+ {showLogin && (
225
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: "12px", marginBottom: "16px" }}>
226
+ <div>
227
+ <label style={label} htmlFor="mcp-gateway-email">Admin email</label>
228
+ <input
229
+ id="mcp-gateway-email"
230
+ style={input}
231
+ value={draft.email}
232
+ onChange={(e) => setDraft({ ...draft, email: e.target.value })}
233
+ placeholder="admin@example.com"
234
+ inputMode="email"
235
+ autoComplete="username"
236
+ spellCheck={false}
237
+ />
238
+ </div>
239
+ <div>
240
+ <label style={label} htmlFor="mcp-gateway-password">Admin password</label>
241
+ <input
242
+ id="mcp-gateway-password"
243
+ type="password"
244
+ style={input}
245
+ value={draft.password}
246
+ onChange={(e) => setDraft({ ...draft, password: e.target.value })}
247
+ placeholder={config?.hasPassword ? "•••••••• saved" : "Not set"}
248
+ autoComplete="current-password"
249
+ />
250
+ <CredentialNote
251
+ saved={config?.hasPassword}
252
+ fromEnv={config?.passwordFromEnv}
253
+ onClear={() => onClear("password")}
254
+ busy={busy === "clear"}
255
+ />
256
+ </div>
257
+ </div>
258
+ )}
259
+
260
+ {showToken && (
261
+ <div style={{ marginBottom: "16px" }}>
262
+ <label style={label} htmlFor="mcp-gateway-token">API token</label>
263
+ <input
264
+ id="mcp-gateway-token"
265
+ type="password"
266
+ style={input}
267
+ value={draft.apiToken}
268
+ onChange={(e) => setDraft({ ...draft, apiToken: e.target.value })}
269
+ placeholder={config?.hasApiToken ? "•••••••• saved" : "Not set"}
270
+ autoComplete="off"
271
+ spellCheck={false}
272
+ />
273
+ <CredentialNote
274
+ saved={config?.hasApiToken}
275
+ fromEnv={config?.apiTokenFromEnv}
276
+ onClear={() => onClear("apiToken")}
277
+ busy={busy === "clear"}
278
+ />
279
+ </div>
280
+ )}
281
+
282
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
283
+ <button style={button("primary")} onClick={onTest} disabled={!!busy}>
284
+ {busy === "test" ? "Testing…" : "Test connection"}
285
+ </button>
286
+ <button style={button()} onClick={onSave} disabled={!!busy}>
287
+ {busy === "save" ? "Saving…" : "Save"}
288
+ </button>
289
+ </div>
290
+ </div>
291
+
292
+ {error && (
293
+ <div role="alert" style={{ ...box, background: "#5c1a1a", borderColor: "#8a2a2a", color: "#fecaca", fontSize: "13px" }}>
294
+ {error}
295
+ </div>
296
+ )}
297
+
298
+ {result && <TestResult result={result} />}
299
+ </div>
300
+ );
301
+ }
302
+
303
+ function CredentialNote({ saved, fromEnv, onClear, busy }) {
304
+ if (!saved) {
305
+ return <small style={{ color: "#a0a0b0", fontSize: "11px" }}>Nothing saved yet.</small>;
306
+ }
307
+ if (fromEnv) {
308
+ return (
309
+ <small style={{ color: "#a0a0b0", fontSize: "11px" }}>
310
+ Provided by this deployment's environment. Type here to override it.
311
+ </small>
312
+ );
313
+ }
314
+ return (
315
+ <small style={{ color: "#a0a0b0", fontSize: "11px" }}>
316
+ Saved. Leave blank to keep it, or{" "}
317
+ <button
318
+ onClick={onClear}
319
+ disabled={busy}
320
+ style={{ background: "none", border: "none", color: "#93c5fd", cursor: "pointer", padding: 0, font: "inherit" }}
321
+ >
322
+ remove it
323
+ </button>
324
+ .
325
+ </small>
326
+ );
327
+ }
328
+
329
+ function TestResult({ result }) {
330
+ const good = result.ok;
331
+ return (
332
+ <div
333
+ role="status"
334
+ style={{
335
+ ...box,
336
+ borderColor: good ? "#166534" : "#8a2a2a",
337
+ background: good ? "#0f2417" : "#2a1414",
338
+ }}
339
+ >
340
+ <div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "8px" }}>
341
+ <span aria-hidden style={{ fontSize: "15px" }}>{good ? "✅" : "⚠️"}</span>
342
+ <strong style={{ color: good ? "#86efac" : "#fecaca", fontSize: "13px" }}>
343
+ {good ? "Connection works" : "Not connected"}
344
+ </strong>
345
+ </div>
346
+ <p style={{ margin: 0, color: "#d0d0d8", fontSize: "13px", lineHeight: 1.5 }}>{result.detail}</p>
347
+ <dl
348
+ style={{
349
+ display: "grid",
350
+ gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
351
+ gap: "8px 16px",
352
+ margin: "12px 0 0 0",
353
+ fontSize: "12px",
354
+ color: "#a0a0b0",
355
+ }}
356
+ >
357
+ <Fact term="Gateway" value={result.url} />
358
+ <Fact term="Reachable" value={result.reachable ? "yes" : "no"} />
359
+ <Fact
360
+ term="Authentication"
361
+ value={result.authRequired === false ? "disabled on gateway" : result.authenticated ? `signed in (${result.authModeUsed})` : "required"}
362
+ />
363
+ {result.serverCount != null && <Fact term="Servers visible" value={String(result.serverCount)} />}
364
+ </dl>
365
+ {(result.warnings || []).map((w) => (
366
+ <p key={w} style={{ margin: "8px 0 0 0", color: "#fcd34d", fontSize: "12px" }}>{w}</p>
367
+ ))}
368
+ </div>
369
+ );
370
+ }
371
+
372
+ function Fact({ term, value }) {
373
+ return (
374
+ <div>
375
+ <dt style={{ color: "#6b7280" }}>{term}</dt>
376
+ <dd style={{ margin: 0, color: "#d0d0d8", wordBreak: "break-all" }}>{value}</dd>
377
+ </div>
378
+ );
379
+ }
frontend/components/AdminTabs/mcp/GatewayHeader.jsx ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/GatewayHeader.jsx
2
+ // Top strip of the MCP Servers tab: gateway pill + roll-up counters.
3
+
4
+ import React from "react";
5
+
6
+ export default function GatewayHeader({
7
+ status,
8
+ installedCount,
9
+ enabledCount,
10
+ totalTools,
11
+ onRefresh,
12
+ onSync,
13
+ syncing,
14
+ }) {
15
+ const reachable = status?.gateway_reachable;
16
+ const dotColor = reachable ? "#10b981" : "#ef4444";
17
+ const dotLabel = reachable ? "Connected" : "Unreachable";
18
+ const gatewayUrl = status?.gateway_url || "—";
19
+
20
+ return (
21
+ <div
22
+ style={{
23
+ background: "#1a1b26",
24
+ border: "1px solid #2a2b36",
25
+ borderRadius: "8px",
26
+ padding: "16px 20px",
27
+ marginBottom: "16px",
28
+ display: "flex",
29
+ justifyContent: "space-between",
30
+ alignItems: "center",
31
+ flexWrap: "wrap",
32
+ gap: "12px",
33
+ }}
34
+ >
35
+ <div>
36
+ <div
37
+ style={{
38
+ display: "flex",
39
+ alignItems: "center",
40
+ gap: "8px",
41
+ marginBottom: "4px",
42
+ }}
43
+ >
44
+ <span
45
+ aria-hidden
46
+ style={{
47
+ width: "10px",
48
+ height: "10px",
49
+ background: dotColor,
50
+ borderRadius: "50%",
51
+ boxShadow: `0 0 8px ${dotColor}`,
52
+ }}
53
+ />
54
+ <strong style={{ fontSize: "14px", color: "#e0e0e7" }}>
55
+ MCP Context Forge — {dotLabel}
56
+ </strong>
57
+ {status?.plugin_enabled === false && (
58
+ <span
59
+ title="Set GITPILOT_MCP_ENABLED=true to let agents call MCP tools."
60
+ style={{
61
+ marginLeft: "8px",
62
+ padding: "2px 8px",
63
+ background: "#5c1a1a",
64
+ color: "#fecaca",
65
+ borderRadius: "4px",
66
+ fontSize: "11px",
67
+ fontWeight: 600,
68
+ }}
69
+ >
70
+ plugin disabled
71
+ </span>
72
+ )}
73
+ </div>
74
+ <div style={{ fontSize: "12px", color: "#a0a0b0" }}>
75
+ Gateway: <code>{gatewayUrl}</code>
76
+ </div>
77
+ </div>
78
+
79
+ <div
80
+ style={{
81
+ display: "flex",
82
+ gap: "20px",
83
+ alignItems: "center",
84
+ fontSize: "12px",
85
+ color: "#cdd0d8",
86
+ }}
87
+ >
88
+ <Counter label="Installed" value={installedCount} />
89
+ <Counter label="Enabled" value={enabledCount} />
90
+ <Counter label="Tools" value={totalTools} />
91
+ <button
92
+ onClick={onRefresh}
93
+ style={{
94
+ padding: "6px 12px",
95
+ background: "#252634",
96
+ color: "#e0e0e7",
97
+ border: "1px solid #3a3b4a",
98
+ borderRadius: "4px",
99
+ cursor: "pointer",
100
+ fontSize: "12px",
101
+ }}
102
+ >
103
+ Refresh
104
+ </button>
105
+ {onSync && (
106
+ <button
107
+ onClick={onSync}
108
+ disabled={!reachable || syncing}
109
+ title={
110
+ reachable
111
+ ? "Pull the server registry from MCP Context Forge"
112
+ : "Gateway unreachable — start MCP Context Forge first (make run)"
113
+ }
114
+ style={{
115
+ padding: "6px 12px",
116
+ background: reachable ? "#1e3a5f" : "#252634",
117
+ color: reachable ? "#93c5fd" : "#7a7d8a",
118
+ border: `1px solid ${reachable ? "#3B82F6" : "#3a3b4a"}`,
119
+ borderRadius: "4px",
120
+ cursor: reachable && !syncing ? "pointer" : "not-allowed",
121
+ fontSize: "12px",
122
+ fontWeight: 600,
123
+ opacity: !reachable || syncing ? 0.6 : 1,
124
+ }}
125
+ >
126
+ {syncing ? "Syncing…" : "Sync"}
127
+ </button>
128
+ )}
129
+ </div>
130
+ </div>
131
+ );
132
+ }
133
+
134
+ function Counter({ label, value }) {
135
+ return (
136
+ <div style={{ textAlign: "center" }}>
137
+ <div style={{ fontSize: "18px", fontWeight: 700, color: "#e0e0e7" }}>
138
+ {value ?? "—"}
139
+ </div>
140
+ <div style={{ fontSize: "11px", color: "#7a7d8a", textTransform: "uppercase" }}>
141
+ {label}
142
+ </div>
143
+ </div>
144
+ );
145
+ }
frontend/components/AdminTabs/mcp/ServerCard.jsx ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/ServerCard.jsx
2
+ // One installed MCP server. Collapsed shows summary + actions; expanded
3
+ // reveals the per-tool list with risk badges and individual toggles.
4
+
5
+ import React, { useState } from "react";
6
+ import ToolRow from "./ToolRow.jsx";
7
+
8
+ const RISK_PALETTE = {
9
+ low: { bg: "#0f3a26", border: "#1f5a3e", text: "#86efac" },
10
+ medium: { bg: "#3a2e0f", border: "#5a4a1f", text: "#fcd34d" },
11
+ high: { bg: "#3a0f0f", border: "#5a1f1f", text: "#fca5a5" },
12
+ };
13
+
14
+ export default function ServerCard({
15
+ server,
16
+ onEnable,
17
+ onDisable,
18
+ onUninstall,
19
+ onTest,
20
+ onToggleTool,
21
+ onForget,
22
+ }) {
23
+ const [expanded, setExpanded] = useState(false);
24
+ const [testResult, setTestResult] = useState(null);
25
+ const [testing, setTesting] = useState(false);
26
+
27
+ const handleTest = async () => {
28
+ setTesting(true);
29
+ try {
30
+ const result = await onTest();
31
+ setTestResult(result);
32
+ } finally {
33
+ setTesting(false);
34
+ }
35
+ };
36
+
37
+ const statusDot = server.enabled ? "#10b981" : "#6b7280";
38
+ const statusLabel = server.enabled ? "Enabled" : "Disabled";
39
+
40
+ // Risk roll-up shown next to the tool count.
41
+ const riskCounts = server.tools?.reduce(
42
+ (acc, t) => ({ ...acc, [t.risk]: (acc[t.risk] || 0) + 1 }),
43
+ {}
44
+ ) || {};
45
+
46
+ return (
47
+ <div
48
+ style={{
49
+ background: "#1a1b26",
50
+ border: "1px solid #2a2b36",
51
+ borderRadius: "8px",
52
+ overflow: "hidden",
53
+ }}
54
+ >
55
+ <div style={{ padding: "16px 20px" }}>
56
+ <div
57
+ style={{
58
+ display: "flex",
59
+ justifyContent: "space-between",
60
+ alignItems: "flex-start",
61
+ gap: "16px",
62
+ flexWrap: "wrap",
63
+ }}
64
+ >
65
+ <div style={{ flex: "1 1 320px", minWidth: 0 }}>
66
+ <div
67
+ style={{
68
+ display: "flex",
69
+ alignItems: "center",
70
+ gap: "8px",
71
+ marginBottom: "6px",
72
+ }}
73
+ >
74
+ <span
75
+ aria-hidden
76
+ style={{
77
+ width: "8px",
78
+ height: "8px",
79
+ background: statusDot,
80
+ borderRadius: "50%",
81
+ }}
82
+ />
83
+ <strong
84
+ style={{
85
+ fontSize: "15px",
86
+ color: "#e0e0e7",
87
+ overflow: "hidden",
88
+ textOverflow: "ellipsis",
89
+ whiteSpace: "nowrap",
90
+ }}
91
+ >
92
+ {server.id}
93
+ </strong>
94
+ <span
95
+ style={{
96
+ padding: "2px 8px",
97
+ background: server.enabled ? "#0f3a26" : "#252634",
98
+ color: server.enabled ? "#86efac" : "#a0a0b0",
99
+ borderRadius: "4px",
100
+ fontSize: "11px",
101
+ fontWeight: 600,
102
+ }}
103
+ >
104
+ {statusLabel}
105
+ </span>
106
+ {!server.is_known && (
107
+ <span
108
+ title="Custom server (not part of the GitPilot catalog)"
109
+ style={{
110
+ padding: "2px 8px",
111
+ background: "#1e3a5f",
112
+ color: "#93c5fd",
113
+ borderRadius: "4px",
114
+ fontSize: "11px",
115
+ }}
116
+ >
117
+ custom
118
+ </span>
119
+ )}
120
+ {server.orphan && (
121
+ <span
122
+ title="No longer registered in MCP Context Forge. Still works locally; click Forget to drop it, or re-attach it in Forge."
123
+ style={{
124
+ padding: "2px 8px",
125
+ background: "#3a2e0f",
126
+ color: "#fcd34d",
127
+ borderRadius: "4px",
128
+ fontSize: "11px",
129
+ fontWeight: 600,
130
+ }}
131
+ >
132
+ orphan
133
+ </span>
134
+ )}
135
+ {server.source === "forge-sync" && !server.orphan && (
136
+ <span
137
+ title="Added by the most recent forge sync."
138
+ style={{
139
+ padding: "2px 8px",
140
+ background: "#1e3a5f",
141
+ color: "#93c5fd",
142
+ borderRadius: "4px",
143
+ fontSize: "11px",
144
+ }}
145
+ >
146
+ via sync
147
+ </span>
148
+ )}
149
+ </div>
150
+ <div
151
+ style={{
152
+ fontSize: "12px",
153
+ color: "#a0a0b0",
154
+ marginBottom: "8px",
155
+ }}
156
+ >
157
+ {server.description || "—"}
158
+ </div>
159
+ <div
160
+ style={{
161
+ fontSize: "11px",
162
+ color: "#7a7d8a",
163
+ marginBottom: "8px",
164
+ wordBreak: "break-all",
165
+ }}
166
+ >
167
+ <code>{server.endpoint || "—"}</code>
168
+ </div>
169
+ <div style={{ display: "flex", gap: "6px", flexWrap: "wrap" }}>
170
+ {(server.tags || []).map((t) => (
171
+ <span
172
+ key={t}
173
+ style={{
174
+ padding: "2px 8px",
175
+ background: "#252634",
176
+ border: "1px solid #2a2b36",
177
+ borderRadius: "10px",
178
+ fontSize: "11px",
179
+ color: "#cdd0d8",
180
+ }}
181
+ >
182
+ {t}
183
+ </span>
184
+ ))}
185
+ </div>
186
+ </div>
187
+
188
+ <div
189
+ style={{
190
+ display: "flex",
191
+ flexDirection: "column",
192
+ gap: "8px",
193
+ alignItems: "flex-end",
194
+ }}
195
+ >
196
+ <div style={{ display: "flex", gap: "6px" }}>
197
+ {server.enabled ? (
198
+ <Btn variant="ghost" onClick={onDisable}>
199
+ Disable
200
+ </Btn>
201
+ ) : (
202
+ <Btn variant="primary" onClick={onEnable}>
203
+ Enable
204
+ </Btn>
205
+ )}
206
+ <Btn onClick={handleTest} disabled={testing}>
207
+ {testing ? "Testing…" : "Test"}
208
+ </Btn>
209
+ {onForget ? (
210
+ <Btn variant="danger" onClick={onForget}>
211
+ Forget
212
+ </Btn>
213
+ ) : (
214
+ <Btn variant="danger" onClick={onUninstall}>
215
+ Uninstall
216
+ </Btn>
217
+ )}
218
+ </div>
219
+ <div style={{ fontSize: "11px", color: "#a0a0b0" }}>
220
+ {server.tool_count} tool{server.tool_count === 1 ? "" : "s"}
221
+ {Object.entries(riskCounts).map(([risk, count]) => (
222
+ <span
223
+ key={risk}
224
+ title={`${count} ${risk}-risk tools`}
225
+ style={{
226
+ marginLeft: "6px",
227
+ padding: "1px 6px",
228
+ borderRadius: "10px",
229
+ background: RISK_PALETTE[risk]?.bg,
230
+ color: RISK_PALETTE[risk]?.text,
231
+ border: `1px solid ${RISK_PALETTE[risk]?.border}`,
232
+ fontSize: "10px",
233
+ }}
234
+ >
235
+ {count} {risk}
236
+ </span>
237
+ ))}
238
+ </div>
239
+ <button
240
+ onClick={() => setExpanded((v) => !v)}
241
+ style={{
242
+ padding: "4px 8px",
243
+ background: "transparent",
244
+ color: "#93c5fd",
245
+ border: "none",
246
+ cursor: "pointer",
247
+ fontSize: "12px",
248
+ }}
249
+ >
250
+ {expanded ? "Hide tools ▴" : "Show tools ▾"}
251
+ </button>
252
+ </div>
253
+ </div>
254
+
255
+ {testResult && (
256
+ <div
257
+ role="status"
258
+ style={{
259
+ marginTop: "12px",
260
+ padding: "8px 12px",
261
+ fontSize: "12px",
262
+ borderRadius: "6px",
263
+ background: testResult.ok ? "#0f3a26" : "#3a0f0f",
264
+ border: `1px solid ${testResult.ok ? "#1f5a3e" : "#5a1f1f"}`,
265
+ color: testResult.ok ? "#86efac" : "#fca5a5",
266
+ }}
267
+ >
268
+ {testResult.ok
269
+ ? "Healthy. Inspector confirmed the server is reachable and advertises its expected tools."
270
+ : `Failed: ${testResult.reason || testResult.error || "unknown error"}`}
271
+ </div>
272
+ )}
273
+ </div>
274
+
275
+ {expanded && (
276
+ <div
277
+ style={{
278
+ borderTop: "1px solid #2a2b36",
279
+ background: "#16171f",
280
+ padding: "8px 0",
281
+ }}
282
+ >
283
+ {server.tools?.length ? (
284
+ server.tools.map((t) => (
285
+ <ToolRow
286
+ key={t.name}
287
+ tool={t}
288
+ disabled={!server.enabled}
289
+ onToggle={(enabled) => onToggleTool(t.name, enabled)}
290
+ />
291
+ ))
292
+ ) : (
293
+ <div
294
+ style={{
295
+ padding: "12px 20px",
296
+ fontSize: "12px",
297
+ color: "#a0a0b0",
298
+ }}
299
+ >
300
+ No tools advertised by this server.
301
+ </div>
302
+ )}
303
+ </div>
304
+ )}
305
+ </div>
306
+ );
307
+ }
308
+
309
+ function Btn({ children, variant = "default", ...props }) {
310
+ const palettes = {
311
+ default: { bg: "#252634", color: "#e0e0e7", border: "#3a3b4a" },
312
+ primary: { bg: "#3B82F6", color: "#fff", border: "#3B82F6" },
313
+ ghost: { bg: "transparent", color: "#cdd0d8", border: "#3a3b4a" },
314
+ danger: { bg: "transparent", color: "#fca5a5", border: "#5a1f1f" },
315
+ };
316
+ const p = palettes[variant];
317
+ return (
318
+ <button
319
+ {...props}
320
+ style={{
321
+ padding: "6px 12px",
322
+ background: p.bg,
323
+ color: p.color,
324
+ border: `1px solid ${p.border}`,
325
+ borderRadius: "4px",
326
+ cursor: props.disabled ? "not-allowed" : "pointer",
327
+ fontSize: "12px",
328
+ opacity: props.disabled ? 0.6 : 1,
329
+ }}
330
+ >
331
+ {children}
332
+ </button>
333
+ );
334
+ }
frontend/components/AdminTabs/mcp/SyncReport.jsx ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/SyncReport.jsx
2
+ // Renders the SyncReport returned by POST /api/mcp/sync as a compact
3
+ // dismissible banner. Best practices: structured + colour-coded counts,
4
+ // truncated id lists with a "View" toggle, single primary "Dismiss"
5
+ // action, ARIA "status" so a screen reader announces the result once.
6
+
7
+ import React, { useState } from "react";
8
+
9
+ export default function SyncReport({ report, onDismiss }) {
10
+ const [open, setOpen] = useState(false);
11
+ if (!report) return null;
12
+
13
+ const { added = [], kept = [], orphaned = [], forge_unreachable, error } = report;
14
+
15
+ if (forge_unreachable) {
16
+ return (
17
+ <Banner
18
+ kind="bad"
19
+ title="Sync failed: forge unreachable"
20
+ body={error || "Could not reach MCP Context Forge."}
21
+ onDismiss={onDismiss}
22
+ />
23
+ );
24
+ }
25
+
26
+ const noChanges = added.length === 0 && orphaned.length === 0;
27
+
28
+ return (
29
+ <Banner
30
+ kind={noChanges ? "info" : added.length ? "ok" : "warn"}
31
+ title={
32
+ noChanges
33
+ ? "Sync complete — no changes"
34
+ : `Sync complete · +${added.length} added · ${kept.length} refreshed · ${orphaned.length} orphan`
35
+ }
36
+ onDismiss={onDismiss}
37
+ footer={
38
+ <button
39
+ onClick={() => setOpen((v) => !v)}
40
+ style={{
41
+ background: "transparent",
42
+ border: "none",
43
+ color: "#93c5fd",
44
+ cursor: "pointer",
45
+ fontSize: 12,
46
+ padding: 0,
47
+ }}
48
+ >
49
+ {open ? "Hide details ▴" : "View details ▾"}
50
+ </button>
51
+ }
52
+ >
53
+ {open && (
54
+ <div
55
+ style={{ fontSize: 12, color: "#cdd0d8", marginTop: 6, lineHeight: 1.5 }}
56
+ >
57
+ {added.length > 0 && (
58
+ <Detail label="Added" items={added} colour="#86efac" />
59
+ )}
60
+ {kept.length > 0 && (
61
+ <Detail label="Refreshed" items={kept} colour="#93c5fd" />
62
+ )}
63
+ {orphaned.length > 0 && (
64
+ <Detail
65
+ label="Orphaned"
66
+ items={orphaned}
67
+ colour="#fcd34d"
68
+ hint="Still works locally — Forge no longer advertises them. Use 'Forget' to drop, or re-attach them in Forge."
69
+ />
70
+ )}
71
+ {report.correlation_id && (
72
+ <div style={{ marginTop: 6, color: "#7a7d8a" }}>
73
+ correlation_id: <code>{report.correlation_id}</code>
74
+ </div>
75
+ )}
76
+ </div>
77
+ )}
78
+ </Banner>
79
+ );
80
+ }
81
+
82
+ function Banner({ kind, title, body, footer, onDismiss, children }) {
83
+ const palette = {
84
+ ok: { bg: "#0f3a26", border: "#1f5a3e", text: "#86efac" },
85
+ info: { bg: "#1e3a5f", border: "#3B82F6", text: "#93c5fd" },
86
+ warn: { bg: "#3a2e0f", border: "#5a4a1f", text: "#fcd34d" },
87
+ bad: { bg: "#3a0f0f", border: "#5a1f1f", text: "#fca5a5" },
88
+ }[kind] || { bg: "#1a1b26", border: "#2a2b36", text: "#cdd0d8" };
89
+
90
+ return (
91
+ <div
92
+ role="status"
93
+ aria-live="polite"
94
+ style={{
95
+ background: palette.bg,
96
+ border: `1px solid ${palette.border}`,
97
+ borderRadius: 6,
98
+ padding: "10px 14px",
99
+ marginBottom: 12,
100
+ color: palette.text,
101
+ fontSize: 13,
102
+ display: "flex",
103
+ flexDirection: "column",
104
+ gap: 4,
105
+ }}
106
+ >
107
+ <div
108
+ style={{
109
+ display: "flex",
110
+ justifyContent: "space-between",
111
+ alignItems: "center",
112
+ gap: 8,
113
+ }}
114
+ >
115
+ <strong>{title}</strong>
116
+ <button
117
+ onClick={onDismiss}
118
+ aria-label="Dismiss"
119
+ style={{
120
+ background: "transparent",
121
+ border: "none",
122
+ color: palette.text,
123
+ cursor: "pointer",
124
+ fontSize: 16,
125
+ lineHeight: 1,
126
+ padding: 0,
127
+ }}
128
+ >
129
+ ×
130
+ </button>
131
+ </div>
132
+ {body && <div>{body}</div>}
133
+ {children}
134
+ {footer && <div>{footer}</div>}
135
+ </div>
136
+ );
137
+ }
138
+
139
+ function Detail({ label, items, colour, hint }) {
140
+ return (
141
+ <div style={{ marginTop: 4 }}>
142
+ <span style={{ color: colour, fontWeight: 600 }}>{label}:</span>{" "}
143
+ <span>
144
+ {items.slice(0, 6).join(", ")}
145
+ {items.length > 6 ? ` … (+${items.length - 6} more)` : ""}
146
+ </span>
147
+ {hint && (
148
+ <div style={{ marginTop: 2, fontSize: 11, color: "#7a7d8a" }}>{hint}</div>
149
+ )}
150
+ </div>
151
+ );
152
+ }
frontend/components/AdminTabs/mcp/ToolRow.jsx ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/AdminTabs/mcp/ToolRow.jsx
2
+ // One row inside an expanded ServerCard. Tool name, risk badge,
3
+ // "used by" agent chips, and a per-tool enable toggle.
4
+
5
+ import React from "react";
6
+
7
+ const RISK_PALETTE = {
8
+ low: { bg: "#0f3a26", text: "#86efac", label: "low" },
9
+ medium: { bg: "#3a2e0f", text: "#fcd34d", label: "med" },
10
+ high: { bg: "#3a0f0f", text: "#fca5a5", label: "high" },
11
+ };
12
+
13
+ export default function ToolRow({ tool, disabled, onToggle }) {
14
+ const risk = RISK_PALETTE[tool.risk] || RISK_PALETTE.low;
15
+
16
+ // Destructive tools cannot be toggled on by the UI; the backend's
17
+ // PolicyEngine will reject a toggle PUT anyway, but disabling the
18
+ // control surfaces the constraint up front.
19
+ const lockEnable = tool.destructive;
20
+
21
+ return (
22
+ <div
23
+ style={{
24
+ display: "flex",
25
+ alignItems: "center",
26
+ justifyContent: "space-between",
27
+ gap: "12px",
28
+ padding: "8px 20px",
29
+ borderBottom: "1px solid #1a1b26",
30
+ }}
31
+ >
32
+ <div style={{ flex: "1 1 auto", minWidth: 0 }}>
33
+ <div
34
+ style={{
35
+ display: "flex",
36
+ alignItems: "center",
37
+ gap: "8px",
38
+ marginBottom: "2px",
39
+ }}
40
+ >
41
+ <code
42
+ style={{
43
+ fontSize: "12px",
44
+ color: "#e0e0e7",
45
+ overflow: "hidden",
46
+ textOverflow: "ellipsis",
47
+ whiteSpace: "nowrap",
48
+ }}
49
+ >
50
+ {tool.name}
51
+ </code>
52
+ <span
53
+ title={`risk: ${tool.risk}`}
54
+ style={{
55
+ padding: "1px 6px",
56
+ borderRadius: "10px",
57
+ background: risk.bg,
58
+ color: risk.text,
59
+ fontSize: "10px",
60
+ fontWeight: 600,
61
+ textTransform: "uppercase",
62
+ }}
63
+ >
64
+ {risk.label}
65
+ </span>
66
+ </div>
67
+ <div
68
+ style={{
69
+ display: "flex",
70
+ gap: "4px",
71
+ flexWrap: "wrap",
72
+ fontSize: "10px",
73
+ color: "#7a7d8a",
74
+ }}
75
+ >
76
+ {(tool.used_by || []).length > 0 && <span>used by</span>}
77
+ {(tool.used_by || []).map((agent) => (
78
+ <span
79
+ key={agent}
80
+ style={{
81
+ padding: "1px 6px",
82
+ borderRadius: "10px",
83
+ background: "#1e3a5f",
84
+ color: "#93c5fd",
85
+ }}
86
+ >
87
+ {agent}
88
+ </span>
89
+ ))}
90
+ </div>
91
+ </div>
92
+
93
+ <Toggle
94
+ checked={tool.enabled}
95
+ disabled={disabled || lockEnable}
96
+ title={
97
+ lockEnable
98
+ ? "Destructive tool — blocked by policy"
99
+ : disabled
100
+ ? "Enable the server first"
101
+ : tool.enabled
102
+ ? "Disable this tool for GitPilot agents"
103
+ : "Allow GitPilot agents to call this tool"
104
+ }
105
+ onChange={(checked) => onToggle(checked)}
106
+ />
107
+ </div>
108
+ );
109
+ }
110
+
111
+ function Toggle({ checked, disabled, title, onChange }) {
112
+ return (
113
+ <label title={title} style={{ display: "inline-flex", alignItems: "center" }}>
114
+ <input
115
+ type="checkbox"
116
+ checked={!!checked}
117
+ disabled={disabled}
118
+ onChange={(e) => onChange(e.target.checked)}
119
+ style={{ position: "absolute", opacity: 0, pointerEvents: "none" }}
120
+ aria-label={title}
121
+ />
122
+ <span
123
+ style={{
124
+ width: "32px",
125
+ height: "18px",
126
+ borderRadius: "9px",
127
+ background: checked && !disabled ? "#3B82F6" : "#2a2b36",
128
+ position: "relative",
129
+ transition: "background 0.15s",
130
+ opacity: disabled ? 0.5 : 1,
131
+ cursor: disabled ? "not-allowed" : "pointer",
132
+ }}
133
+ >
134
+ <span
135
+ style={{
136
+ width: "14px",
137
+ height: "14px",
138
+ borderRadius: "50%",
139
+ background: "#fff",
140
+ position: "absolute",
141
+ top: "2px",
142
+ left: checked ? "16px" : "2px",
143
+ transition: "left 0.15s",
144
+ }}
145
+ />
146
+ </span>
147
+ </label>
148
+ );
149
+ }
frontend/components/AssistantMessage.jsx ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from "react";
2
+ import { apiUrl } from "../utils/api.js";
3
+ import PlanView from "./PlanView.jsx";
4
+ import RunnableCodeBlock, { splitFences } from "./RunnableCodeBlock.jsx";
5
+ import ExecutionPlanCard, { approveAndBuildRunBody } from "./ExecutionPlanCard.jsx";
6
+
7
+ export default function AssistantMessage({
8
+ answer,
9
+ plan,
10
+ executionLog,
11
+ planStatus,
12
+ owner,
13
+ repo,
14
+ onApproveExecution,
15
+ nextActions,
16
+ relatedPlan,
17
+ diff,
18
+ branch,
19
+ }) {
20
+ // Approval-first sandbox: when the planner returns an execution_plan,
21
+ // render the green ExecutionPlanCard instead of the orange Action Plan.
22
+ const executionPlan = plan?.execution_plan || null;
23
+ const [runResult, setRunResult] = useState(null);
24
+ const [runError, setRunError] = useState(null);
25
+ const [runBusy, setRunBusy] = useState(false);
26
+
27
+ const approveExecution = async (ep) => {
28
+ if (onApproveExecution) {
29
+ onApproveExecution(ep, plan);
30
+ return;
31
+ }
32
+ setRunBusy(true);
33
+ setRunError(null);
34
+ setRunResult(null);
35
+ try {
36
+ const body = await approveAndBuildRunBody(ep);
37
+ const res = await fetch(apiUrl("/api/sandbox/run"), {
38
+ method: "POST", headers: { "Content-Type": "application/json" },
39
+ body: JSON.stringify(body),
40
+ });
41
+ const data = await res.json();
42
+ if (!res.ok) setRunError(data.detail || `HTTP ${res.status}`);
43
+ else setRunResult(data);
44
+ } catch (e) { setRunError(e.message); }
45
+ finally { setRunBusy(false); }
46
+ };
47
+
48
+ const hasFileActions = plan?.steps?.some((s) => s.files?.length > 0);
49
+ const answerText = typeof answer === "string" ? answer.trim() : "";
50
+ // Suppress the answer prose when it would just duplicate what the
51
+ // plan card or success receipt already says.
52
+ const showAnswerProse =
53
+ answerText &&
54
+ !executionLog &&
55
+ !(plan && hasFileActions && !executionPlan && answerText === plan.summary);
56
+
57
+ return (
58
+ <div className="chat-message-ai assistant-card">
59
+ {/* Free-form answer prose. Rendered without a section header so
60
+ short answers feel like a chat reply, not a debug log. */}
61
+ {showAnswerProse && (
62
+ <div className="assistant-answer">
63
+ {splitFences(answerText).map((seg, i) =>
64
+ seg.type === "code" ? (
65
+ <RunnableCodeBlock
66
+ key={i}
67
+ language={seg.language}
68
+ code={seg.code}
69
+ owner={owner}
70
+ repo={repo}
71
+ />
72
+ ) : (
73
+ <p key={i} className="assistant-answer__p">
74
+ {seg.value}
75
+ </p>
76
+ ),
77
+ )}
78
+ </div>
79
+ )}
80
+
81
+ {/* Sandbox approval card. */}
82
+ {executionPlan && (
83
+ <div className="assistant-block">
84
+ <ExecutionPlanCard
85
+ plan={executionPlan}
86
+ variant="full"
87
+ busy={runBusy}
88
+ onApprove={approveExecution}
89
+ onCancel={() => { /* no-op */ }}
90
+ />
91
+ {runError && (
92
+ <div className="assistant-run-error">Run error: {runError}</div>
93
+ )}
94
+ {runResult && (
95
+ <pre className="assistant-run-output">
96
+ {runResult.stdout || runResult.stderr || "(no output)"}
97
+ </pre>
98
+ )}
99
+ </div>
100
+ )}
101
+
102
+ {/* Proposed execution plan — only when there are file changes
103
+ and no execution log is present yet. */}
104
+ {plan && hasFileActions && !executionPlan && !executionLog && (
105
+ <div className="assistant-block">
106
+ <PlanView plan={plan} planStatus={planStatus} />
107
+ </div>
108
+ )}
109
+
110
+ {/* Completed execution receipt. */}
111
+ {executionLog && (
112
+ <SuccessReceipt
113
+ executionLog={executionLog}
114
+ relatedPlan={relatedPlan}
115
+ owner={owner}
116
+ repo={repo}
117
+ branch={branch}
118
+ diff={diff}
119
+ nextActions={nextActions}
120
+ />
121
+ )}
122
+
123
+ {/* Next actions when there is no execution log (e.g. simple answers). */}
124
+ {!executionLog && Array.isArray(nextActions) && nextActions.length > 0 && (
125
+ <div className="assistant-next-row">
126
+ {nextActions.map((a, i) => (
127
+ <NextActionButton key={i} action={a} />
128
+ ))}
129
+ </div>
130
+ )}
131
+ </div>
132
+ );
133
+ }
134
+
135
+ function NextActionButton({ action }) {
136
+ const onClick = () => {
137
+ if (action.kind === "run_file" && action.payload?.file) {
138
+ window.dispatchEvent(
139
+ new CustomEvent("gitpilot:run-file", {
140
+ detail: { path: action.payload.file },
141
+ }),
142
+ );
143
+ } else if (action.kind === "open_workspace" && action.payload?.file) {
144
+ window.dispatchEvent(
145
+ new CustomEvent("gitpilot:open-workspace", {
146
+ detail: { path: action.payload.file },
147
+ }),
148
+ );
149
+ } else if (action.kind === "open_in_canvas" && action.payload?.file) {
150
+ window.dispatchEvent(
151
+ new CustomEvent("gitpilot:open-in-canvas", {
152
+ detail: { path: action.payload.file },
153
+ }),
154
+ );
155
+ }
156
+ };
157
+
158
+ const isPrimary = action.kind === "run_file";
159
+ return (
160
+ <button
161
+ type="button"
162
+ onClick={onClick}
163
+ className={
164
+ "next-action-btn" +
165
+ (isPrimary ? " next-action-btn--primary" : " next-action-btn--ghost")
166
+ }
167
+ >
168
+ <span className="next-action-btn__glyph" aria-hidden="true">
169
+ {action.kind === "run_file"
170
+ ? "▶"
171
+ : action.kind === "open_workspace"
172
+ ? "📂"
173
+ : "⊞"}
174
+ </span>
175
+ {action.label}
176
+ </button>
177
+ );
178
+ }
179
+
180
+ function SuccessReceipt({
181
+ executionLog,
182
+ relatedPlan,
183
+ owner,
184
+ repo,
185
+ branch,
186
+ diff,
187
+ nextActions,
188
+ }) {
189
+ const steps = executionLog?.steps || [];
190
+ const totalSteps = steps.length;
191
+
192
+ // Aggregate every file action across steps so "Files changed (N)" can
193
+ // be a single top-level section instead of per-step duplication.
194
+ const allFiles = [];
195
+ if (relatedPlan?.steps?.length) {
196
+ for (const s of relatedPlan.steps) {
197
+ for (const f of s.files || []) {
198
+ if (f.action !== "INDEX") allFiles.push(f);
199
+ }
200
+ }
201
+ }
202
+ const totalDuration = steps.reduce((acc, s) => {
203
+ return acc + (s.executions || []).reduce(
204
+ (a, ex) => a + (typeof ex.duration_ms === "number" ? ex.duration_ms : 0),
205
+ 0,
206
+ );
207
+ }, 0);
208
+
209
+ // Short headline outcome lines (max 2): "Created X", "Modified Y".
210
+ const headlines = [];
211
+ for (const action of ["CREATE", "MODIFY", "DELETE"]) {
212
+ for (const f of allFiles) {
213
+ if (f.action === action && headlines.length < 2) {
214
+ headlines.push({ verb: verbFor(action), path: f.path });
215
+ }
216
+ }
217
+ }
218
+
219
+ // The bottom-bar already owns Create PR. Only show a pointer text here
220
+ // when there is a meaningful PR path (branch + file changes).
221
+ const hasPRPath = Boolean(branch && allFiles.length > 0);
222
+
223
+ // Filter out create-PR-style next-actions (handled by bottom bar);
224
+ // keep ▶ run / 📂 open as inline buttons.
225
+ const inlineNextActions = (nextActions || []).filter(
226
+ (a) => a && a.kind && a.kind !== "create_pr",
227
+ );
228
+
229
+ const hasTechLog =
230
+ totalDuration > 0 ||
231
+ steps.some((s) => s.summary || (s.executions || []).length > 0);
232
+
233
+ return (
234
+ <div className="success-card">
235
+ <div className="success-card__head">
236
+ <div className="success-card__icon" aria-hidden="true">
237
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none"
238
+ stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"
239
+ strokeLinejoin="round">
240
+ <polyline points="20 6 9 17 4 12" />
241
+ </svg>
242
+ </div>
243
+ <div className="success-card__head-text">
244
+ <div className="success-card__title">Execution completed</div>
245
+ <div className="success-card__subtitle">
246
+ Successfully executed {totalSteps} step{totalSteps === 1 ? "" : "s"}
247
+ <span className="success-card__dot">·</span>
248
+ <span className="success-card__time-inline">Just now</span>
249
+ </div>
250
+ </div>
251
+ <span className="exec-status-badge exec-status-badge--ok success-card__badge">
252
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
253
+ stroke="currentColor" strokeWidth="3" strokeLinecap="round"
254
+ strokeLinejoin="round" aria-hidden="true">
255
+ <polyline points="20 6 9 17 4 12" />
256
+ </svg>
257
+ Executed
258
+ </span>
259
+ </div>
260
+
261
+ {headlines.length > 0 && (
262
+ <ul className="success-headlines">
263
+ {headlines.map((h, i) => (
264
+ <li key={i} className="success-headline">
265
+ <span className="success-headline__verb">{h.verb}</span>
266
+ <code className="success-headline__path">{h.path}</code>
267
+ </li>
268
+ ))}
269
+ </ul>
270
+ )}
271
+
272
+ {(owner || branch) && (
273
+ <div className="success-meta">
274
+ {owner && repo && (
275
+ <div className="success-meta__item">
276
+ <span className="success-meta__label">Repository</span>
277
+ <span className="success-meta__value">{owner}/{repo}</span>
278
+ </div>
279
+ )}
280
+ {branch && (
281
+ <div className="success-meta__item">
282
+ <span className="success-meta__label">Branch</span>
283
+ <span className="success-meta__value success-meta__value--mono">
284
+ {branch}
285
+ </span>
286
+ </div>
287
+ )}
288
+ </div>
289
+ )}
290
+
291
+ {allFiles.length > 0 && (
292
+ <div className="success-files">
293
+ <div className="success-files__label">
294
+ Files changed ({allFiles.length})
295
+ </div>
296
+ <ul className="success-action-list">
297
+ {allFiles.map((f, i) => (
298
+ <li key={i} className="success-action-row">
299
+ <span className="success-action__check" aria-hidden="true">✓</span>
300
+ <span
301
+ className={`exec-badge exec-badge--${f.action.toLowerCase()}`}
302
+ >
303
+ {f.action}
304
+ </span>
305
+ <code className="success-action__path">{f.path}</code>
306
+ <span className="success-action__meta">
307
+ {actionMeta(f.action)}
308
+ </span>
309
+ </li>
310
+ ))}
311
+ </ul>
312
+ </div>
313
+ )}
314
+
315
+ {inlineNextActions.length > 0 && (
316
+ <div className="success-next-row">
317
+ {inlineNextActions.map((a, i) => (
318
+ <NextActionButton key={i} action={a} />
319
+ ))}
320
+ </div>
321
+ )}
322
+
323
+ {hasTechLog && (
324
+ <details className="success-techlog">
325
+ <summary>
326
+ View execution log
327
+ {totalDuration > 0 && (
328
+ <span className="success-techlog__time">
329
+ · {(totalDuration / 1000).toFixed(1)}s
330
+ </span>
331
+ )}
332
+ </summary>
333
+ {steps.map((s) => (
334
+ <div key={s.step_number} className="success-techlog__step">
335
+ <div className="success-techlog__step-title">
336
+ Step {s.step_number}
337
+ {totalSteps > 1 ? ` of ${totalSteps}` : ""}
338
+ </div>
339
+ {s.summary && (
340
+ <pre className="success-techlog__pre">{s.summary}</pre>
341
+ )}
342
+ {Array.isArray(s.executions) && s.executions.map((ex, i) => (
343
+ <ExecutionCard key={i} ex={ex} />
344
+ ))}
345
+ </div>
346
+ ))}
347
+ </details>
348
+ )}
349
+
350
+ {hasPRPath && (
351
+ <div className="success-hint">
352
+ Next: Create a pull request when ready.
353
+ </div>
354
+ )}
355
+ </div>
356
+ );
357
+ }
358
+
359
+ function actionMeta(action) {
360
+ switch (action) {
361
+ case "READ": return "Read-only";
362
+ case "CREATE": return "Created";
363
+ case "MODIFY": return "Modified";
364
+ case "DELETE": return "Deleted";
365
+ case "INDEX": return "Indexed";
366
+ default: return "";
367
+ }
368
+ }
369
+
370
+ function verbFor(action) {
371
+ switch (action) {
372
+ case "CREATE": return "Created";
373
+ case "MODIFY": return "Modified";
374
+ case "DELETE": return "Deleted";
375
+ default: return action;
376
+ }
377
+ }
378
+
379
+ function ExecutionCard({ ex }) {
380
+ const status = ex.status || "pending";
381
+ const statusClass =
382
+ status === "completed" ? "exec-card-inner--ok" :
383
+ status === "failed" ? "exec-card-inner--bad" :
384
+ status === "skipped" ? "exec-card-inner--warn" :
385
+ "exec-card-inner--info";
386
+ return (
387
+ <div className={`exec-card-inner ${statusClass}`}>
388
+ <div className="exec-card-inner__head">
389
+ <div>
390
+ <strong className="exec-card-inner__path">{ex.path}</strong>
391
+ {ex.sandbox && (
392
+ <span className="exec-card-inner__sandbox">· {ex.sandbox}</span>
393
+ )}
394
+ </div>
395
+ <span className="exec-card-inner__status">
396
+ {status === "completed" && `Exit ${ex.exit_code} · ${ex.duration_ms} ms`}
397
+ {status === "failed" && (typeof ex.exit_code === "number"
398
+ ? `Failed · exit ${ex.exit_code}` : "Failed")}
399
+ {status === "skipped" && "Skipped"}
400
+ {status === "pending" && "Running…"}
401
+ </span>
402
+ </div>
403
+ {ex.command && (
404
+ <div className="exec-card-inner__cmd">$ {ex.command}</div>
405
+ )}
406
+ {ex.stdout && (
407
+ <details open style={{ marginTop: 4 }}>
408
+ <summary className="exec-card-inner__stdout-summary">stdout</summary>
409
+ <pre className="exec-card-inner__pre">{ex.stdout}</pre>
410
+ </details>
411
+ )}
412
+ {ex.stderr && (
413
+ <details open={status === "failed"} style={{ marginTop: 4 }}>
414
+ <summary className="exec-card-inner__stderr-summary">stderr</summary>
415
+ <pre className="exec-card-inner__pre exec-card-inner__pre--err">
416
+ {ex.stderr}
417
+ </pre>
418
+ </details>
419
+ )}
420
+ {ex.error && !ex.stderr && (
421
+ <div className="exec-card-inner__error">{ex.error}</div>
422
+ )}
423
+ {ex.reason && (
424
+ <div className="exec-card-inner__reason">{ex.reason}</div>
425
+ )}
426
+ </div>
427
+ );
428
+ }
frontend/components/AuthPage.jsx ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useRef, useState } from "react";
2
+ import "./auth.css";
3
+ import { resolveBackendUrl } from "../utils/backend.js";
4
+ import { getSessionToken, setSessionToken } from "../utils/api.js";
5
+
6
+ // Premium /auth — GitPilot account (email/password) + "Continue with GitHub".
7
+ // GitPilot account = who you are; GitHub = repository access (the device flow).
8
+ //
9
+ // One layout for every state: <div.gp-auth> (full-viewport background) wraps a
10
+ // single <gp-auth-card>. Sign in, create account, and the GitHub authorization
11
+ // step all render INSIDE that same card — no nested wrappers, no second
12
+ // rectangle. The GitHub step shows "Connecting to GitHub…" with a spinner and
13
+ // then either redirects (web OAuth) or shows the device code in place.
14
+
15
+ const api = (path) => `${resolveBackendUrl()}${path}`;
16
+
17
+ // The account session also travels in a header (not just the cross-site cookie)
18
+ // so email/password sign-in survives the Vercel-frontend / HF-backend split.
19
+ function sessionHeaders() {
20
+ const t = getSessionToken();
21
+ return t ? { "X-GitPilot-Session": t } : {};
22
+ }
23
+
24
+ // Persist the portable session token returned by account endpoints.
25
+ function rememberSession(data) {
26
+ if (data && data.session_token) setSessionToken(data.session_token);
27
+ }
28
+
29
+ async function post(path, body) {
30
+ const r = await fetch(api(path), {
31
+ method: "POST",
32
+ headers: { "content-type": "application/json", ...sessionHeaders() },
33
+ credentials: "include", // also send/receive the session cookie when same-origin
34
+ body: JSON.stringify(body || {}),
35
+ });
36
+ let data = {};
37
+ try { data = await r.json(); } catch { /* empty body */ }
38
+ return { ok: r.ok, status: r.status, data };
39
+ }
40
+
41
+ async function getJSON(path, opts = {}) {
42
+ const r = await fetch(api(path), {
43
+ credentials: "include",
44
+ ...opts,
45
+ headers: { ...sessionHeaders(), ...(opts.headers || {}) },
46
+ });
47
+ let data = {};
48
+ try { data = await r.json(); } catch { /* empty body */ }
49
+ return { ok: r.ok, status: r.status, data };
50
+ }
51
+
52
+ const GithubMark = () => (
53
+ <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.1.68-.22.68-.49v-1.7c-2.78.62-3.37-1.21-3.37-1.21-.45-1.18-1.11-1.49-1.11-1.49-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.89 1.56 2.34 1.11 2.91.85.09-.66.35-1.11.63-1.36-2.22-.26-4.55-1.14-4.55-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.7 0 0 .84-.28 2.75 1.05a9.3 9.3 0 0 1 5 0c1.91-1.33 2.75-1.05 2.75-1.05.55 1.4.2 2.44.1 2.7.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9v2.82c0 .27.18.6.69.49A10.02 10.02 0 0 0 22 12.25C22 6.58 17.52 2 12 2z" /></svg>
54
+ );
55
+ const Eye = ({ off }) => (off
56
+ ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.5 18.5 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19M1 1l22 22"/></svg>
57
+ : <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
58
+ );
59
+
60
+ export default function AuthPage({ onAuthenticated, backendReady = false, connectMode = false }) {
61
+ const params = new URLSearchParams(window.location.search);
62
+ const isVerifyLink =
63
+ !!params.get("token") && window.location.pathname.includes("verify-email");
64
+ // connectMode / ?view=github: jump straight to the GitHub device flow (used by
65
+ // the in-workspace "Connect GitHub" button for already-signed-in accounts).
66
+ const wantsGithub = !!params.get("code") || params.get("view") === "github" || connectMode;
67
+ const [mode, setMode] = useState(params.get("mode") === "signup" ? "signup" : "signin");
68
+ // Pick the opening view: GitHub flow → github; an email confirmation link
69
+ // (?token= on /verify-email) → verify; otherwise email.
70
+ const [view, setView] = useState(
71
+ wantsGithub ? "github" : isVerifyLink ? "verify" : "email"
72
+ ); // "email" | "github" | "verify"
73
+ const [email, setEmail] = useState("");
74
+ const [password, setPassword] = useState("");
75
+ const [name, setName] = useState("");
76
+ const [showPw, setShowPw] = useState(false);
77
+ const [busy, setBusy] = useState(false);
78
+ const [note, setNote] = useState(null); // {kind, text}
79
+
80
+ // GitHub authorization state (rendered inside the same card)
81
+ const [ghPhase, setGhPhase] = useState("connecting"); // "connecting" | "device" | "error"
82
+ const [ghDevice, setGhDevice] = useState(null); // {user_code, verification_uri, ...}
83
+ const [ghError, setGhError] = useState("");
84
+ const pollTimer = useRef(null);
85
+ const stopPolling = useRef(false);
86
+ const ghStarted = useRef(false);
87
+
88
+ // Email-verification state (dedicated screen, not a silent redirect)
89
+ const [verifyPhase, setVerifyPhase] = useState("verifying"); // "verifying" | "success" | "error"
90
+ const [verifyMsg, setVerifyMsg] = useState("");
91
+ const [verifyUser, setVerifyUser] = useState(null);
92
+ const [resendBusy, setResendBusy] = useState(false);
93
+ const verifyStarted = useRef(false);
94
+
95
+ // Exchange the email-confirmation token once, then show success/error in place.
96
+ useEffect(() => {
97
+ if (view !== "verify" || verifyStarted.current) return;
98
+ verifyStarted.current = true;
99
+ const token = params.get("token");
100
+ setVerifyPhase("verifying");
101
+ (async () => {
102
+ const r = await post("/api/account/verify-email", { token });
103
+ // Strip the token from the URL so a refresh can't replay a stale link.
104
+ window.history.replaceState({}, document.title, "/auth");
105
+ if (r.ok) {
106
+ rememberSession(r.data);
107
+ setVerifyUser(r.data);
108
+ setVerifyPhase("success");
109
+ } else {
110
+ setVerifyMsg(r.data.detail || "This confirmation link is invalid or has expired.");
111
+ setVerifyPhase("error");
112
+ }
113
+ })();
114
+ // eslint-disable-next-line react-hooks/exhaustive-deps
115
+ }, [view]);
116
+
117
+ const resendVerification = async () => {
118
+ if (!email) { setNote({ kind: "err", text: "Enter your email to resend the link." }); return; }
119
+ setResendBusy(true);
120
+ try {
121
+ await post("/api/account/resend-verification", { email });
122
+ setNote({ kind: "ok", text: "If your account needs confirmation, a new link is on its way." });
123
+ } finally {
124
+ setResendBusy(false);
125
+ }
126
+ };
127
+
128
+ // ── GitHub authorization (device + web OAuth), all inside the same card ──
129
+ function finishGitHub(data) {
130
+ stopPolling.current = true;
131
+ if (pollTimer.current) clearTimeout(pollTimer.current);
132
+ if (!data || !data.access_token || !data.user) {
133
+ setGhPhase("error");
134
+ setGhError("GitHub returned an incomplete session. Please try again.");
135
+ return;
136
+ }
137
+ try {
138
+ localStorage.setItem("github_token", data.access_token);
139
+ localStorage.setItem("github_user", JSON.stringify(data.user));
140
+ } catch { /* storage may be blocked */ }
141
+ if (typeof onAuthenticated === "function") {
142
+ onAuthenticated({ access_token: data.access_token, user: data.user });
143
+ }
144
+ // Linked from inside the workspace → reload into it with the new GitHub token.
145
+ if (connectMode) {
146
+ window.location.href = "/";
147
+ }
148
+ }
149
+
150
+ async function pollDevice(deviceCode, interval) {
151
+ if (stopPolling.current) return;
152
+ try {
153
+ const r = await fetch(api("/api/auth/device/poll"), {
154
+ method: "POST",
155
+ headers: { "Content-Type": "application/json" },
156
+ body: JSON.stringify({ device_code: deviceCode }),
157
+ });
158
+ if (r.status === 200) { finishGitHub(await r.json()); return; }
159
+ if (r.status === 202) {
160
+ pollTimer.current = setTimeout(() => pollDevice(deviceCode, interval), interval * 1000);
161
+ return;
162
+ }
163
+ const err = await r.json().catch(() => ({ error: "Unknown polling error" }));
164
+ if (err.error === "slow_down") {
165
+ pollTimer.current = setTimeout(() => pollDevice(deviceCode, interval + 5), (interval + 5) * 1000);
166
+ return;
167
+ }
168
+ throw new Error(err.error || `Polling failed: ${r.status}`);
169
+ } catch (e) {
170
+ if (!stopPolling.current) { setGhPhase("error"); setGhError(e.message || "Could not reach GitHub."); }
171
+ }
172
+ }
173
+
174
+ async function startGitHub() {
175
+ setGhPhase("connecting");
176
+ setGhError("");
177
+ setGhDevice(null);
178
+ stopPolling.current = false;
179
+
180
+ // If we returned from a web OAuth redirect, exchange the code first.
181
+ const code = params.get("code");
182
+ const state = params.get("state") || "";
183
+ if (code) {
184
+ window.history.replaceState({}, document.title, window.location.pathname);
185
+ try {
186
+ const r = await post("/api/auth/callback", { code, state });
187
+ if (r.ok) { finishGitHub(r.data); return; }
188
+ throw new Error(r.data.detail || "GitHub sign-in failed.");
189
+ } catch (e) {
190
+ setGhPhase("error"); setGhError(e.message || "GitHub sign-in failed."); return;
191
+ }
192
+ }
193
+
194
+ // Try the standard web OAuth redirect; fall back to device flow.
195
+ try {
196
+ const r = await getJSON("/api/auth/url");
197
+ if (r.ok && r.data.authorization_url) {
198
+ if (r.data.state) sessionStorage.setItem("gitpilot_oauth_state", r.data.state);
199
+ window.location.href = r.data.authorization_url; // redirect to GitHub
200
+ return;
201
+ }
202
+ } catch { /* fall through to device flow */ }
203
+
204
+ // Device flow (no client secret configured): show the code in place.
205
+ try {
206
+ const r = await post("/api/auth/device/code", {});
207
+ if (r.data.error) {
208
+ if (String(r.data.error).includes("400") || String(r.data.error).includes("Bad Request")) {
209
+ throw new Error("Device Flow is disabled for this GitHub App. Enable it under GitHub App Settings → General → 'Enable Device Flow'.");
210
+ }
211
+ throw new Error(r.data.error);
212
+ }
213
+ if (!r.data.device_code) throw new Error("GitHub did not return a device code.");
214
+ setGhDevice(r.data);
215
+ setGhPhase("device");
216
+ pollDevice(r.data.device_code, r.data.interval || 5);
217
+ } catch (e) {
218
+ setGhPhase("error");
219
+ setGhError(e.message || "Could not start GitHub sign-in.");
220
+ }
221
+ }
222
+
223
+ // Kick off the GitHub flow when entering the github view.
224
+ useEffect(() => {
225
+ if (view === "github") {
226
+ if (ghStarted.current) return;
227
+ ghStarted.current = true;
228
+ startGitHub();
229
+ } else {
230
+ ghStarted.current = false;
231
+ stopPolling.current = true;
232
+ if (pollTimer.current) clearTimeout(pollTimer.current);
233
+ }
234
+ return () => {
235
+ stopPolling.current = true;
236
+ if (pollTimer.current) clearTimeout(pollTimer.current);
237
+ };
238
+ // eslint-disable-next-line react-hooks/exhaustive-deps
239
+ }, [view]);
240
+
241
+ const goEmail = () => {
242
+ stopPolling.current = true;
243
+ if (pollTimer.current) clearTimeout(pollTimer.current);
244
+ setGhDevice(null);
245
+ setGhError("");
246
+ setView("email");
247
+ };
248
+
249
+ const submit = async (e) => {
250
+ e.preventDefault();
251
+ setNote(null);
252
+ setBusy(true);
253
+ try {
254
+ if (mode === "signin") {
255
+ const r = await post("/api/account/login", { email, password });
256
+ if (r.ok) {
257
+ rememberSession(r.data);
258
+ if (typeof onAuthenticated === "function") onAuthenticated({ user: r.data });
259
+ }
260
+ else if (r.status === 403) setNote({ kind: "err", text: "Verify your email before signing in." });
261
+ else setNote({ kind: "err", text: r.data.detail || "Invalid email or password." });
262
+ } else {
263
+ const r = await post("/api/account/signup", { email, password, name: name || null });
264
+ if (r.status === 202) setNote({ kind: "ok", text: "Check your email — we sent a confirmation link." });
265
+ else setNote({ kind: "err", text: r.data.detail || "Could not create the account." });
266
+ }
267
+ } catch {
268
+ setNote({ kind: "err", text: "Network error — is the backend reachable?" });
269
+ } finally {
270
+ setBusy(false);
271
+ }
272
+ };
273
+
274
+ const forgot = async () => {
275
+ if (!email) { setNote({ kind: "err", text: "Enter your email first." }); return; }
276
+ await post("/api/account/password/forgot", { email });
277
+ setNote({ kind: "ok", text: "If an account exists, we'll send a reset link." });
278
+ };
279
+
280
+ // ── Email-confirmation card (landed from the verify-email link) ──
281
+ if (view === "verify") {
282
+ return (
283
+ <div className="gp-auth">
284
+ <a className="gp-home" href="/">← Back to home</a>
285
+ <div className="gp-auth-card">
286
+ <a className="gp-auth-logo" href="/" aria-label="Back to GitPilot home">GP</a>
287
+
288
+ {verifyPhase === "verifying" && (
289
+ <>
290
+ <h2>Confirming your email…</h2>
291
+ <p className="lead">Activating your GitPilot account. This only takes a moment.</p>
292
+ <div className="gp-spinwrap"><span className="gp-spin" /></div>
293
+ </>
294
+ )}
295
+
296
+ {verifyPhase === "success" && (
297
+ <>
298
+ <div className="gp-verify-check" aria-hidden="true">✓</div>
299
+ <h2>Email confirmed</h2>
300
+ <p className="lead">
301
+ Welcome{verifyUser?.name ? `, ${verifyUser.name}` : ""}! Your GitPilot
302
+ account is active.
303
+ </p>
304
+ <button
305
+ type="button"
306
+ className="gp-submit"
307
+ onClick={() => onAuthenticated && onAuthenticated({ user: verifyUser })}
308
+ >
309
+ Continue to GitPilot →
310
+ </button>
311
+ </>
312
+ )}
313
+
314
+ {verifyPhase === "error" && (
315
+ <>
316
+ <h2>Confirmation link problem</h2>
317
+ <div className="gp-note err">{verifyMsg}</div>
318
+ <p className="lead">Links expire after 15 minutes. Enter your email to get a fresh one.</p>
319
+ {note && <div className={`gp-note ${note.kind}`}>{note.text}</div>}
320
+ <div className="gp-field">
321
+ <input
322
+ type="email"
323
+ value={email}
324
+ onChange={(e) => setEmail(e.target.value)}
325
+ placeholder="Email"
326
+ />
327
+ </div>
328
+ <button type="button" className="gp-submit" onClick={resendVerification} disabled={resendBusy}>
329
+ {resendBusy ? "Sending…" : "Resend confirmation email"}
330
+ </button>
331
+ <button type="button" className="gp-link" onClick={() => setView("email")} style={{ marginTop: 12 }}>
332
+ Back to sign in
333
+ </button>
334
+ </>
335
+ )}
336
+
337
+ <div className="gp-copy">© {new Date().getFullYear()} GitPilot Inc.</div>
338
+ </div>
339
+ </div>
340
+ );
341
+ }
342
+
343
+ // ── GitHub authorization card (same shell, no nested rectangle) ──
344
+ if (view === "github") {
345
+ return (
346
+ <div className="gp-auth">
347
+ <a className="gp-home" href="/">← Back to home</a>
348
+ <div className="gp-auth-card">
349
+ {connectMode
350
+ ? <button className="gp-back" onClick={() => { window.location.href = "/"; }}>← Back to workspace</button>
351
+ : <button className="gp-back" onClick={goEmail}>← Back to sign in</button>}
352
+ <a className="gp-auth-logo" href="/" aria-label="Back to GitPilot home">GP</a>
353
+
354
+ {ghPhase === "connecting" && (
355
+ <>
356
+ <h2>Connecting to GitHub…</h2>
357
+ <p className="lead">Opening a secure authorization session for your repositories.</p>
358
+ <div className="gp-spinwrap"><span className="gp-spin" /></div>
359
+ </>
360
+ )}
361
+
362
+ {ghPhase === "device" && ghDevice && (
363
+ <>
364
+ <h2>Authorize GitPilot</h2>
365
+ <p className="lead">Enter this code on GitHub to grant repository access.</p>
366
+ <button
367
+ type="button"
368
+ className="gp-code"
369
+ title="Click to copy"
370
+ onClick={() => navigator.clipboard?.writeText(ghDevice.user_code)}
371
+ >
372
+ {ghDevice.user_code}
373
+ </button>
374
+ <a className="gp-github" href={ghDevice.verification_uri} target="_blank" rel="noreferrer">
375
+ <GithubMark /> Open GitHub to authorize ↗
376
+ </a>
377
+ <div className="gp-waiting"><span className="gp-spin gp-spin-sm" /> Waiting for authorization…</div>
378
+ </>
379
+ )}
380
+
381
+ {ghPhase === "error" && (
382
+ <>
383
+ <h2>GitHub sign-in failed</h2>
384
+ <div className="gp-note err">{ghError}</div>
385
+ <button type="button" className="gp-github" onClick={startGitHub}>
386
+ <GithubMark /> Try again
387
+ </button>
388
+ </>
389
+ )}
390
+
391
+ <div className="gp-copy">© {new Date().getFullYear()} GitPilot Inc.</div>
392
+ </div>
393
+ </div>
394
+ );
395
+ }
396
+
397
+ // ── Email / password card (sign in + create account share this shell) ──
398
+ return (
399
+ <div className="gp-auth">
400
+ <a className="gp-home" href="/">← Back to home</a>
401
+ <form className="gp-auth-card" onSubmit={submit}>
402
+ {mode === "signup" && (
403
+ <button type="button" className="gp-back" onClick={() => { setMode("signin"); setNote(null); }}>← Back to sign in</button>
404
+ )}
405
+ <a className="gp-auth-logo" href="/" aria-label="Back to GitPilot home">GP</a>
406
+ {mode === "signin" ? (
407
+ <>
408
+ <h2>GitPilot Enterprise</h2>
409
+ <p className="lead">Agentic AI workflow for your repositories.<br />Secure. Context-aware. Automated.</p>
410
+ </>
411
+ ) : (
412
+ <>
413
+ <h2>Create your account</h2>
414
+ <p className="lead">Start using GitPilot with a secure workspace.</p>
415
+ </>
416
+ )}
417
+
418
+ <button type="button" className="gp-github" onClick={() => setView("github")}>
419
+ <GithubMark /> Continue with GitHub
420
+ </button>
421
+ <div className="gp-or">or</div>
422
+
423
+ {note && <div className={`gp-note ${note.kind}`}>{note.text}</div>}
424
+
425
+ {mode === "signup" && (
426
+ <div className="gp-field">
427
+ <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name (optional)" />
428
+ </div>
429
+ )}
430
+ <div className="gp-field">
431
+ <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
432
+ </div>
433
+ <div className="gp-field gp-pw">
434
+ <input type={showPw ? "text" : "password"} required minLength={8} value={password}
435
+ onChange={(e) => setPassword(e.target.value)} placeholder="Password" />
436
+ <button type="button" className="gp-eye" onClick={() => setShowPw((s) => !s)} aria-label="Toggle password">
437
+ <Eye off={showPw} />
438
+ </button>
439
+ </div>
440
+ {mode === "signin" && (
441
+ <div className="gp-forgot"><button type="button" className="gp-link" onClick={forgot}>Forgot password?</button></div>
442
+ )}
443
+
444
+ <button className="gp-submit" type="submit" disabled={busy}>
445
+ {busy ? "Please wait…" : mode === "signin" ? "Sign in" : "Create account"}
446
+ </button>
447
+
448
+ <div className="gp-foot">
449
+ {mode === "signin" ? (
450
+ <>Don&apos;t have an account? <button type="button" className="gp-link" onClick={() => { setMode("signup"); setNote(null); }}>Create account</button></>
451
+ ) : (
452
+ <>Already have an account? <button type="button" className="gp-link" onClick={() => { setMode("signin"); setNote(null); }}>Sign in</button></>
453
+ )}
454
+ </div>
455
+ <div className="gp-copy">© {new Date().getFullYear()} GitPilot Inc.</div>
456
+ </form>
457
+ </div>
458
+ );
459
+ }
frontend/components/BranchPicker.jsx ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useCallback, useEffect, useRef, useState } from "react";
2
+ import { createPortal } from "react-dom";
3
+
4
+ /**
5
+ * BranchPicker — Claude-Code-on-Web parity branch selector.
6
+ *
7
+ * Fetches branches from the new /api/repos/{owner}/{repo}/branches endpoint.
8
+ * Shows search, default branch badge, AI session branch highlighting.
9
+ *
10
+ * Fixes applied:
11
+ * - Dropdown portaled to document.body (avoids overflow:hidden clipping)
12
+ * - Branches cached per repo (no "No branches found" flash)
13
+ * - Shows "Loading..." only on first fetch, keeps stale data otherwise
14
+ */
15
+
16
+ // Simple per-repo branch cache so reopening the dropdown is instant
17
+ const branchCache = {};
18
+
19
+ /**
20
+ * Props:
21
+ * repo, currentBranch, defaultBranch, sessionBranches, onBranchChange
22
+ * — standard branch-picker props
23
+ *
24
+ * externalAnchorRef (optional) — a React ref pointing to an external DOM
25
+ * element to anchor the dropdown to. When provided:
26
+ * - BranchPicker skips rendering its own trigger button
27
+ * - the dropdown opens immediately on mount
28
+ * - closing the dropdown calls onClose()
29
+ *
30
+ * onClose (optional) — called when the dropdown is dismissed (outside
31
+ * click or Escape). Only meaningful with externalAnchorRef.
32
+ */
33
+ export default function BranchPicker({
34
+ repo,
35
+ currentBranch,
36
+ defaultBranch,
37
+ sessionBranches = [],
38
+ onBranchChange,
39
+ externalAnchorRef,
40
+ onClose,
41
+ }) {
42
+ const isExternalMode = !!externalAnchorRef;
43
+ const [open, setOpen] = useState(isExternalMode);
44
+ const [query, setQuery] = useState("");
45
+ const [branches, setBranches] = useState([]);
46
+ const [loading, setLoading] = useState(false);
47
+ const [error, setError] = useState(null);
48
+ const triggerRef = useRef(null);
49
+ const dropdownRef = useRef(null);
50
+ const inputRef = useRef(null);
51
+
52
+ const branch = currentBranch || defaultBranch || "main";
53
+ const isAiSession = sessionBranches.includes(branch) && branch !== defaultBranch;
54
+
55
+ // The element used for dropdown positioning
56
+ const anchorRef = isExternalMode ? externalAnchorRef : triggerRef;
57
+
58
+ const cacheKey = repo ? `${repo.owner}/${repo.name}` : null;
59
+
60
+ // Seed from cache on mount / repo change
61
+ useEffect(() => {
62
+ if (cacheKey && branchCache[cacheKey]) {
63
+ setBranches(branchCache[cacheKey]);
64
+ }
65
+ }, [cacheKey]);
66
+
67
+ // Fetch branches from GitHub via backend
68
+ const fetchBranches = useCallback(async (searchQuery) => {
69
+ if (!repo) return;
70
+ setLoading(true);
71
+ setError(null);
72
+ try {
73
+ const token = localStorage.getItem("github_token");
74
+ const headers = token ? { Authorization: `Bearer ${token}` } : {};
75
+ const params = new URLSearchParams({ per_page: "100" });
76
+ if (searchQuery) params.set("query", searchQuery);
77
+
78
+ const res = await fetch(
79
+ `/api/repos/${repo.owner}/${repo.name}/branches?${params}`,
80
+ { headers, cache: "no-cache" }
81
+ );
82
+ if (!res.ok) {
83
+ const errData = await res.json().catch(() => ({}));
84
+ const detail = errData.detail || `HTTP ${res.status}`;
85
+ console.warn("BranchPicker: fetch failed:", detail);
86
+ setError(detail);
87
+ return;
88
+ }
89
+ const data = await res.json();
90
+ const fetched = data.branches || [];
91
+ setBranches(fetched);
92
+
93
+ // Only cache the unfiltered result
94
+ if (!searchQuery && cacheKey) {
95
+ branchCache[cacheKey] = fetched;
96
+ }
97
+ } catch (err) {
98
+ console.warn("Failed to fetch branches:", err);
99
+ } finally {
100
+ setLoading(false);
101
+ }
102
+ }, [repo, cacheKey]);
103
+
104
+ // Fetch + focus when opened
105
+ useEffect(() => {
106
+ if (open) {
107
+ fetchBranches(query);
108
+ setTimeout(() => inputRef.current?.focus(), 50);
109
+ }
110
+ }, [open]); // eslint-disable-line react-hooks/exhaustive-deps
111
+
112
+ // Debounced search
113
+ useEffect(() => {
114
+ if (!open) return;
115
+ const t = setTimeout(() => fetchBranches(query), 300);
116
+ return () => clearTimeout(t);
117
+ }, [query, open, fetchBranches]);
118
+
119
+ // Close on outside click
120
+ useEffect(() => {
121
+ if (!open) return;
122
+ const handler = (e) => {
123
+ const inAnchor = anchorRef.current && anchorRef.current.contains(e.target);
124
+ const inDropdown = dropdownRef.current && dropdownRef.current.contains(e.target);
125
+ if (!inAnchor && !inDropdown) {
126
+ handleClose();
127
+ }
128
+ };
129
+ document.addEventListener("mousedown", handler);
130
+ return () => document.removeEventListener("mousedown", handler);
131
+ }, [open]); // eslint-disable-line react-hooks/exhaustive-deps
132
+
133
+ const handleClose = useCallback(() => {
134
+ setOpen(false);
135
+ setQuery("");
136
+ onClose?.();
137
+ }, [onClose]);
138
+
139
+ const handleSelect = (branchName) => {
140
+ handleClose();
141
+ if (branchName !== branch) {
142
+ onBranchChange?.(branchName);
143
+ }
144
+ };
145
+
146
+ // Merge API branches with session branches (AI branches might not show in GitHub API)
147
+ const allBranches = [...branches];
148
+ for (const sb of sessionBranches) {
149
+ if (!allBranches.find((b) => b.name === sb)) {
150
+ allBranches.push({ name: sb, is_default: false, protected: false });
151
+ }
152
+ }
153
+
154
+ // Calculate portal position from anchor element
155
+ const getDropdownPosition = () => {
156
+ if (!anchorRef.current) return { top: 0, left: 0 };
157
+ const rect = anchorRef.current.getBoundingClientRect();
158
+ return {
159
+ top: rect.bottom + 4,
160
+ left: rect.left,
161
+ };
162
+ };
163
+
164
+ const pos = open ? getDropdownPosition() : { top: 0, left: 0 };
165
+
166
+ return (
167
+ <div style={styles.container}>
168
+ {/* Trigger button — hidden when using external anchor */}
169
+ {!isExternalMode && (
170
+ <button
171
+ ref={triggerRef}
172
+ type="button"
173
+ style={{
174
+ ...styles.trigger,
175
+ borderColor: isAiSession ? "rgba(59, 130, 246, 0.3)" : "#3F3F46",
176
+ color: isAiSession ? "#60a5fa" : "#E4E4E7",
177
+ backgroundColor: isAiSession ? "rgba(59, 130, 246, 0.05)" : "transparent",
178
+ }}
179
+ onClick={() => setOpen((v) => !v)}
180
+ >
181
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
182
+ <line x1="6" y1="3" x2="6" y2="15" />
183
+ <circle cx="18" cy="6" r="3" />
184
+ <circle cx="6" cy="18" r="3" />
185
+ <path d="M18 9a9 9 0 0 1-9 9" />
186
+ </svg>
187
+ <span style={styles.branchName}>{branch}</span>
188
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
189
+ <polyline points="6 9 12 15 18 9" />
190
+ </svg>
191
+ </button>
192
+ )}
193
+
194
+ {/* Dropdown — portaled to document.body to escape overflow:hidden */}
195
+ {open && createPortal(
196
+ <div
197
+ ref={dropdownRef}
198
+ style={{
199
+ ...styles.dropdown,
200
+ top: pos.top,
201
+ left: pos.left,
202
+ }}
203
+ >
204
+ {/* Search input */}
205
+ <div style={styles.searchBox}>
206
+ <input
207
+ ref={inputRef}
208
+ type="text"
209
+ placeholder="Search branches..."
210
+ value={query}
211
+ onChange={(e) => setQuery(e.target.value)}
212
+ style={styles.searchInput}
213
+ onKeyDown={(e) => {
214
+ if (e.key === "Escape") {
215
+ handleClose();
216
+ }
217
+ }}
218
+ />
219
+ </div>
220
+
221
+ {/* Branch list */}
222
+ <div style={styles.branchList}>
223
+ {loading && allBranches.length === 0 && (
224
+ <div style={styles.loadingRow}>Loading...</div>
225
+ )}
226
+
227
+ {!loading && error && (
228
+ <div style={styles.errorRow}>{error}</div>
229
+ )}
230
+
231
+ {!loading && !error && allBranches.length === 0 && (
232
+ <div style={styles.loadingRow}>No branches found</div>
233
+ )}
234
+
235
+ {allBranches.map((b) => {
236
+ const isDefault = b.is_default || b.name === defaultBranch;
237
+ const isAi = sessionBranches.includes(b.name);
238
+ const isCurrent = b.name === branch;
239
+
240
+ return (
241
+ <div
242
+ key={b.name}
243
+ style={{
244
+ ...styles.branchRow,
245
+ backgroundColor: isCurrent
246
+ ? isAi
247
+ ? "rgba(59, 130, 246, 0.10)"
248
+ : "#27272A"
249
+ : "transparent",
250
+ }}
251
+ onMouseDown={() => handleSelect(b.name)}
252
+ >
253
+ <span style={{ opacity: isCurrent ? 1 : 0, width: 16, flexShrink: 0 }}>
254
+ &#10003;
255
+ </span>
256
+ <span
257
+ style={{
258
+ flex: 1,
259
+ fontFamily: "monospace",
260
+ fontSize: 12,
261
+ color: isAi ? "#60a5fa" : "#E4E4E7",
262
+ whiteSpace: "nowrap",
263
+ overflow: "hidden",
264
+ textOverflow: "ellipsis",
265
+ }}
266
+ >
267
+ {b.name}
268
+ </span>
269
+ {isDefault && (
270
+ <span style={styles.defaultBadge}>default</span>
271
+ )}
272
+ {isAi && !isDefault && (
273
+ <span style={styles.aiBadge}>AI</span>
274
+ )}
275
+ {b.protected && (
276
+ <span style={styles.protectedBadge}>
277
+ <svg width="8" height="8" viewBox="0 0 24 24" fill="currentColor">
278
+ <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z" />
279
+ </svg>
280
+ </span>
281
+ )}
282
+ </div>
283
+ );
284
+ })}
285
+
286
+ {/* Subtle loading indicator when refreshing with cached data visible */}
287
+ {loading && allBranches.length > 0 && (
288
+ <div style={styles.loadingRow}>Updating...</div>
289
+ )}
290
+ </div>
291
+ </div>,
292
+ document.body
293
+ )}
294
+ </div>
295
+ );
296
+ }
297
+
298
+ const styles = {
299
+ container: {
300
+ position: "relative",
301
+ },
302
+ trigger: {
303
+ display: "flex",
304
+ alignItems: "center",
305
+ gap: 6,
306
+ padding: "4px 8px",
307
+ borderRadius: 4,
308
+ border: "1px solid #3F3F46",
309
+ background: "transparent",
310
+ fontSize: 13,
311
+ cursor: "pointer",
312
+ fontFamily: "monospace",
313
+ maxWidth: 200,
314
+ },
315
+ branchName: {
316
+ whiteSpace: "nowrap",
317
+ overflow: "hidden",
318
+ textOverflow: "ellipsis",
319
+ maxWidth: 140,
320
+ },
321
+ dropdown: {
322
+ position: "fixed",
323
+ width: 280,
324
+ backgroundColor: "#1F1F23",
325
+ border: "1px solid #27272A",
326
+ borderRadius: 8,
327
+ boxShadow: "0 8px 24px rgba(0,0,0,0.6)",
328
+ zIndex: 9999,
329
+ overflow: "hidden",
330
+ },
331
+ searchBox: {
332
+ padding: "8px 10px",
333
+ borderBottom: "1px solid #27272A",
334
+ },
335
+ searchInput: {
336
+ width: "100%",
337
+ padding: "6px 8px",
338
+ borderRadius: 4,
339
+ border: "1px solid #3F3F46",
340
+ background: "#131316",
341
+ color: "#E4E4E7",
342
+ fontSize: 12,
343
+ outline: "none",
344
+ fontFamily: "monospace",
345
+ boxSizing: "border-box",
346
+ },
347
+ branchList: {
348
+ maxHeight: 260,
349
+ overflowY: "auto",
350
+ },
351
+ branchRow: {
352
+ display: "flex",
353
+ alignItems: "center",
354
+ gap: 6,
355
+ padding: "7px 10px",
356
+ cursor: "pointer",
357
+ transition: "background-color 0.1s",
358
+ borderBottom: "1px solid rgba(39, 39, 42, 0.5)",
359
+ },
360
+ loadingRow: {
361
+ padding: "12px 10px",
362
+ textAlign: "center",
363
+ fontSize: 12,
364
+ color: "#71717A",
365
+ },
366
+ errorRow: {
367
+ padding: "12px 10px",
368
+ textAlign: "center",
369
+ fontSize: 11,
370
+ color: "#F59E0B",
371
+ },
372
+ defaultBadge: {
373
+ fontSize: 9,
374
+ padding: "1px 5px",
375
+ borderRadius: 8,
376
+ backgroundColor: "rgba(16, 185, 129, 0.15)",
377
+ color: "#10B981",
378
+ fontWeight: 600,
379
+ textTransform: "uppercase",
380
+ letterSpacing: "0.04em",
381
+ flexShrink: 0,
382
+ },
383
+ aiBadge: {
384
+ fontSize: 9,
385
+ padding: "1px 5px",
386
+ borderRadius: 8,
387
+ backgroundColor: "rgba(59, 130, 246, 0.15)",
388
+ color: "#60a5fa",
389
+ fontWeight: 700,
390
+ flexShrink: 0,
391
+ },
392
+ protectedBadge: {
393
+ color: "#F59E0B",
394
+ flexShrink: 0,
395
+ display: "flex",
396
+ alignItems: "center",
397
+ },
398
+ };
frontend/components/ChatPanel.jsx ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { resolveBackendUrl } from "../utils/backend.js";
2
+ import { apiUrl } from "../utils/api.js";
3
+ // frontend/components/ChatPanel.jsx
4
+ import React, { useEffect, useRef, useState } from "react";
5
+ import AssistantMessage from "./AssistantMessage.jsx";
6
+ import ThinkingIndicator from "./ThinkingIndicator.jsx";
7
+ import ContextMeter from "./ContextMeter.jsx";
8
+ import TasksPanel from "./TasksPanel.jsx";
9
+ import DiffStats from "./DiffStats.jsx";
10
+ import DiffViewer from "./DiffViewer.jsx";
11
+ import CreatePRButton from "./CreatePRButton.jsx";
12
+ import StreamingMessage from "./StreamingMessage.jsx";
13
+ import SandboxCanvas from "./SandboxCanvas.jsx";
14
+ import FilePreviewPanel from "./FilePreviewPanel.jsx";
15
+ import { SessionWebSocket } from "../utils/ws.js";
16
+ import { classifyPlan, planSummary } from "../utils/planKind.js";
17
+
18
+ // Map a file extension to the canonical sandbox language tag. Used
19
+ // when "Open in Canvas" needs to seed SandboxCanvas with the right
20
+ // language hint pulled straight from a repo file path.
21
+ const _LANG_FROM_EXT = {
22
+ py: "python", js: "javascript", mjs: "javascript", cjs: "javascript",
23
+ sh: "bash", bash: "bash",
24
+ };
25
+ function languageFromPath(path) {
26
+ if (!path || !path.includes(".")) return "python";
27
+ return _LANG_FROM_EXT[path.split(".").pop().toLowerCase()] || "python";
28
+ }
29
+
30
+ // Helper to get headers (inline safety if utility is missing)
31
+ const getHeaders = () => ({
32
+ "Content-Type": "application/json",
33
+ Authorization: `Bearer ${localStorage.getItem("github_token") || ""}`,
34
+ });
35
+
36
+ export default function ChatPanel({
37
+ repo,
38
+ defaultBranch = "main",
39
+ currentBranch, // do NOT default here; parent must pass the real one
40
+ onExecutionComplete,
41
+ sessionChatState,
42
+ onSessionChatStateChange,
43
+ sessionId,
44
+ onEnsureSession,
45
+ canChat = true, // readiness gate: false disables composer and shows blocker
46
+ chatBlocker = null, // { message: string, cta?: string, onCta?: () => void }
47
+ }) {
48
+ // Initialize state from props or defaults
49
+ const [messages, setMessages] = useState(sessionChatState?.messages || []);
50
+ const [goal, setGoal] = useState("");
51
+ const [plan, setPlan] = useState(sessionChatState?.plan || null);
52
+
53
+ const [loadingPlan, setLoadingPlan] = useState(false);
54
+ const [executing, setExecuting] = useState(false);
55
+ const [status, setStatus] = useState("");
56
+ // Batch B9 — populated when a plan whose first step was INDEX is
57
+ // rejected. Lets us render a small "Run with grep instead?" prompt
58
+ // so the user doesn't have to retype the goal.
59
+ const [retryAfterIndexReject, setRetryAfterIndexReject] = useState(null);
60
+
61
+ // Claude-Code-on-Web: WebSocket streaming + diff + PR
62
+ const [wsConnected, setWsConnected] = useState(false);
63
+ const [streamingEvents, setStreamingEvents] = useState([]);
64
+ const [diffData, setDiffData] = useState(null);
65
+ const [showDiffViewer, setShowDiffViewer] = useState(false);
66
+ // SandboxCanvas state — opened by the "Open in Canvas" CTA on
67
+ // post-CREATE next_actions and ExecutionCard footers. ``canvasSpec``
68
+ // is { filename, language, code } or null when closed.
69
+ const [canvasSpec, setCanvasSpec] = useState(null);
70
+ const [canvasError, setCanvasError] = useState(null);
71
+ // FilePreviewPanel state — opened by clicking a file row in the
72
+ // sidebar (gitpilot:open-file). Read-first surface; users can pick
73
+ // "Prepare Run" / "Open Workspace" / "Ask GitPilot" from there.
74
+ const [previewPath, setPreviewPath] = useState(null);
75
+ const [previewContent, setPreviewContent] = useState(null);
76
+ const [previewLoading, setPreviewLoading] = useState(false);
77
+ const [previewError, setPreviewError] = useState(null);
78
+ const [previewErrorCode, setPreviewErrorCode] = useState(null);
79
+ // "preview" (narrow drawer) or "workspace" (wide editor).
80
+ const [previewMode, setPreviewMode] = useState("preview");
81
+ const wsRef = useRef(null);
82
+
83
+ // Ref mirrors streamingEvents so WS callbacks avoid stale closures
84
+ const streamingEventsRef = useRef([]);
85
+ useEffect(() => { streamingEventsRef.current = streamingEvents; }, [streamingEvents]);
86
+
87
+ // Tracks files that were just CREATE'd / MODIFY'd by a fresh execution.
88
+ // Used to (a) auto-retry once on 404 (GitHub contents API has brief
89
+ // eventual-consistency lag) and (b) classify the file viewer's empty
90
+ // state as "still syncing" instead of a generic 404.
91
+ const fileWasJustCreatedRef = useRef(new Set());
92
+ const fileWasJustDeletedRef = useRef(new Set());
93
+
94
+ // Skip the session-sync useEffect reset when we just created a session
95
+ // (the parent already seeded the messages into chatBySession)
96
+ const skipNextSyncRef = useRef(false);
97
+
98
+ const messagesEndRef = useRef(null);
99
+ const prevMsgCountRef = useRef((sessionChatState?.messages || []).length);
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // WebSocket connection management
103
+ // ---------------------------------------------------------------------------
104
+ useEffect(() => {
105
+ // Clean up previous connection
106
+ if (wsRef.current) {
107
+ wsRef.current.close();
108
+ wsRef.current = null;
109
+ setWsConnected(false);
110
+ }
111
+
112
+ if (!sessionId) return;
113
+
114
+ // Wait for backend to be reachable before opening WebSocket.
115
+ // Without this, the WS connects immediately on session creation
116
+ // and fails repeatedly with "closed before established" when the
117
+ // backend is still starting up (common on WSL cold start).
118
+ let cancelled = false;
119
+ const backendUrl = resolveBackendUrl();
120
+ const pingUrl = backendUrl ? `${backendUrl}/api/ping` : '/api/ping';
121
+ const waitForBackend = async () => {
122
+ for (let i = 0; i < 10 && !cancelled; i++) {
123
+ try {
124
+ const res = await fetch(pingUrl, { method: 'GET', signal: AbortSignal.timeout(2000) });
125
+ if (res.ok) return true;
126
+ } catch { /* retry */ }
127
+ await new Promise(r => setTimeout(r, 1500));
128
+ }
129
+ return false;
130
+ };
131
+
132
+ waitForBackend().then((ok) => {
133
+ if (cancelled || !ok) return;
134
+ connectWs();
135
+ });
136
+
137
+ function connectWs() {
138
+ const ws = new SessionWebSocket(sessionId, {
139
+ onConnect: () => setWsConnected(true),
140
+ onDisconnect: () => setWsConnected(false),
141
+ onMessage: (data) => {
142
+ if (data.type === "agent_message") {
143
+ setStreamingEvents((prev) => [...prev, data]);
144
+ } else if (data.type === "tool_use" || data.type === "tool_result") {
145
+ setStreamingEvents((prev) => [...prev, data]);
146
+ } else if (data.type === "diff_update") {
147
+ setDiffData(data.stats || data);
148
+ } else if (data.type === "session_restored") {
149
+ // Session loaded
150
+ }
151
+ },
152
+ onStatusChange: (newStatus) => {
153
+ if (newStatus === "waiting") {
154
+ // Always clear loading state when agent finishes
155
+ setLoadingPlan(false);
156
+
157
+ // Consolidate streaming events into a chat message (use ref to
158
+ // avoid stale closure — streamingEvents state would be stale here).
159
+ //
160
+ // We also commit the FINAL consolidated text to the backend session
161
+ // here. Previously this branch never called persistMessage, so the
162
+ // assistant turn looked correct in the live view but vanished on the
163
+ // next session reload — the canonical "streaming truncation" symptom.
164
+ const events = streamingEventsRef.current;
165
+ if (events.length > 0) {
166
+ const textParts = events
167
+ .filter((e) => e.type === "agent_message")
168
+ .map((e) => e.content);
169
+ if (textParts.length > 0) {
170
+ const consolidated = {
171
+ from: "ai",
172
+ role: "assistant",
173
+ answer: textParts.join(""),
174
+ content: textParts.join(""),
175
+ };
176
+ setMessages((prev) => [...prev, consolidated]);
177
+ persistMessage(sessionId, "assistant", consolidated.content);
178
+ }
179
+ setStreamingEvents([]);
180
+ }
181
+ }
182
+ },
183
+ onError: (err) => {
184
+ console.warn("[ws] Error:", err);
185
+ setLoadingPlan(false);
186
+ },
187
+ });
188
+
189
+ ws.connect();
190
+ wsRef.current = ws;
191
+ } // end connectWs
192
+
193
+ return () => {
194
+ cancelled = true;
195
+ if (wsRef.current) wsRef.current.close();
196
+ };
197
+ }, [sessionId]); // eslint-disable-line react-hooks/exhaustive-deps
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // 1) SESSION SYNC: Restore chat when branch, repo, OR session changes
201
+ // IMPORTANT: Do NOT depend on sessionChatState here (prevents prop/state loop)
202
+ // ---------------------------------------------------------------------------
203
+ useEffect(() => {
204
+ // When send() just created a session, the parent seeded the messages
205
+ // into chatBySession already. Skip the reset so we don't wipe
206
+ // the optimistic user message that was already rendered.
207
+ if (skipNextSyncRef.current) {
208
+ skipNextSyncRef.current = false;
209
+ return;
210
+ }
211
+
212
+ const nextMessages = sessionChatState?.messages || [];
213
+ const nextPlan = sessionChatState?.plan || null;
214
+
215
+ setMessages(nextMessages);
216
+ setPlan(nextPlan);
217
+
218
+ // Reset transient UI state on branch/repo/session switch
219
+ setGoal("");
220
+ setStatus("");
221
+ setLoadingPlan(false);
222
+ setExecuting(false);
223
+ setStreamingEvents([]);
224
+ setDiffData(null);
225
+
226
+ // Update msg count tracker so auto-scroll doesn't "jump" on switch
227
+ prevMsgCountRef.current = nextMessages.length;
228
+ // eslint-disable-next-line react-hooks/exhaustive-deps
229
+ }, [currentBranch, repo?.full_name, sessionId]);
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // 1b) FILE ▶ RUN: listen for run-file events from the sidebar.
233
+ // ---------------------------------------------------------------------------
234
+ //
235
+ // FileTree dispatches ``gitpilot:run-file`` with the clicked file's
236
+ // path. We turn that into a normal chat message ("run <path>")
237
+ // which goes through /api/chat/plan, hits the deterministic
238
+ // short-circuit, and renders an ExecutionPlanCard — exactly the
239
+ // same flow as typing the command. One handler, one approval surface,
240
+ // zero duplicated logic.
241
+ useEffect(() => {
242
+ const onRunFile = (e) => {
243
+ const path = e?.detail?.path;
244
+ if (!path || !repo) return;
245
+ send({ goal: `run ${path}` });
246
+ };
247
+ // "Open in Canvas" handler — fetches the file's content from the
248
+ // active branch and opens SandboxCanvas seeded with it. Logs a
249
+ // friendly error banner when the fetch fails so a misconfigured
250
+ // token / wrong branch doesn't silently swallow the click.
251
+ const onOpenInCanvas = async (e) => {
252
+ const path = e?.detail?.path;
253
+ if (!path || !repo) return;
254
+ setCanvasError(null);
255
+ const branch = currentBranch || "HEAD";
256
+ try {
257
+ const url = `/api/repos/${repo.owner}/${repo.name}/file`
258
+ + `?path=${encodeURIComponent(path)}`
259
+ + `&ref=${encodeURIComponent(branch)}`;
260
+ const res = await fetch(apiUrl(url), { headers: getHeaders() });
261
+ const data = await res.json().catch(() => ({}));
262
+ if (!res.ok) {
263
+ setCanvasError(data.detail || `Could not load ${path} (HTTP ${res.status})`);
264
+ // Still open the canvas with empty content so the user can
265
+ // paste something — better than nothing happening on click.
266
+ setCanvasSpec({
267
+ filename: path, language: languageFromPath(path), code: "",
268
+ });
269
+ return;
270
+ }
271
+ setCanvasSpec({
272
+ filename: path,
273
+ language: languageFromPath(path),
274
+ code: data.content || "",
275
+ });
276
+ } catch (err) {
277
+ setCanvasError(err?.message || "Could not load file for Canvas");
278
+ setCanvasSpec({
279
+ filename: path, language: languageFromPath(path), code: "",
280
+ });
281
+ }
282
+ };
283
+ // "Open file" — clicking a file row in the sidebar mounts the
284
+ // read-first FilePreviewPanel. Calmer than dropping straight
285
+ // into Canvas: the user sees the file, can pick "Prepare Run"
286
+ // when they're ready (or "Open Workspace" for a wider editing
287
+ // surface). The ``mode`` detail toggles the panel's geometry:
288
+ // "preview" ── narrow right drawer for a quick look
289
+ // "workspace" ── wide right-side editor for serious review
290
+ const openFile = async (path, mode = "preview") => {
291
+ if (!path || !repo) return;
292
+ setPreviewPath(path);
293
+ setPreviewMode(mode);
294
+ setPreviewContent(null);
295
+ setPreviewError(null);
296
+ setPreviewErrorCode(null);
297
+ setPreviewLoading(true);
298
+ // Tell the sidebar which file is currently focused so it can
299
+ // light up the row with the ◄ marker.
300
+ try {
301
+ window.dispatchEvent(new CustomEvent("gitpilot:file-opened", { detail: { path } }));
302
+ } catch (_e) { /* old browser */ }
303
+ const branch = currentBranch || "HEAD";
304
+ const fetchOnce = async () => {
305
+ const url = `/api/repos/${repo.owner}/${repo.name}/file`
306
+ + `?path=${encodeURIComponent(path)}`
307
+ + `&ref=${encodeURIComponent(branch)}`;
308
+ const res = await fetch(apiUrl(url), { headers: getHeaders() });
309
+ const data = await res.json().catch(() => ({}));
310
+ return { res, data };
311
+ };
312
+ try {
313
+ let { res, data } = await fetchOnce();
314
+ // Auto-retry once on 404 for recently created files — GitHub
315
+ // contents API has brief eventual-consistency lag after a
316
+ // freshly published commit.
317
+ if (res.status === 404 && fileWasJustCreatedRef.current?.has(path)) {
318
+ await new Promise((r) => setTimeout(r, 900));
319
+ ({ res, data } = await fetchOnce());
320
+ }
321
+ if (!res.ok) {
322
+ setPreviewError(data.detail || `HTTP ${res.status}`);
323
+ setPreviewErrorCode(res.status);
324
+ } else {
325
+ setPreviewContent(data.content || "");
326
+ }
327
+ } catch (err) {
328
+ setPreviewError(err?.message || "Could not load file");
329
+ setPreviewErrorCode(null);
330
+ } finally {
331
+ setPreviewLoading(false);
332
+ }
333
+ };
334
+ const onOpenFile = (e) => openFile(e?.detail?.path, "preview");
335
+ const onOpenWorkspace = (e) => openFile(e?.detail?.path, "workspace");
336
+ // "Ask GitPilot" — seed the chat input with a contextual question
337
+ // about the clicked file. Pure additive: focuses the input and
338
+ // pre-fills it; the user can edit or send as-is.
339
+ const onAskAboutFile = (e) => {
340
+ const path = e?.detail?.path;
341
+ if (!path) return;
342
+ setGoal(`Tell me about ${path}.`);
343
+ const ta = document.querySelector(".chat-input");
344
+ if (ta) { ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }
345
+ };
346
+ window.addEventListener("gitpilot:run-file", onRunFile);
347
+ window.addEventListener("gitpilot:open-in-canvas", onOpenInCanvas);
348
+ window.addEventListener("gitpilot:open-file", onOpenFile);
349
+ window.addEventListener("gitpilot:open-workspace", onOpenWorkspace);
350
+ window.addEventListener("gitpilot:ask-about-file", onAskAboutFile);
351
+ return () => {
352
+ window.removeEventListener("gitpilot:run-file", onRunFile);
353
+ window.removeEventListener("gitpilot:open-in-canvas", onOpenInCanvas);
354
+ window.removeEventListener("gitpilot:open-file", onOpenFile);
355
+ window.removeEventListener("gitpilot:open-workspace", onOpenWorkspace);
356
+ window.removeEventListener("gitpilot:ask-about-file", onAskAboutFile);
357
+ };
358
+ // ``send`` is stable enough across renders for this use case —
359
+ // we don't want to re-bind on every keystroke.
360
+ // eslint-disable-next-line react-hooks/exhaustive-deps
361
+ }, [repo?.full_name, currentBranch, sessionId]);
362
+
363
+ // ---------------------------------------------------------------------------
364
+ // 2) PERSISTENCE: Save chat to Parent (no loop now because sync only on branch)
365
+ // ---------------------------------------------------------------------------
366
+ useEffect(() => {
367
+ if (typeof onSessionChatStateChange === "function") {
368
+ // Avoid wiping parent state on mount
369
+ if (messages.length > 0 || plan) {
370
+ onSessionChatStateChange({ messages, plan });
371
+ }
372
+ }
373
+ // eslint-disable-next-line react-hooks/exhaustive-deps
374
+ }, [messages, plan]);
375
+
376
+ // ---------------------------------------------------------------------------
377
+ // 3) AUTO-SCROLL: Only scroll when a message is appended (reduces flicker)
378
+ // ---------------------------------------------------------------------------
379
+ useEffect(() => {
380
+ const curCount = messages.length + streamingEvents.length;
381
+ const prevCount = prevMsgCountRef.current;
382
+
383
+ // Only scroll when new messages are added
384
+ if (curCount > prevCount) {
385
+ prevMsgCountRef.current = curCount;
386
+ requestAnimationFrame(() => {
387
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
388
+ });
389
+ } else {
390
+ prevMsgCountRef.current = curCount;
391
+ }
392
+ }, [messages.length, streamingEvents.length]);
393
+
394
+ // ---------------------------------------------------------------------------
395
+ // HANDLERS
396
+ // ---------------------------------------------------------------------------
397
+ // ---------------------------------------------------------------------------
398
+ // Persist a message to the backend session (fire-and-forget).
399
+ //
400
+ // The fourth argument carries the *structured* payload of the assistant
401
+ // response — the Action Plan, the Execution Log, diff stats, etc. The
402
+ // backend stores it on Message.metadata; on session reload App.jsx
403
+ // spreads metadata back into the local message via normalizeBackendMessage,
404
+ // so the same AssistantMessage renderer can re-draw the Plan / Steps /
405
+ // Create buttons identically to the live view.
406
+ //
407
+ // Before this fix the structured payload was dropped at persist time —
408
+ // the session reloaded as raw text, and the UI degraded to a plain
409
+ // paragraph. This is the canonical "state loss during hydration" bug.
410
+ // ---------------------------------------------------------------------------
411
+ const persistMessage = (sid, role, content, metadata = null) => {
412
+ if (!sid) return;
413
+ const body = { role, content };
414
+ if (metadata && typeof metadata === "object" && Object.keys(metadata).length > 0) {
415
+ body.metadata = metadata;
416
+ }
417
+ fetch(apiUrl(`/api/sessions/${sid}/message`), {
418
+ method: "POST",
419
+ headers: getHeaders(),
420
+ body: JSON.stringify(body),
421
+ }).catch(() => {}); // best-effort
422
+ };
423
+
424
+ // Pick the structured fields a message can carry across a reload.
425
+ // Keep this in one place so every call-site stores the same shape and
426
+ // the renderer never has to guess.
427
+ const pickAssistantMetadata = (m) => {
428
+ if (!m || typeof m !== "object") return null;
429
+ const meta = {};
430
+ if (m.plan) meta.plan = m.plan;
431
+ if (m.executionLog) meta.executionLog = m.executionLog;
432
+ if (m.diff) meta.diff = m.diff;
433
+ if (m.actions) meta.actions = m.actions;
434
+ if (m.nextActions) meta.nextActions = m.nextActions;
435
+ if (m.branch) meta.branch = m.branch;
436
+ // Informational plans (READ-only answers to "what does X do?" style
437
+ // questions) carry no Approve/Reject controls — pin the flag so the
438
+ // session reload re-renders the same shape.
439
+ if (m.informational) meta.informational = true;
440
+ return Object.keys(meta).length > 0 ? meta : null;
441
+ };
442
+
443
+ const send = async (overrides = {}) => {
444
+ if (!repo) return;
445
+ // Allow callers (e.g. the "Retry with grep" button on a rejected
446
+ // INDEX plan) to drive send() with a fixed goal and a router flag.
447
+ const overrideGoal = overrides.goal;
448
+ const force_no_rag = Boolean(overrides.force_no_rag);
449
+ const sourceText = overrideGoal != null ? overrideGoal : goal;
450
+ if (!sourceText || !sourceText.trim()) return;
451
+
452
+ const text = sourceText.trim();
453
+
454
+ // Clear input immediately (Claude Code behavior) — but only when
455
+ // the user typed; programmatic retries leave the input alone.
456
+ if (overrideGoal == null) setGoal("");
457
+ // Reset textarea height
458
+ const ta = document.querySelector(".chat-input");
459
+ if (ta) ta.style.height = "40px";
460
+
461
+ // Optimistic update (user bubble appears immediately)
462
+ const userMsg = { from: "user", role: "user", text, content: text };
463
+ setMessages((prev) => [...prev, userMsg]);
464
+
465
+ setLoadingPlan(true);
466
+ setStatus("");
467
+ setPlan(null);
468
+ setStreamingEvents([]);
469
+
470
+ // ------- Implicit session creation (Claude Code parity) -------
471
+ // Every chat must be backed by a session. If none exists yet,
472
+ // create one on-demand before sending the plan request.
473
+ let sid = sessionId;
474
+ if (!sid && typeof onEnsureSession === "function") {
475
+ // Derive a short title from the first message
476
+ const sessionName = text.length > 60 ? text.slice(0, 57) + "..." : text;
477
+
478
+ // Tell the sync useEffect to skip the reset that would otherwise
479
+ // wipe the optimistic user message when activeSessionId changes.
480
+ skipNextSyncRef.current = true;
481
+
482
+ sid = await onEnsureSession(sessionName, [userMsg]);
483
+ if (!sid) {
484
+ // Session creation failed — continue without session
485
+ skipNextSyncRef.current = false;
486
+ }
487
+ }
488
+
489
+ // Persist user message to backend session
490
+ persistMessage(sid, "user", text);
491
+
492
+ // Always use HTTP for plan generation (the original reliable flow).
493
+ // WebSocket is only used for real-time streaming feedback display.
494
+ const effectiveBranch = currentBranch || defaultBranch || "HEAD";
495
+
496
+ try {
497
+ // Timeout after 5 minutes (CrewAI agent can be slow with small models)
498
+ const planController = new AbortController();
499
+ const planTimer = setTimeout(() => planController.abort(), 300000);
500
+
501
+ let res;
502
+ try {
503
+ res = await fetch(apiUrl("/api/chat/plan"), {
504
+ method: "POST",
505
+ headers: getHeaders(),
506
+ body: JSON.stringify({
507
+ repo_owner: repo.owner,
508
+ repo_name: repo.name,
509
+ goal: text,
510
+ branch_name: effectiveBranch,
511
+ // Lets the backend record this plan as a Task on the
512
+ // session so the right-sidebar Tasks panel can trace it.
513
+ session_id: sid,
514
+ // Batch B9 — set on the "Retry with grep" path after the
515
+ // user rejects an INDEX-plan. Tells the router to
516
+ // suppress RAG / INDEX recommendations.
517
+ force_no_rag,
518
+ }),
519
+ signal: planController.signal,
520
+ });
521
+ } catch (fetchErr) {
522
+ if (fetchErr.name === "AbortError") {
523
+ throw new Error("Request timed out after 5 minutes. The LLM may be too slow. Try a faster model.");
524
+ }
525
+ throw fetchErr;
526
+ } finally {
527
+ clearTimeout(planTimer);
528
+ }
529
+
530
+ let data;
531
+ try {
532
+ data = await res.json();
533
+ } catch {
534
+ 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.`);
535
+ }
536
+ if (!res.ok) {
537
+ const detail = data?.detail || data?.error || data?.message || "";
538
+ // Friendly message for common LLM failures
539
+ if (detail.includes("None or empty") || detail.includes("Invalid response from LLM")) {
540
+ throw new Error(
541
+ "The LLM returned an empty response. This often happens with small models (deepseek, qwen 0.5b). " +
542
+ "Try a larger model (llama3, qwen2.5:7b) or enable Lite Mode in Settings."
543
+ );
544
+ }
545
+ throw new Error(detail || "Failed to generate plan");
546
+ }
547
+
548
+ // Classify the plan into one of three kinds so we can render the right
549
+ // shape — not just "valid or banner". See utils/planKind.js; it lives
550
+ // there so the rule can be tested directly instead of being re-derived
551
+ // from a component that needs a browser to run.
552
+ const summary = planSummary(data);
553
+ const planKind = classifyPlan(data);
554
+
555
+ if (planKind === "executable") {
556
+ setPlan(data);
557
+ const assistantMsg = {
558
+ from: "ai",
559
+ role: "assistant",
560
+ answer: summary,
561
+ content: summary,
562
+ plan: data,
563
+ };
564
+ setMessages((prev) => [...prev, assistantMsg]);
565
+ persistMessage(sid, "assistant", summary, pickAssistantMetadata(assistantMsg));
566
+ } else if (planKind === "informational") {
567
+ // The summary is the answer. No plan card, no Approve/Reject —
568
+ // there is nothing to execute. We deliberately do NOT attach
569
+ // ``plan: data`` here so AssistantMessage renders this turn
570
+ // exactly like a chat reply.
571
+ setPlan(null);
572
+ const assistantMsg = {
573
+ from: "ai",
574
+ role: "assistant",
575
+ answer: summary,
576
+ content: summary,
577
+ informational: true,
578
+ };
579
+ setMessages((prev) => [...prev, assistantMsg]);
580
+ persistMessage(sid, "assistant", summary, pickAssistantMetadata(assistantMsg));
581
+ } else {
582
+ // empty — be honest about what we know. The earlier wording
583
+ // ("got stuck reading the same file twice") was a guess from
584
+ // an older bug; for the cases that actually still hit this
585
+ // branch the real signal is just "no actionable steps".
586
+ setPlan(null);
587
+ const failureText =
588
+ "The model returned an empty plan. Try rephrasing more concretely, " +
589
+ "or pick a stronger model in Settings → Provider.";
590
+ const failureMsg = {
591
+ from: "ai",
592
+ role: "system",
593
+ content: failureText,
594
+ };
595
+ setMessages((prev) => [...prev, failureMsg]);
596
+ persistMessage(sid, "system", failureText);
597
+ setStatus("No actionable plan produced.");
598
+ return;
599
+ }
600
+ } catch (err) {
601
+ const msg = String(err?.message || err);
602
+ console.error(err);
603
+ setStatus(msg);
604
+ setMessages((prev) => [
605
+ ...prev,
606
+ { from: "ai", role: "system", content: `Error: ${msg}` },
607
+ ]);
608
+ } finally {
609
+ setLoadingPlan(false);
610
+ }
611
+ };
612
+
613
+ // ---------------------------------------------------------------------------
614
+ // Reject the active plan — minimal first cut.
615
+ //
616
+ // Industry rule we follow from the start: never write to disk on a path the
617
+ // user did not approve. Rejecting is the cheapest expression of that —
618
+ // discard the proposed plan locally, leave the workspace untouched, record
619
+ // the rejection in chat history so the user sees it after a session reload.
620
+ //
621
+ // No backend endpoint is needed yet because plans are not persisted as
622
+ // first-class objects today; they ride along on the assistant message's
623
+ // metadata. When we later add per-plan state tracking, this handler will
624
+ // also POST /api/chat/plan/{id}/reject — leaving that for a follow-up.
625
+ // ---------------------------------------------------------------------------
626
+ const rejectPlan = () => {
627
+ if (!plan || executing) return;
628
+
629
+ // Batch B9 — if the rejected plan contained an INDEX step, the
630
+ // user is implicitly saying "I don't want to build the semantic
631
+ // index right now". Stash the original goal so we can offer a
632
+ // one-click "retry with grep" path on the next render.
633
+ const hadIndexStep = Array.isArray(plan?.steps) &&
634
+ plan.steps.some((s) =>
635
+ Array.isArray(s?.files) && s.files.some((f) => f?.action === "INDEX"),
636
+ );
637
+ const rejectedGoal = plan?.goal || "";
638
+
639
+ setPlan(null);
640
+ setStatus("Plan rejected. No files were changed.");
641
+
642
+ const rejectionMsg = {
643
+ from: "ai",
644
+ role: "system",
645
+ content: "Plan rejected. No files were changed.",
646
+ };
647
+ setMessages((prev) => [...prev, rejectionMsg]);
648
+
649
+ if (sessionId) {
650
+ persistMessage(sessionId, "system", rejectionMsg.content);
651
+ }
652
+
653
+ if (hadIndexStep && rejectedGoal) {
654
+ setRetryAfterIndexReject({ goal: rejectedGoal });
655
+ } else {
656
+ setRetryAfterIndexReject(null);
657
+ }
658
+ };
659
+
660
+ const execute = async () => {
661
+ if (!repo || !plan) return;
662
+
663
+ setExecuting(true);
664
+ setStatus("");
665
+
666
+ try {
667
+ // Guard: currentBranch might be missing if parent didn't pass it yet
668
+ const safeCurrent = currentBranch || defaultBranch || "HEAD";
669
+ const safeDefault = defaultBranch || "main";
670
+
671
+ // Sticky vs Hard Switch:
672
+ // - If on default branch -> undefined (backend creates new branch)
673
+ // - If already on AI branch -> currentBranch (backend updates existing)
674
+ const branch_name = safeCurrent === safeDefault ? undefined : safeCurrent;
675
+
676
+ const res = await fetch(apiUrl("/api/chat/execute"), {
677
+ method: "POST",
678
+ headers: getHeaders(),
679
+ body: JSON.stringify({
680
+ repo_owner: repo.owner,
681
+ repo_name: repo.name,
682
+ plan,
683
+ branch_name,
684
+ // Lets the backend persist the new branch on the session
685
+ // record so reopening this session lands on the published
686
+ // branch, not the one it was created on.
687
+ session_id: sessionId,
688
+ }),
689
+ });
690
+
691
+ const data = await res.json();
692
+ if (!res.ok) throw new Error(data.detail || "Execution failed");
693
+
694
+ setStatus(data.message || "Execution completed.");
695
+
696
+ // Track files touched by this execution so the file viewer can
697
+ // give "still syncing" / "deleted" classifications and so the
698
+ // sidebar refreshes off the freshly-pushed branch tree.
699
+ if (plan?.steps) {
700
+ for (const step of plan.steps) {
701
+ for (const f of step.files || []) {
702
+ if (f.action === "CREATE" || f.action === "MODIFY") {
703
+ fileWasJustCreatedRef.current.add(f.path);
704
+ } else if (f.action === "DELETE") {
705
+ fileWasJustDeletedRef.current.add(f.path);
706
+ }
707
+ }
708
+ }
709
+ }
710
+ // Forget the marker after 30 s so older "syncing" badges don't
711
+ // stick around forever.
712
+ window.setTimeout(() => {
713
+ fileWasJustCreatedRef.current.clear();
714
+ fileWasJustDeletedRef.current.clear();
715
+ }, 30000);
716
+
717
+ // Ask the sidebar's file tree to refetch off the newly-published
718
+ // branch. Fires after a small delay so GitHub's contents API has
719
+ // a chance to catch up.
720
+ window.setTimeout(() => {
721
+ try {
722
+ window.dispatchEvent(new CustomEvent("gitpilot:refresh-tree"));
723
+ } catch (_e) { /* old browser */ }
724
+ }, 600);
725
+
726
+ const completionMsg = {
727
+ from: "ai",
728
+ role: "assistant",
729
+ answer: data.message || "Execution completed.",
730
+ content: data.message || "Execution completed.",
731
+ executionLog: data.executionLog,
732
+ diff: data.diff,
733
+ // Backend-suggested follow-ups (e.g. "Run demo.py" after CREATE
734
+ // of a runnable file). Rendered as a button row in the
735
+ // completion message — one click, no typing.
736
+ nextActions: data.next_actions,
737
+ branch: data.branch || data.branch_name,
738
+ };
739
+
740
+ // Show completion immediately (keeps old "Execution Log" section)
741
+ setMessages((prev) => [...prev, completionMsg]);
742
+
743
+ // Persist the execution log + diff alongside the message text so
744
+ // the History view re-renders the green "Execution Log" panel and
745
+ // the "View diff" affordance. Without this, reloading the session
746
+ // shows just the one-line "Execution completed." summary.
747
+ persistMessage(
748
+ sessionId,
749
+ "assistant",
750
+ completionMsg.content,
751
+ pickAssistantMetadata(completionMsg),
752
+ );
753
+
754
+ // Clear active plan UI
755
+ setPlan(null);
756
+
757
+ // Pass completionMsg upward for seeding branch history
758
+ if (typeof onExecutionComplete === "function") {
759
+ onExecutionComplete({
760
+ branch: data.branch || data.branch_name,
761
+ mode: data.mode,
762
+ commit_url: data.commit_url || data.html_url,
763
+ message: data.message,
764
+ completionMsg,
765
+ sourceBranch: safeCurrent,
766
+ });
767
+ }
768
+ } catch (err) {
769
+ console.error(err);
770
+ setStatus(String(err?.message || err));
771
+ } finally {
772
+ setExecuting(false);
773
+ }
774
+ };
775
+
776
+ // ---------------------------------------------------------------------------
777
+ // RENDER
778
+ // ---------------------------------------------------------------------------
779
+ const isOnSessionBranch = currentBranch && currentBranch !== defaultBranch;
780
+
781
+ return (
782
+ <div className="chat-container">
783
+ <style>{`
784
+ .chat-container { display: flex; flex-direction: column; height: 100%; }
785
+
786
+ .chat-messages {
787
+ flex: 1; overflow-y: auto;
788
+ padding: 20px;
789
+ display: flex; flex-direction: column; gap: 16px;
790
+ }
791
+
792
+ .chat-message-user {
793
+ align-self: flex-end;
794
+ background: #27272A;
795
+ color: #fff;
796
+ padding: 12px 16px;
797
+ border-radius: 10px;
798
+ max-width: 85%;
799
+ font-size: 14px;
800
+ line-height: 1.5;
801
+ }
802
+
803
+ /* Success System Message Styling */
804
+ .chat-msg-success {
805
+ align-self: flex-start;
806
+ width: 100%;
807
+ background: rgba(16, 185, 129, 0.10);
808
+ border: 1px solid rgba(16, 185, 129, 0.20);
809
+ color: #D1FAE5;
810
+ padding: 12px 16px;
811
+ border-radius: 10px;
812
+ display: flex;
813
+ gap: 12px;
814
+ font-size: 14px;
815
+ }
816
+ .success-icon { font-size: 18px; }
817
+ .success-link {
818
+ display: inline-block;
819
+ margin-top: 6px;
820
+ font-weight: 600;
821
+ color: #34D399;
822
+ text-decoration: none;
823
+ }
824
+ .success-link:hover { text-decoration: underline; }
825
+
826
+ .chat-input-box {
827
+ padding: 16px;
828
+ border-top: 1px solid #27272A;
829
+ background: #131316;
830
+ }
831
+
832
+ .chat-input-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
833
+
834
+ .chat-input {
835
+ flex: 1;
836
+ min-width: 200px;
837
+ background: #18181B;
838
+ border: 1px solid #27272A;
839
+ color: white;
840
+ padding: 10px 12px;
841
+ border-radius: 8px;
842
+ outline: none;
843
+ font-size: 14px;
844
+ font-family: inherit;
845
+ resize: none;
846
+ min-height: 40px;
847
+ max-height: 160px;
848
+ line-height: 1.4;
849
+ }
850
+
851
+ /* Enterprise controls (restored) */
852
+ .chat-btn {
853
+ height: 38px;
854
+ padding: 0 14px;
855
+ border-radius: 8px;
856
+ font-weight: 700;
857
+ cursor: pointer;
858
+ border: 1px solid transparent;
859
+ font-size: 13px;
860
+ white-space: nowrap;
861
+ }
862
+
863
+ /* Orange primary (old style) */
864
+ .chat-btn.primary { background: #D95C3D; color: #fff; }
865
+ .chat-btn.primary:hover { filter: brightness(0.98); }
866
+ .chat-btn.primary:disabled { opacity: 0.55; cursor: not-allowed; }
867
+
868
+ /* Secondary outline */
869
+ .chat-btn.secondary {
870
+ background: transparent;
871
+ border: 1px solid #3F3F46;
872
+ color: #A1A1AA;
873
+ }
874
+ .chat-btn.secondary:hover { background: rgba(255,255,255,0.04); }
875
+ .chat-btn.secondary:disabled { opacity: 0.55; cursor: not-allowed; }
876
+
877
+ .chat-empty-state {
878
+ text-align: center;
879
+ color: #52525B;
880
+ margin-top: 40px;
881
+ font-size: 14px;
882
+ }
883
+
884
+ /* WebSocket connection indicator */
885
+ .ws-indicator {
886
+ display: inline-flex;
887
+ align-items: center;
888
+ gap: 4px;
889
+ font-size: 10px;
890
+ color: #71717A;
891
+ padding: 2px 6px;
892
+ border-radius: 4px;
893
+ background: rgba(24, 24, 27, 0.6);
894
+ }
895
+ .ws-dot {
896
+ width: 6px;
897
+ height: 6px;
898
+ border-radius: 50%;
899
+ }
900
+
901
+ @keyframes blink {
902
+ 0%, 100% { opacity: 1; }
903
+ 50% { opacity: 0; }
904
+ }
905
+ `}</style>
906
+
907
+ <div className="chat-messages">
908
+ {messages.map((m, idx) => {
909
+ // Success message (App.jsx injected)
910
+ if (m.isSuccess) {
911
+ return (
912
+ <div key={idx} className="chat-msg-success">
913
+ <div className="success-icon">🚀</div>
914
+ <div>
915
+ <div style={{ whiteSpace: "pre-wrap" }}>{m.content}</div>
916
+ {m.link && (
917
+ <a href={m.link} target="_blank" rel="noreferrer" className="success-link">
918
+ View Changes on GitHub &rarr;
919
+ </a>
920
+ )}
921
+ </div>
922
+ </div>
923
+ );
924
+ }
925
+
926
+ // User message
927
+ if (m.from === "user" || m.role === "user") {
928
+ return (
929
+ <div key={idx} className="chat-message-user">
930
+ <span>{m.text || m.content}</span>
931
+ </div>
932
+ );
933
+ }
934
+
935
+ // Assistant message (Answer / Plan / Execution Log).
936
+ //
937
+ // Lifecycle audit signal: if this message carries a plan, look
938
+ // ahead in the timeline for any subsequent message that
939
+ // records an execution log (=> the plan was approved+executed)
940
+ // or a system "Plan rejected" entry (=> the plan was
941
+ // rejected). The status is rendered as a small green/grey
942
+ // badge next to the Action Plan header so users can tell at a
943
+ // glance — in history — whether a previous plan was acted on.
944
+ let planStatus = null;
945
+ if (m.plan) {
946
+ const after = messages.slice(idx + 1);
947
+ if (after.some((later) => later.executionLog)) {
948
+ planStatus = "executed";
949
+ } else if (
950
+ after.some(
951
+ (later) =>
952
+ later.role === "system" &&
953
+ typeof later.content === "string" &&
954
+ later.content.includes("Plan rejected"),
955
+ )
956
+ ) {
957
+ planStatus = "rejected";
958
+ }
959
+ }
960
+
961
+ // Find the plan that was approved for this completion, so the
962
+ // success receipt can label actions (READ/CREATE/...) instead of
963
+ // showing only an opaque execution dump.
964
+ let linkedPlan = null;
965
+ if (m.executionLog) {
966
+ for (let i = idx - 1; i >= 0; i--) {
967
+ if (messages[i].plan?.steps) {
968
+ linkedPlan = messages[i].plan;
969
+ break;
970
+ }
971
+ }
972
+ }
973
+
974
+ return (
975
+ <div key={idx}>
976
+ <AssistantMessage
977
+ answer={m.answer || m.content}
978
+ plan={m.plan}
979
+ executionLog={m.executionLog}
980
+ planStatus={planStatus}
981
+ owner={repo?.owner}
982
+ repo={repo?.name}
983
+ onApproveExecution={() => execute()}
984
+ nextActions={m.nextActions}
985
+ relatedPlan={linkedPlan}
986
+ diff={m.diff}
987
+ branch={m.branch || currentBranch}
988
+ />
989
+ {/* Diff stats indicator (Claude-Code-on-Web parity) */}
990
+ {m.diff && (
991
+ <DiffStats diff={m.diff} onClick={() => {
992
+ setDiffData(m.diff);
993
+ setShowDiffViewer(true);
994
+ }} />
995
+ )}
996
+ </div>
997
+ );
998
+ })}
999
+
1000
+ {/* Streaming events (real-time agent output) */}
1001
+ {streamingEvents.length > 0 && (
1002
+ <div>
1003
+ <StreamingMessage events={streamingEvents} />
1004
+ </div>
1005
+ )}
1006
+
1007
+ {/* Enterprise Pulse — agentic thinking state shown after the user
1008
+ hits Send and before the first streamed/planned chunk arrives.
1009
+ Falls back gracefully to nothing once streamingEvents start
1010
+ flowing in (StreamingMessage takes over the live feedback). */}
1011
+ {loadingPlan && streamingEvents.length === 0 && (
1012
+ <ThinkingIndicator />
1013
+ )}
1014
+
1015
+ {/* Live execution status — visible in the chat timeline while
1016
+ ``executing`` is true, sits between the Action Plan card and
1017
+ where the Execution Log (green panel in AssistantMessage)
1018
+ will land once the backend returns. Removes the "did the
1019
+ app freeze?" feeling caused by only the bottom button
1020
+ saying "Executing…".
1021
+
1022
+ Reuses the ThinkingIndicator with execution-specific labels.
1023
+ When the executor finishes, ``setExecuting(false)`` removes
1024
+ this bubble and the completionMsg lands in the timeline as
1025
+ a normal assistant message with its green Execution Log
1026
+ block — already rendered by AssistantMessage today. */}
1027
+ {executing && (
1028
+ <ThinkingIndicator
1029
+ labels={[
1030
+ "Executing plan",
1031
+ "Applying changes",
1032
+ "Verifying result",
1033
+ ]}
1034
+ />
1035
+ )}
1036
+
1037
+ {!messages.length && !plan && !loadingPlan && streamingEvents.length === 0 && (
1038
+ <div className="chat-empty-state">
1039
+ <div className="chat-empty-icon">💬</div>
1040
+ <p>Tell GitPilot what you want to do with this repository.</p>
1041
+ <p style={{ fontSize: 12, color: "#676883", marginTop: 4 }}>
1042
+ It will propose a safe step-by-step plan before any execution.
1043
+ </p>
1044
+ </div>
1045
+ )}
1046
+
1047
+ <div ref={messagesEndRef} />
1048
+ </div>
1049
+
1050
+ {/* Batch B9 — post-Reject "retry with grep" prompt. Renders
1051
+ only when the user rejected a plan whose first step was an
1052
+ INDEX action. One click re-issues the same goal with
1053
+ force_no_rag so the router falls back to grep. */}
1054
+ {retryAfterIndexReject && !loadingPlan && (
1055
+ <div
1056
+ style={{
1057
+ padding: "10px 16px",
1058
+ borderTop: "1px solid #27272A",
1059
+ background: "rgba(217, 92, 61, 0.06)",
1060
+ display: "flex",
1061
+ alignItems: "center",
1062
+ justifyContent: "space-between",
1063
+ gap: 12,
1064
+ flexWrap: "wrap",
1065
+ }}
1066
+ >
1067
+ <span style={{ fontSize: 13, color: "#D4D4D8" }}>
1068
+ Index skipped. Run the same goal with grep instead?
1069
+ </span>
1070
+ <span style={{ display: "inline-flex", gap: 8 }}>
1071
+ <button
1072
+ type="button"
1073
+ className="chat-btn primary"
1074
+ onClick={() => {
1075
+ const g = retryAfterIndexReject.goal;
1076
+ setRetryAfterIndexReject(null);
1077
+ send({ goal: g, force_no_rag: true });
1078
+ }}
1079
+ >
1080
+ Yes, use grep
1081
+ </button>
1082
+ <button
1083
+ type="button"
1084
+ className="chat-btn ghost"
1085
+ onClick={() => setRetryAfterIndexReject(null)}
1086
+ style={{
1087
+ color: "#9CA3AF",
1088
+ borderColor: "rgba(156, 163, 175, 0.35)",
1089
+ background: "transparent",
1090
+ }}
1091
+ >
1092
+ No, dismiss
1093
+ </button>
1094
+ </span>
1095
+ </div>
1096
+ )}
1097
+
1098
+ {/* Diff stats bar (when agent has made changes) */}
1099
+ {diffData && (
1100
+ <div style={{
1101
+ padding: "8px 16px",
1102
+ borderTop: "1px solid #27272A",
1103
+ background: "#18181B",
1104
+ }}>
1105
+ <DiffStats diff={diffData} onClick={() => setShowDiffViewer(true)} />
1106
+ </div>
1107
+ )}
1108
+
1109
+ <div className="chat-input-box">
1110
+ {/* Readiness blocker banner */}
1111
+ {!canChat && chatBlocker && (
1112
+ <div style={{
1113
+ fontSize: 12,
1114
+ color: "#F59E0B",
1115
+ background: "rgba(245, 158, 11, 0.08)",
1116
+ border: "1px solid rgba(245, 158, 11, 0.2)",
1117
+ borderRadius: 6,
1118
+ padding: "8px 12px",
1119
+ marginBottom: 8,
1120
+ display: "flex",
1121
+ alignItems: "center",
1122
+ justifyContent: "space-between",
1123
+ }}>
1124
+ <span>{chatBlocker.message || "Chat is not ready yet."}</span>
1125
+ {chatBlocker.cta && chatBlocker.onCta && (
1126
+ <button
1127
+ type="button"
1128
+ onClick={chatBlocker.onCta}
1129
+ style={{
1130
+ fontSize: 11,
1131
+ fontWeight: 600,
1132
+ color: "#F59E0B",
1133
+ background: "transparent",
1134
+ border: "1px solid rgba(245, 158, 11, 0.3)",
1135
+ borderRadius: 4,
1136
+ padding: "2px 8px",
1137
+ cursor: "pointer",
1138
+ }}
1139
+ >
1140
+ {chatBlocker.cta}
1141
+ </button>
1142
+ )}
1143
+ </div>
1144
+ )}
1145
+ {status && (
1146
+ <div style={{ fontSize: 11, color: "#ffb3b7", marginBottom: 8 }}>
1147
+ {status}
1148
+ </div>
1149
+ )}
1150
+
1151
+ <div className="chat-input-row">
1152
+ <textarea
1153
+ className="chat-input"
1154
+ placeholder={wsConnected ? "Send feedback or instructions..." : "Describe the change you want to make..."}
1155
+ value={goal}
1156
+ rows={1}
1157
+ onChange={(e) => {
1158
+ setGoal(e.target.value);
1159
+ e.target.style.height = "40px";
1160
+ e.target.style.height = Math.min(e.target.scrollHeight, 160) + "px";
1161
+ }}
1162
+ onKeyDown={(e) => {
1163
+ if (e.key === "Enter" && !e.shiftKey) {
1164
+ e.preventDefault();
1165
+ if (!loadingPlan && !executing) send();
1166
+ }
1167
+ }}
1168
+ disabled={!canChat || loadingPlan || executing}
1169
+ />
1170
+
1171
+ {/* Always show both buttons (old UX) */}
1172
+ <button
1173
+ className="chat-btn primary"
1174
+ type="button"
1175
+ onClick={send}
1176
+ disabled={!canChat || loadingPlan || executing || !goal.trim()}
1177
+ >
1178
+ {loadingPlan ? "Planning..." : wsConnected ? "Send" : "Generate plan"}
1179
+ </button>
1180
+
1181
+ {/* Approve & execute — visible only while a plan is awaiting
1182
+ approval, or while an execution is already in flight (so
1183
+ the user sees the "Executing…" label, not a missing
1184
+ button). Previously this was always rendered with
1185
+ ``disabled={!plan}``, which meant after a successful
1186
+ execute() the button stayed on screen as a dimmed ghost
1187
+ and a second click could trigger a duplicate run —
1188
+ causing the executor to re-write the same file with the
1189
+ same content (~50 s of wasted LLM time per accidental
1190
+ click). Hiding the button entirely once ``plan`` is
1191
+ null makes the bug impossible. */}
1192
+ {(plan || executing) && (
1193
+ <button
1194
+ className="chat-btn secondary"
1195
+ type="button"
1196
+ onClick={execute}
1197
+ disabled={executing || loadingPlan}
1198
+ >
1199
+ {executing ? "Executing..." : "Approve & execute"}
1200
+ </button>
1201
+ )}
1202
+
1203
+ {/* Reject plan — same visibility window as Approve. */}
1204
+ {plan && !executing && !loadingPlan && (
1205
+ <button
1206
+ className="chat-btn ghost"
1207
+ type="button"
1208
+ onClick={rejectPlan}
1209
+ title="Discard this plan. No files will be changed."
1210
+ style={{
1211
+ color: "#F87171",
1212
+ borderColor: "rgba(248, 113, 113, 0.35)",
1213
+ background: "transparent",
1214
+ }}
1215
+ >
1216
+ Reject plan
1217
+ </button>
1218
+ )}
1219
+
1220
+ {/* Create PR button (Claude-Code-on-Web parity) */}
1221
+ {isOnSessionBranch && (
1222
+ <CreatePRButton
1223
+ repo={repo}
1224
+ sessionId={sessionId}
1225
+ branch={currentBranch}
1226
+ defaultBranch={defaultBranch}
1227
+ disabled={executing || loadingPlan}
1228
+ />
1229
+ )}
1230
+ </div>
1231
+
1232
+ {/* WebSocket connection indicator + context-window meter */}
1233
+ <div style={{ marginTop: 6, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
1234
+ <span>
1235
+ {sessionId && (
1236
+ <span className="ws-indicator">
1237
+ <span className="ws-dot" style={{
1238
+ backgroundColor: wsConnected ? "#10B981" : "#EF4444",
1239
+ }} />
1240
+ {wsConnected ? "Live" : "Connecting..."}
1241
+ </span>
1242
+ )}
1243
+ </span>
1244
+ <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
1245
+ <TasksPanel sessionId={sessionId} />
1246
+ <ContextMeter sessionId={sessionId} />
1247
+ </span>
1248
+ </div>
1249
+ </div>
1250
+
1251
+ {/* Diff Viewer overlay */}
1252
+ {showDiffViewer && (
1253
+ <DiffViewer
1254
+ diff={diffData}
1255
+ onClose={() => setShowDiffViewer(false)}
1256
+ />
1257
+ )}
1258
+
1259
+ {/* FilePreviewPanel — read-first viewer. Opens on a file row
1260
+ click in the sidebar. Header carries Prepare Run (runnable
1261
+ only), Open Workspace, and an overflow menu. */}
1262
+ {previewPath && (
1263
+ <FilePreviewPanel
1264
+ path={previewPath}
1265
+ content={previewContent}
1266
+ loading={previewLoading}
1267
+ error={previewError}
1268
+ errorCode={previewErrorCode}
1269
+ notFoundKind={
1270
+ fileWasJustDeletedRef.current.has(previewPath)
1271
+ ? "deleted"
1272
+ : fileWasJustCreatedRef.current.has(previewPath)
1273
+ ? "syncing"
1274
+ : "unavailable"
1275
+ }
1276
+ mode={previewMode}
1277
+ branch={currentBranch}
1278
+ onModeChange={setPreviewMode}
1279
+ onRefreshTree={() => {
1280
+ try {
1281
+ window.dispatchEvent(new CustomEvent("gitpilot:refresh-tree"));
1282
+ } catch (_e) { /* old browser */ }
1283
+ }}
1284
+ onRetry={() => {
1285
+ const p = previewPath;
1286
+ const m = previewMode;
1287
+ setPreviewPath(null);
1288
+ // Fire the same window event we listened to — keeps the
1289
+ // retry path identical to the original load and lets any
1290
+ // future side-effects (e.g. analytics) see one event class.
1291
+ setTimeout(() => window.dispatchEvent(new CustomEvent(
1292
+ m === "workspace" ? "gitpilot:open-workspace" : "gitpilot:open-file",
1293
+ { detail: { path: p } },
1294
+ )), 0);
1295
+ }}
1296
+ onClose={() => {
1297
+ try {
1298
+ window.dispatchEvent(new CustomEvent("gitpilot:file-closed"));
1299
+ } catch (_e) {/* old browser */}
1300
+ setPreviewPath(null);
1301
+ setPreviewContent(null);
1302
+ setPreviewError(null);
1303
+ setPreviewErrorCode(null);
1304
+ }}
1305
+ />
1306
+ )}
1307
+
1308
+ {/* SandboxCanvas overlay — opened by "Open in Canvas" next_action
1309
+ buttons and ExecutionCard footers via the
1310
+ gitpilot:open-in-canvas window event. */}
1311
+ {canvasSpec && (
1312
+ <SandboxCanvas
1313
+ initialLanguage={canvasSpec.language}
1314
+ initialCode={canvasSpec.code}
1315
+ filename={canvasSpec.filename}
1316
+ onClose={() => { setCanvasSpec(null); setCanvasError(null); }}
1317
+ />
1318
+ )}
1319
+ {canvasError && canvasSpec && (
1320
+ <div style={{
1321
+ position: "fixed", bottom: 16, right: 16, zIndex: 110,
1322
+ padding: "8px 12px", maxWidth: 380, fontSize: 12,
1323
+ color: "#fca5a5", background: "#3d1111",
1324
+ border: "1px solid #7f1d1d", borderRadius: 6,
1325
+ }}>
1326
+ {canvasError}
1327
+ </div>
1328
+ )}
1329
+ </div>
1330
+ );
1331
+ }
frontend/components/ContextBar.jsx ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useCallback, useRef, useState } from "react";
2
+ import BranchPicker from "./BranchPicker.jsx";
3
+
4
+ /**
5
+ * ContextBar — horizontal repo chip bar for multi-repo workspace context.
6
+ *
7
+ * Uses CSS classes for hover-reveal X (Claude-style: subtle by default,
8
+ * visible on chip hover, red on X hover). Each chip owns its own remove
9
+ * button — removing one repo never affects the others.
10
+ */
11
+ export default function ContextBar({
12
+ contextRepos,
13
+ activeRepoKey,
14
+ repoStateByKey,
15
+ onActivate,
16
+ onRemove,
17
+ onAdd,
18
+ onBranchChange,
19
+ mode, // workspace mode: "github", "local-git", "folder" (optional)
20
+ }) {
21
+ if (!contextRepos || contextRepos.length === 0) return null;
22
+
23
+ return (
24
+ <div className="ctxbar">
25
+ {/* Workspace mode indicator */}
26
+ {mode && (
27
+ <span className="ctxbar-mode" title={`Workspace mode: ${mode}`}>
28
+ {mode === "github" ? "GH" : mode === "local-git" ? "Git" : "Dir"}
29
+ </span>
30
+ )}
31
+ <div className="ctxbar-scroll">
32
+ {contextRepos.map((entry) => {
33
+ const isActive = entry.repoKey === activeRepoKey;
34
+ return (
35
+ <RepoChip
36
+ key={entry.repoKey}
37
+ entry={entry}
38
+ isActive={isActive}
39
+ repoState={repoStateByKey?.[entry.repoKey]}
40
+ onActivate={() => onActivate(entry.repoKey)}
41
+ onRemove={() => onRemove(entry.repoKey)}
42
+ onBranchChange={(newBranch) =>
43
+ onBranchChange(entry.repoKey, newBranch)
44
+ }
45
+ />
46
+ );
47
+ })}
48
+
49
+ <button
50
+ type="button"
51
+ className="ctxbar-add"
52
+ onClick={onAdd}
53
+ title="Add repository to context"
54
+ >
55
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
56
+ <line x1="12" y1="5" x2="12" y2="19" />
57
+ <line x1="5" y1="12" x2="19" y2="12" />
58
+ </svg>
59
+ </button>
60
+ </div>
61
+
62
+ <div className="ctxbar-meta">
63
+ {contextRepos.length} {contextRepos.length === 1 ? "repo" : "repos"}
64
+ </div>
65
+ </div>
66
+ );
67
+ }
68
+
69
+ function RepoChip({ entry, isActive, repoState, onActivate, onRemove, onBranchChange }) {
70
+ const [branchOpen, setBranchOpen] = useState(false);
71
+ const [hovered, setHovered] = useState(false);
72
+ const branchBtnRef = useRef(null);
73
+ const repo = entry.repo;
74
+ const branch = repoState?.currentBranch || entry.branch || repo?.default_branch || "main";
75
+ const defaultBranch = repoState?.defaultBranch || repo?.default_branch || "main";
76
+ const sessionBranches = repoState?.sessionBranches || [];
77
+ const displayName = repo?.name || entry.repoKey?.split("/")[1] || entry.repoKey;
78
+
79
+ const handleChipClick = useCallback(
80
+ (e) => {
81
+ if (e.target.closest("[data-chip-action]")) return;
82
+ onActivate();
83
+ },
84
+ [onActivate]
85
+ );
86
+
87
+ return (
88
+ <div
89
+ className={"ctxbar-chip" + (isActive ? " ctxbar-chip-active" : "")}
90
+ onClick={handleChipClick}
91
+ onMouseEnter={() => setHovered(true)}
92
+ onMouseLeave={() => setHovered(false)}
93
+ title={isActive ? `Active (write): ${entry.repoKey}` : `Click to activate ${entry.repoKey}`}
94
+ >
95
+ {/* Active indicator bar */}
96
+ {isActive && <div className="ctxbar-chip-indicator" />}
97
+
98
+ {/* Repo name */}
99
+ <span className="ctxbar-chip-name">{displayName}</span>
100
+
101
+ {/* Separator dot */}
102
+ <span className="ctxbar-chip-dot" />
103
+
104
+ {/* Branch name — single click opens GitHub branch list */}
105
+ <button
106
+ ref={branchBtnRef}
107
+ type="button"
108
+ data-chip-action="branch"
109
+ className={"ctxbar-chip-branch" + (isActive ? " ctxbar-chip-branch-active" : "")}
110
+ onClick={(e) => {
111
+ e.stopPropagation();
112
+ setBranchOpen((v) => !v);
113
+ }}
114
+ >
115
+ {branch}
116
+ </button>
117
+
118
+ {/* Write badge for active repo */}
119
+ {isActive && <span className="ctxbar-chip-write">write</span>}
120
+
121
+ {/* Remove button: hidden by default, revealed on hover */}
122
+ <button
123
+ type="button"
124
+ data-chip-action="remove"
125
+ className={"ctxbar-chip-remove" + (hovered ? " ctxbar-chip-remove-visible" : "")}
126
+ onClick={(e) => {
127
+ e.stopPropagation();
128
+ onRemove();
129
+ }}
130
+ title={`Remove ${displayName} from context`}
131
+ >
132
+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
133
+ <line x1="18" y1="6" x2="6" y2="18" />
134
+ <line x1="6" y1="6" x2="18" y2="18" />
135
+ </svg>
136
+ </button>
137
+
138
+ {/* BranchPicker in external-anchor mode: dropdown opens immediately,
139
+ positioned from the branch button, fetches all branches from GitHub */}
140
+ {branchOpen && (
141
+ <BranchPicker
142
+ repo={repo}
143
+ currentBranch={branch}
144
+ defaultBranch={defaultBranch}
145
+ sessionBranches={sessionBranches}
146
+ externalAnchorRef={branchBtnRef}
147
+ onBranchChange={(newBranch) => {
148
+ onBranchChange(newBranch);
149
+ setBranchOpen(false);
150
+ }}
151
+ onClose={() => setBranchOpen(false)}
152
+ />
153
+ )}
154
+ </div>
155
+ );
156
+ }
frontend/components/ContextMeter.jsx ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/ContextMeter.jsx
2
+ //
3
+ // Small bottom-right control that shows the active LLM's context-window
4
+ // utilisation. Collapsed: a single ⓘ icon (no number — keeps the UI
5
+ // quiet during normal use). Expanded: a compact popover with the
6
+ // breakdown, topology line, and a manual refresh button.
7
+ //
8
+ // Refresh model: lazy — fetched only when the popover opens, plus the
9
+ // explicit ↻ button. Zero idle traffic.
10
+ //
11
+ // Token-count estimate flag: when the backend reports is_estimate=true
12
+ // (Ollama / OllaBridge — no real tokenizer available) every number is
13
+ // prefixed with ≈ so the imprecision is visible.
14
+ //
15
+ // Colours: GitPilot orange #D95C3D for ≥60% (warning), red #B91C1C for
16
+ // ≥85% (saturated). No new dependencies; inline styles + a scoped
17
+ // <style> block for animations / focus rings.
18
+
19
+ import React, { useEffect, useRef, useState } from "react";
20
+ import { apiUrl } from "../utils/api.js";
21
+
22
+ const GITPILOT_ORANGE = "#D95C3D";
23
+ const SATURATED_RED = "#B91C1C";
24
+ const DIM = "#9aa0b4";
25
+ const SLATE = "#6b7280";
26
+
27
+ const fmt = (n) => {
28
+ if (n == null) return "—";
29
+ return new Intl.NumberFormat("en-US").format(n);
30
+ };
31
+
32
+ const pct = (used, total) => {
33
+ if (!total) return 0;
34
+ return Math.max(0, Math.min(100, (100 * used) / total));
35
+ };
36
+
37
+ const colourFor = (percent) => {
38
+ if (percent >= 85) return SATURATED_RED;
39
+ if (percent >= 60) return GITPILOT_ORANGE;
40
+ return SLATE;
41
+ };
42
+
43
+ function Bar({ percent, colour }) {
44
+ // 16-segment monochrome bar, matching the ASCII design.
45
+ const filled = Math.round((percent / 100) * 16);
46
+ const segs = [];
47
+ for (let i = 0; i < 16; i++) {
48
+ segs.push(
49
+ <span
50
+ key={i}
51
+ aria-hidden="true"
52
+ style={{
53
+ display: "inline-block",
54
+ width: 6,
55
+ height: 8,
56
+ marginRight: 1,
57
+ background: i < filled ? colour : "rgba(255,255,255,0.08)",
58
+ borderRadius: 1,
59
+ }}
60
+ />,
61
+ );
62
+ }
63
+ return (
64
+ <span style={{ display: "inline-flex", alignItems: "center", lineHeight: 1 }}>
65
+ {segs}
66
+ </span>
67
+ );
68
+ }
69
+
70
+ function Row({ label, tokens, total, estimate, accent }) {
71
+ const p = pct(tokens, total);
72
+ const prefix = estimate ? "≈ " : "";
73
+ return (
74
+ <div
75
+ style={{
76
+ display: "grid",
77
+ gridTemplateColumns: "1fr auto auto",
78
+ gap: 12,
79
+ padding: "4px 0",
80
+ fontSize: 12,
81
+ color: accent ? "#e5e7eb" : DIM,
82
+ fontVariantNumeric: "tabular-nums",
83
+ }}
84
+ >
85
+ <span>{label}</span>
86
+ <span style={{ color: accent ? "#e5e7eb" : "#cbd1e3" }}>
87
+ {prefix}
88
+ {fmt(tokens)}
89
+ </span>
90
+ <span style={{ width: 48, textAlign: "right" }}>{p.toFixed(1)}%</span>
91
+ </div>
92
+ );
93
+ }
94
+
95
+ export default function ContextMeter({ sessionId = null }) {
96
+ const [open, setOpen] = useState(false);
97
+ const [data, setData] = useState(null);
98
+ const [loading, setLoading] = useState(false);
99
+ const [error, setError] = useState(null);
100
+ const popoverRef = useRef(null);
101
+ const triggerRef = useRef(null);
102
+
103
+ const fetchUsage = async () => {
104
+ setLoading(true);
105
+ setError(null);
106
+ try {
107
+ const qs = sessionId ? `?session_id=${encodeURIComponent(sessionId)}` : "";
108
+ const r = await fetch(apiUrl(`/api/context/usage${qs}`));
109
+ if (!r.ok) {
110
+ // 404 means the feature flag is off — render nothing in that case.
111
+ if (r.status === 404) {
112
+ setError("disabled");
113
+ setData(null);
114
+ } else {
115
+ setError(`http ${r.status}`);
116
+ }
117
+ } else {
118
+ setData(await r.json());
119
+ }
120
+ } catch (e) {
121
+ setError(String(e?.message || e));
122
+ } finally {
123
+ setLoading(false);
124
+ }
125
+ };
126
+
127
+ // Refetch every time the popover opens so the user sees the *current*
128
+ // numbers after each plan/execute cycle — not a frozen snapshot from
129
+ // first open. The endpoint is cheap (single-digit-ms after the first
130
+ // provider probe), so re-fetch-on-open is the honest default.
131
+ useEffect(() => {
132
+ if (open) {
133
+ fetchUsage();
134
+ }
135
+ }, [open, sessionId]); // eslint-disable-line react-hooks/exhaustive-deps
136
+
137
+ // Invalidate the displayed snapshot when the active session changes
138
+ // so we don't briefly show another session's numbers.
139
+ useEffect(() => {
140
+ setData(null);
141
+ }, [sessionId]);
142
+
143
+ // Click-outside + Esc to close.
144
+ useEffect(() => {
145
+ if (!open) return;
146
+ const onDocClick = (e) => {
147
+ if (
148
+ popoverRef.current &&
149
+ !popoverRef.current.contains(e.target) &&
150
+ triggerRef.current &&
151
+ !triggerRef.current.contains(e.target)
152
+ ) {
153
+ setOpen(false);
154
+ }
155
+ };
156
+ const onKey = (e) => {
157
+ if (e.key === "Escape") setOpen(false);
158
+ };
159
+ document.addEventListener("mousedown", onDocClick);
160
+ document.addEventListener("keydown", onKey);
161
+ return () => {
162
+ document.removeEventListener("mousedown", onDocClick);
163
+ document.removeEventListener("keydown", onKey);
164
+ };
165
+ }, [open]);
166
+
167
+ // Feature flag off — render nothing.
168
+ if (error === "disabled") return null;
169
+
170
+ const percent = data ? data.percent_used : 0;
171
+ const bar = colourFor(percent);
172
+ const estimate = data?.is_estimate;
173
+ const prefix = estimate ? "≈ " : "";
174
+
175
+ return (
176
+ <span
177
+ className="gitpilot-ctx-meter"
178
+ style={{ position: "relative", display: "inline-flex" }}
179
+ >
180
+ <style>{`
181
+ .gitpilot-ctx-meter .ctx-trigger {
182
+ background: transparent;
183
+ border: 1px solid rgba(255,255,255,0.12);
184
+ color: ${DIM};
185
+ width: 22px;
186
+ height: 22px;
187
+ border-radius: 11px;
188
+ display: inline-flex;
189
+ align-items: center;
190
+ justify-content: center;
191
+ font-size: 12px;
192
+ line-height: 1;
193
+ cursor: pointer;
194
+ padding: 0;
195
+ transition: color 120ms ease, border-color 120ms ease;
196
+ }
197
+ .gitpilot-ctx-meter .ctx-trigger:hover,
198
+ .gitpilot-ctx-meter .ctx-trigger:focus-visible {
199
+ color: #e5e7eb;
200
+ border-color: rgba(255,255,255,0.28);
201
+ outline: none;
202
+ }
203
+ .gitpilot-ctx-meter .ctx-trigger[data-warn="1"] { color: ${GITPILOT_ORANGE}; border-color: ${GITPILOT_ORANGE}55; }
204
+ .gitpilot-ctx-meter .ctx-trigger[data-sat="1"] { color: ${SATURATED_RED}; border-color: ${SATURATED_RED}55; }
205
+ .gitpilot-ctx-meter .ctx-popover {
206
+ position: absolute;
207
+ right: 0;
208
+ bottom: calc(100% + 8px);
209
+ width: 360px;
210
+ background: #1a1c25;
211
+ border: 1px solid rgba(255,255,255,0.10);
212
+ border-radius: 8px;
213
+ box-shadow: 0 8px 24px rgba(0,0,0,0.45);
214
+ padding: 14px 16px;
215
+ z-index: 50;
216
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
217
+ }
218
+ .gitpilot-ctx-meter .ctx-popover h4 {
219
+ margin: 0 0 10px 0;
220
+ font-size: 12px;
221
+ font-weight: 600;
222
+ letter-spacing: 0.04em;
223
+ text-transform: uppercase;
224
+ color: ${DIM};
225
+ }
226
+ .gitpilot-ctx-meter .ctx-meta {
227
+ display: grid;
228
+ grid-template-columns: 84px 1fr;
229
+ gap: 2px 12px;
230
+ font-size: 12px;
231
+ color: #cbd1e3;
232
+ margin-bottom: 12px;
233
+ font-variant-numeric: tabular-nums;
234
+ }
235
+ .gitpilot-ctx-meter .ctx-meta .k { color: ${DIM}; }
236
+ .gitpilot-ctx-meter .ctx-divider {
237
+ height: 1px;
238
+ background: rgba(255,255,255,0.08);
239
+ margin: 6px 0;
240
+ }
241
+ .gitpilot-ctx-meter .ctx-footer {
242
+ display: flex;
243
+ justify-content: space-between;
244
+ align-items: center;
245
+ margin-top: 10px;
246
+ font-size: 11px;
247
+ color: ${DIM};
248
+ }
249
+ .gitpilot-ctx-meter .ctx-refresh {
250
+ background: transparent;
251
+ border: 1px solid rgba(255,255,255,0.14);
252
+ color: #cbd1e3;
253
+ font-size: 11px;
254
+ padding: 2px 8px;
255
+ border-radius: 4px;
256
+ cursor: pointer;
257
+ }
258
+ .gitpilot-ctx-meter .ctx-refresh:hover { color: #fff; border-color: rgba(255,255,255,0.3); }
259
+ .gitpilot-ctx-meter .ctx-refresh:disabled { opacity: 0.5; cursor: default; }
260
+ .gitpilot-ctx-meter .ctx-warn {
261
+ margin-top: 10px;
262
+ padding: 8px 10px;
263
+ border: 1px solid ${GITPILOT_ORANGE}55;
264
+ background: ${GITPILOT_ORANGE}14;
265
+ color: ${GITPILOT_ORANGE};
266
+ border-radius: 4px;
267
+ font-size: 11px;
268
+ line-height: 1.5;
269
+ }
270
+ .gitpilot-ctx-meter .ctx-warn[data-sat="1"] {
271
+ border-color: ${SATURATED_RED}66;
272
+ background: ${SATURATED_RED}14;
273
+ color: ${SATURATED_RED};
274
+ }
275
+ .gitpilot-ctx-meter .ctx-warn ul { margin: 4px 0 0 18px; padding: 0; }
276
+ `}</style>
277
+
278
+ <button
279
+ ref={triggerRef}
280
+ type="button"
281
+ className="ctx-trigger"
282
+ aria-label="Context window usage"
283
+ aria-haspopup="dialog"
284
+ aria-expanded={open}
285
+ data-warn={data && percent >= 60 && percent < 85 ? "1" : "0"}
286
+ data-sat={data && percent >= 85 ? "1" : "0"}
287
+ onClick={() => setOpen((v) => !v)}
288
+ title="Context window usage"
289
+ >
290
+ {"ⓘ"}
291
+ </button>
292
+
293
+ {open && (
294
+ <div
295
+ ref={popoverRef}
296
+ className="ctx-popover"
297
+ role="dialog"
298
+ aria-label="Context window usage details"
299
+ >
300
+ <h4>Context window</h4>
301
+
302
+ {loading && !data && (
303
+ <div style={{ color: DIM, fontSize: 12 }}>Loading…</div>
304
+ )}
305
+ {error && error !== "disabled" && (
306
+ <div style={{ color: "#ffb3b7", fontSize: 12 }}>
307
+ Couldn't load: {error}
308
+ </div>
309
+ )}
310
+
311
+ {data && (
312
+ <>
313
+ <div className="ctx-meta">
314
+ <span className="k">Provider</span>
315
+ <span>{data.provider}</span>
316
+ <span className="k">Model</span>
317
+ <span>{data.model || "—"}</span>
318
+ <span className="k">Topology</span>
319
+ <span>{data.topology}</span>
320
+ </div>
321
+
322
+ <div
323
+ style={{
324
+ display: "flex",
325
+ justifyContent: "space-between",
326
+ alignItems: "center",
327
+ fontSize: 12,
328
+ color: "#cbd1e3",
329
+ fontVariantNumeric: "tabular-nums",
330
+ marginBottom: 8,
331
+ }}
332
+ >
333
+ <Bar percent={percent} colour={bar} />
334
+ <span>
335
+ {prefix}
336
+ {fmt(data.used)} / {fmt(data.context_window)}{" "}
337
+ <span style={{ color: bar }}>({percent.toFixed(1)}%)</span>
338
+ </span>
339
+ </div>
340
+
341
+ <Row
342
+ label="Conversation messages"
343
+ tokens={data.breakdown?.messages || 0}
344
+ total={data.context_window}
345
+ estimate={estimate}
346
+ />
347
+ <Row
348
+ label="Planner system prompt"
349
+ tokens={data.breakdown?.system_prompt || 0}
350
+ total={data.context_window}
351
+ estimate={estimate}
352
+ />
353
+ <Row
354
+ label="Repo context summary"
355
+ tokens={data.breakdown?.repo_context || 0}
356
+ total={data.context_window}
357
+ estimate={estimate}
358
+ />
359
+ <Row
360
+ label={`Tool schemas (${data.tool_count || 0})`}
361
+ tokens={data.breakdown?.tool_schemas || 0}
362
+ total={data.context_window}
363
+ estimate={estimate}
364
+ />
365
+ <Row
366
+ label="Reserved for response"
367
+ tokens={data.reserved_response}
368
+ total={data.context_window}
369
+ estimate={false}
370
+ />
371
+
372
+ <div className="ctx-divider" />
373
+
374
+ <Row
375
+ label="Free space"
376
+ tokens={data.free}
377
+ total={data.context_window}
378
+ estimate={estimate}
379
+ accent
380
+ />
381
+
382
+ {percent >= 85 && (
383
+ <div className="ctx-warn" data-sat={percent >= 95 ? "1" : "0"}>
384
+ Context near saturation. Consider:
385
+ <ul>
386
+ <li>Resetting the conversation</li>
387
+ <li>Switching to a larger-context model</li>
388
+ <li>Reducing repository scope</li>
389
+ </ul>
390
+ </div>
391
+ )}
392
+
393
+ <div className="ctx-footer">
394
+ <span>{estimate ? "Token counts are estimated" : "Token counts via tiktoken"}</span>
395
+ <button
396
+ type="button"
397
+ className="ctx-refresh"
398
+ onClick={fetchUsage}
399
+ disabled={loading}
400
+ aria-label="Refresh context usage"
401
+ >
402
+ {loading ? "…" : "↻ refresh"}
403
+ </button>
404
+ </div>
405
+ </>
406
+ )}
407
+ </div>
408
+ )}
409
+ </span>
410
+ );
411
+ }
frontend/components/CreatePRButton.jsx ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from "react";
2
+ import { apiUrl } from "../utils/api.js";
3
+
4
+ /**
5
+ * CreatePRButton — Claude-Code-on-Web parity PR creation action.
6
+ *
7
+ * When clicked, pushes session changes to a new branch and opens a PR.
8
+ * Shows loading state and links to the created PR on GitHub.
9
+ */
10
+ export default function CreatePRButton({
11
+ repo,
12
+ sessionId,
13
+ branch,
14
+ defaultBranch,
15
+ disabled,
16
+ onPRCreated,
17
+ }) {
18
+ const [creating, setCreating] = useState(false);
19
+ const [prUrl, setPrUrl] = useState(null);
20
+ const [error, setError] = useState(null);
21
+
22
+ const handleCreate = async () => {
23
+ if (!repo || !branch || branch === defaultBranch) return;
24
+
25
+ setCreating(true);
26
+ setError(null);
27
+
28
+ try {
29
+ const token = localStorage.getItem("github_token");
30
+ const headers = {
31
+ "Content-Type": "application/json",
32
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
33
+ };
34
+
35
+ const owner = repo.full_name?.split("/")[0] || repo.owner;
36
+ const name = repo.full_name?.split("/")[1] || repo.name;
37
+
38
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${name}/pulls`), {
39
+ method: "POST",
40
+ headers,
41
+ body: JSON.stringify({
42
+ title: `[GitPilot] Changes from session ${sessionId ? sessionId.slice(0, 8) : branch}`,
43
+ head: branch,
44
+ base: defaultBranch || "main",
45
+ body: [
46
+ "## Summary",
47
+ "",
48
+ `Changes created by GitPilot AI assistant on branch \`${branch}\`.`,
49
+ "",
50
+ sessionId ? `Session ID: \`${sessionId}\`` : "",
51
+ "",
52
+ "---",
53
+ "*This PR was generated by [GitPilot](https://github.com/ruslanmv/gitpilot).*",
54
+ ]
55
+ .filter(Boolean)
56
+ .join("\n"),
57
+ }),
58
+ });
59
+
60
+ const data = await res.json();
61
+ if (!res.ok) throw new Error(data.detail || "Failed to create PR");
62
+
63
+ const url = data.html_url || data.url;
64
+ setPrUrl(url);
65
+ onPRCreated?.({ pr_url: url, pr_number: data.number, branch });
66
+ } catch (err) {
67
+ setError(err.message);
68
+ } finally {
69
+ setCreating(false);
70
+ }
71
+ };
72
+
73
+ if (prUrl) {
74
+ return (
75
+ <a
76
+ href={prUrl}
77
+ target="_blank"
78
+ rel="noreferrer"
79
+ style={styles.prLink}
80
+ >
81
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
82
+ <circle cx="18" cy="18" r="3" />
83
+ <circle cx="6" cy="6" r="3" />
84
+ <path d="M13 6h3a2 2 0 0 1 2 2v7" />
85
+ <line x1="6" y1="9" x2="6" y2="21" />
86
+ </svg>
87
+ View PR on GitHub &rarr;
88
+ </a>
89
+ );
90
+ }
91
+
92
+ return (
93
+ <div>
94
+ <button
95
+ type="button"
96
+ style={{
97
+ ...styles.btn,
98
+ opacity: disabled || creating ? 0.55 : 1,
99
+ cursor: disabled || creating ? "not-allowed" : "pointer",
100
+ }}
101
+ onClick={handleCreate}
102
+ disabled={disabled || creating || !branch || branch === defaultBranch}
103
+ title={
104
+ !branch || branch === defaultBranch
105
+ ? "Create a session branch first"
106
+ : "Create a pull request from session changes"
107
+ }
108
+ >
109
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
110
+ <circle cx="18" cy="18" r="3" />
111
+ <circle cx="6" cy="6" r="3" />
112
+ <path d="M13 6h3a2 2 0 0 1 2 2v7" />
113
+ <line x1="6" y1="9" x2="6" y2="21" />
114
+ </svg>
115
+ {creating ? "Creating PR..." : "Create PR"}
116
+ </button>
117
+ {error && (
118
+ <div style={styles.error}>{error}</div>
119
+ )}
120
+ </div>
121
+ );
122
+ }
123
+
124
+ const styles = {
125
+ btn: {
126
+ display: "flex",
127
+ alignItems: "center",
128
+ gap: 6,
129
+ height: 38,
130
+ padding: "0 14px",
131
+ borderRadius: 8,
132
+ border: "1px solid rgba(16, 185, 129, 0.3)",
133
+ background: "rgba(16, 185, 129, 0.08)",
134
+ color: "#10B981",
135
+ fontSize: 13,
136
+ fontWeight: 600,
137
+ cursor: "pointer",
138
+ whiteSpace: "nowrap",
139
+ transition: "background-color 0.15s",
140
+ },
141
+ prLink: {
142
+ display: "flex",
143
+ alignItems: "center",
144
+ gap: 6,
145
+ height: 38,
146
+ padding: "0 14px",
147
+ borderRadius: 8,
148
+ background: "rgba(16, 185, 129, 0.10)",
149
+ color: "#10B981",
150
+ fontSize: 13,
151
+ fontWeight: 600,
152
+ textDecoration: "none",
153
+ whiteSpace: "nowrap",
154
+ },
155
+ error: {
156
+ fontSize: 11,
157
+ color: "#EF4444",
158
+ marginTop: 4,
159
+ },
160
+ };
frontend/components/DiffStats.jsx ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from "react";
2
+
3
+ /**
4
+ * DiffStats — Claude-Code-on-Web parity inline diff indicator.
5
+ *
6
+ * Clickable "+N -N in M files" badge that appears in agent messages.
7
+ * Clicking opens the DiffViewer overlay.
8
+ */
9
+ export default function DiffStats({ diff, onClick }) {
10
+ if (!diff || (!diff.additions && !diff.deletions && !diff.files_changed)) {
11
+ return null;
12
+ }
13
+
14
+ return (
15
+ <button type="button" style={styles.container} onClick={onClick}>
16
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
17
+ <path d="M12 3v18M3 12h18" opacity="0.3" />
18
+ <rect x="3" y="3" width="18" height="18" rx="2" />
19
+ </svg>
20
+ <span style={styles.additions}>+{diff.additions || 0}</span>
21
+ <span style={styles.deletions}>-{diff.deletions || 0}</span>
22
+ <span style={styles.files}>
23
+ in {diff.files_changed || (diff.files || []).length} file{(diff.files_changed || (diff.files || []).length) !== 1 ? "s" : ""}
24
+ </span>
25
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ opacity: 0.5 }}>
26
+ <polyline points="9 18 15 12 9 6" />
27
+ </svg>
28
+ </button>
29
+ );
30
+ }
31
+
32
+ const styles = {
33
+ container: {
34
+ display: "inline-flex",
35
+ alignItems: "center",
36
+ gap: 6,
37
+ padding: "5px 10px",
38
+ borderRadius: 6,
39
+ border: "1px solid #27272A",
40
+ backgroundColor: "rgba(24, 24, 27, 0.8)",
41
+ cursor: "pointer",
42
+ fontSize: 12,
43
+ fontFamily: "monospace",
44
+ color: "#A1A1AA",
45
+ transition: "border-color 0.15s, background-color 0.15s",
46
+ marginTop: 8,
47
+ },
48
+ additions: {
49
+ color: "#10B981",
50
+ fontWeight: 600,
51
+ },
52
+ deletions: {
53
+ color: "#EF4444",
54
+ fontWeight: 600,
55
+ },
56
+ files: {
57
+ color: "#71717A",
58
+ },
59
+ };
frontend/components/DiffViewer.jsx ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from "react";
2
+
3
+ /**
4
+ * DiffViewer — Claude-Code-on-Web parity diff overlay.
5
+ *
6
+ * Shows a file list on the left and unified diff on the right.
7
+ * Green = additions, red = deletions. Additive component.
8
+ */
9
+ export default function DiffViewer({ diff, onClose }) {
10
+ const [selectedFile, setSelectedFile] = useState(0);
11
+
12
+ if (!diff || !diff.files || diff.files.length === 0) {
13
+ return (
14
+ <div style={styles.overlay}>
15
+ <div style={styles.panel}>
16
+ <div style={styles.header}>
17
+ <span style={styles.headerTitle}>Diff Viewer</span>
18
+ <button type="button" style={styles.closeBtn} onClick={onClose}>
19
+ &times;
20
+ </button>
21
+ </div>
22
+ <div style={styles.emptyState}>No changes to display.</div>
23
+ </div>
24
+ </div>
25
+ );
26
+ }
27
+
28
+ const files = diff.files || [];
29
+ const currentFile = files[selectedFile] || files[0];
30
+
31
+ return (
32
+ <div style={styles.overlay}>
33
+ <div style={styles.panel}>
34
+ {/* Header */}
35
+ <div style={styles.header}>
36
+ <div style={styles.headerLeft}>
37
+ <span style={styles.headerTitle}>Diff Viewer</span>
38
+ <span style={styles.statBadge}>
39
+ <span style={{ color: "#10B981" }}>+{diff.additions || 0}</span>
40
+ {" "}
41
+ <span style={{ color: "#EF4444" }}>-{diff.deletions || 0}</span>
42
+ {" in "}
43
+ {diff.files_changed || files.length} files
44
+ </span>
45
+ </div>
46
+ <button type="button" style={styles.closeBtn} onClick={onClose}>
47
+ &times;
48
+ </button>
49
+ </div>
50
+
51
+ {/* Body */}
52
+ <div style={styles.body}>
53
+ {/* File list */}
54
+ <div style={styles.fileList}>
55
+ {files.map((f, idx) => (
56
+ <div
57
+ key={f.path}
58
+ style={{
59
+ ...styles.fileItem,
60
+ backgroundColor:
61
+ idx === selectedFile ? "rgba(59, 130, 246, 0.10)" : "transparent",
62
+ borderLeft:
63
+ idx === selectedFile
64
+ ? "2px solid #3B82F6"
65
+ : "2px solid transparent",
66
+ }}
67
+ onClick={() => setSelectedFile(idx)}
68
+ >
69
+ <span style={styles.fileName}>{f.path}</span>
70
+ <span style={styles.fileStats}>
71
+ <span style={{ color: "#10B981" }}>+{f.additions || 0}</span>
72
+ {" "}
73
+ <span style={{ color: "#EF4444" }}>-{f.deletions || 0}</span>
74
+ </span>
75
+ </div>
76
+ ))}
77
+ </div>
78
+
79
+ {/* Diff content */}
80
+ <div style={styles.diffContent}>
81
+ <div style={styles.diffPath}>{currentFile.path}</div>
82
+ <div style={styles.diffCode}>
83
+ {(currentFile.hunks || []).map((hunk, hi) => (
84
+ <div key={hi}>
85
+ <div style={styles.hunkHeader}>{hunk.header || `@@ hunk ${hi + 1} @@`}</div>
86
+ {(hunk.lines || []).map((line, li) => {
87
+ let bg = "transparent";
88
+ let color = "#D4D4D8";
89
+ if (line.startsWith("+")) {
90
+ bg = "rgba(16, 185, 129, 0.10)";
91
+ color = "#6EE7B7";
92
+ } else if (line.startsWith("-")) {
93
+ bg = "rgba(239, 68, 68, 0.10)";
94
+ color = "#FCA5A5";
95
+ }
96
+ return (
97
+ <div
98
+ key={li}
99
+ style={{
100
+ ...styles.diffLine,
101
+ backgroundColor: bg,
102
+ color,
103
+ }}
104
+ >
105
+ {line}
106
+ </div>
107
+ );
108
+ })}
109
+ </div>
110
+ ))}
111
+
112
+ {(!currentFile.hunks || currentFile.hunks.length === 0) && (
113
+ <div style={styles.diffPlaceholder}>
114
+ Diff content will appear here when the agent modifies files.
115
+ </div>
116
+ )}
117
+ </div>
118
+ </div>
119
+ </div>
120
+ </div>
121
+ </div>
122
+ );
123
+ }
124
+
125
+ const styles = {
126
+ overlay: {
127
+ position: "fixed",
128
+ top: 0,
129
+ left: 0,
130
+ right: 0,
131
+ bottom: 0,
132
+ backgroundColor: "rgba(0, 0, 0, 0.7)",
133
+ zIndex: 200,
134
+ display: "flex",
135
+ alignItems: "center",
136
+ justifyContent: "center",
137
+ },
138
+ panel: {
139
+ width: "90vw",
140
+ maxWidth: 1100,
141
+ height: "80vh",
142
+ backgroundColor: "#131316",
143
+ border: "1px solid #27272A",
144
+ borderRadius: 12,
145
+ display: "flex",
146
+ flexDirection: "column",
147
+ overflow: "hidden",
148
+ },
149
+ header: {
150
+ display: "flex",
151
+ justifyContent: "space-between",
152
+ alignItems: "center",
153
+ padding: "12px 16px",
154
+ borderBottom: "1px solid #27272A",
155
+ backgroundColor: "#18181B",
156
+ },
157
+ headerLeft: {
158
+ display: "flex",
159
+ alignItems: "center",
160
+ gap: 12,
161
+ },
162
+ headerTitle: {
163
+ fontSize: 14,
164
+ fontWeight: 600,
165
+ color: "#E4E4E7",
166
+ },
167
+ statBadge: {
168
+ fontSize: 12,
169
+ color: "#A1A1AA",
170
+ },
171
+ closeBtn: {
172
+ width: 28,
173
+ height: 28,
174
+ borderRadius: 6,
175
+ border: "1px solid #3F3F46",
176
+ background: "transparent",
177
+ color: "#A1A1AA",
178
+ fontSize: 18,
179
+ cursor: "pointer",
180
+ display: "flex",
181
+ alignItems: "center",
182
+ justifyContent: "center",
183
+ },
184
+ body: {
185
+ flex: 1,
186
+ display: "flex",
187
+ overflow: "hidden",
188
+ },
189
+ fileList: {
190
+ width: 240,
191
+ borderRight: "1px solid #27272A",
192
+ overflowY: "auto",
193
+ flexShrink: 0,
194
+ },
195
+ fileItem: {
196
+ padding: "8px 10px",
197
+ cursor: "pointer",
198
+ borderBottom: "1px solid rgba(39, 39, 42, 0.5)",
199
+ transition: "background-color 0.1s",
200
+ },
201
+ fileName: {
202
+ display: "block",
203
+ fontSize: 12,
204
+ fontFamily: "monospace",
205
+ color: "#E4E4E7",
206
+ whiteSpace: "nowrap",
207
+ overflow: "hidden",
208
+ textOverflow: "ellipsis",
209
+ },
210
+ fileStats: {
211
+ display: "block",
212
+ fontSize: 10,
213
+ marginTop: 2,
214
+ },
215
+ diffContent: {
216
+ flex: 1,
217
+ overflow: "auto",
218
+ display: "flex",
219
+ flexDirection: "column",
220
+ },
221
+ diffPath: {
222
+ padding: "8px 12px",
223
+ fontSize: 12,
224
+ fontFamily: "monospace",
225
+ color: "#A1A1AA",
226
+ borderBottom: "1px solid #27272A",
227
+ backgroundColor: "#18181B",
228
+ position: "sticky",
229
+ top: 0,
230
+ zIndex: 1,
231
+ },
232
+ diffCode: {
233
+ padding: "4px 0",
234
+ fontFamily: "monospace",
235
+ fontSize: 12,
236
+ lineHeight: 1.6,
237
+ },
238
+ hunkHeader: {
239
+ padding: "4px 12px",
240
+ color: "#6B7280",
241
+ backgroundColor: "rgba(59, 130, 246, 0.05)",
242
+ fontSize: 11,
243
+ fontStyle: "italic",
244
+ },
245
+ diffLine: {
246
+ padding: "0 12px",
247
+ whiteSpace: "pre",
248
+ },
249
+ diffPlaceholder: {
250
+ padding: 20,
251
+ textAlign: "center",
252
+ color: "#52525B",
253
+ fontSize: 13,
254
+ },
255
+ emptyState: {
256
+ flex: 1,
257
+ display: "flex",
258
+ alignItems: "center",
259
+ justifyContent: "center",
260
+ color: "#52525B",
261
+ fontSize: 14,
262
+ },
263
+ };
frontend/components/EnvironmentEditor.jsx ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from "react";
2
+ import { createPortal } from "react-dom";
3
+
4
+ /**
5
+ * EnvironmentEditor — Claude-Code-on-Web parity environment config modal.
6
+ *
7
+ * Allows setting name, network access level, and environment variables.
8
+ */
9
+ export default function EnvironmentEditor({ environment, onSave, onDelete, onClose }) {
10
+ const [name, setName] = useState(environment?.name || "");
11
+ const [networkAccess, setNetworkAccess] = useState(environment?.network_access || "limited");
12
+ const [envVarsText, setEnvVarsText] = useState(
13
+ environment?.env_vars
14
+ ? Object.entries(environment.env_vars)
15
+ .map(([k, v]) => `${k}=${v}`)
16
+ .join("\n")
17
+ : ""
18
+ );
19
+
20
+ const handleSave = () => {
21
+ const envVars = {};
22
+ envVarsText
23
+ .split("\n")
24
+ .map((line) => line.trim())
25
+ .filter((line) => line && line.includes("="))
26
+ .forEach((line) => {
27
+ const idx = line.indexOf("=");
28
+ const key = line.slice(0, idx).trim();
29
+ const val = line.slice(idx + 1).trim();
30
+ if (key) envVars[key] = val;
31
+ });
32
+
33
+ onSave({
34
+ id: environment?.id || null,
35
+ name: name.trim() || "Default",
36
+ network_access: networkAccess,
37
+ env_vars: envVars,
38
+ });
39
+ };
40
+
41
+ return createPortal(
42
+ <div style={styles.overlay} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
43
+ <div style={styles.modal} onMouseDown={(e) => e.stopPropagation()}>
44
+ <div style={styles.header}>
45
+ <span style={styles.headerTitle}>
46
+ {environment?.id ? "Edit Environment" : "New Environment"}
47
+ </span>
48
+ <button type="button" style={styles.closeBtn} onClick={onClose}>
49
+ &times;
50
+ </button>
51
+ </div>
52
+
53
+ <div style={styles.body}>
54
+ {/* Name */}
55
+ <label style={styles.label}>Environment Name</label>
56
+ <input
57
+ type="text"
58
+ value={name}
59
+ onChange={(e) => setName(e.target.value)}
60
+ placeholder="e.g. Development, Staging, Production"
61
+ style={styles.input}
62
+ />
63
+
64
+ {/* Network Access */}
65
+ <label style={styles.label}>Network Access</label>
66
+ <div style={styles.radioGroup}>
67
+ {[
68
+ { value: "limited", label: "Limited", desc: "Allowlisted domains only (package managers, APIs)" },
69
+ { value: "full", label: "Full", desc: "Unrestricted internet access" },
70
+ { value: "none", label: "None", desc: "Air-gapped — no external network" },
71
+ ].map((opt) => (
72
+ <label
73
+ key={opt.value}
74
+ style={{
75
+ ...styles.radioItem,
76
+ borderColor:
77
+ networkAccess === opt.value ? "#3B82F6" : "#27272A",
78
+ backgroundColor:
79
+ networkAccess === opt.value
80
+ ? "rgba(59, 130, 246, 0.05)"
81
+ : "transparent",
82
+ }}
83
+ >
84
+ <input
85
+ type="radio"
86
+ name="network"
87
+ value={opt.value}
88
+ checked={networkAccess === opt.value}
89
+ onChange={(e) => setNetworkAccess(e.target.value)}
90
+ style={{ display: "none" }}
91
+ />
92
+ <div>
93
+ <div style={{
94
+ fontSize: 13,
95
+ fontWeight: 500,
96
+ color: networkAccess === opt.value ? "#E4E4E7" : "#A1A1AA",
97
+ }}>
98
+ {opt.label}
99
+ </div>
100
+ <div style={{ fontSize: 11, color: "#71717A", marginTop: 2 }}>
101
+ {opt.desc}
102
+ </div>
103
+ </div>
104
+ </label>
105
+ ))}
106
+ </div>
107
+
108
+ {/* Environment Variables */}
109
+ <label style={styles.label}>Environment Variables</label>
110
+ <textarea
111
+ value={envVarsText}
112
+ onChange={(e) => setEnvVarsText(e.target.value)}
113
+ placeholder={"NODE_ENV=development\nDEBUG=true\nAPI_KEY=your-key-here"}
114
+ rows={6}
115
+ style={styles.textarea}
116
+ />
117
+ <div style={{ fontSize: 10, color: "#52525B", marginTop: 4 }}>
118
+ One KEY=VALUE per line. Secrets are stored locally.
119
+ </div>
120
+ </div>
121
+
122
+ <div style={styles.footer}>
123
+ {onDelete && (
124
+ <button type="button" style={styles.deleteBtn} onClick={onDelete}>
125
+ Delete
126
+ </button>
127
+ )}
128
+ <div style={{ flex: 1 }} />
129
+ <button type="button" style={styles.cancelBtn} onClick={onClose}>
130
+ Cancel
131
+ </button>
132
+ <button type="button" style={styles.saveBtn} onClick={handleSave}>
133
+ Save
134
+ </button>
135
+ </div>
136
+ </div>
137
+ </div>,
138
+ document.body
139
+ );
140
+ }
141
+
142
+ const styles = {
143
+ overlay: {
144
+ position: "fixed",
145
+ top: 0,
146
+ left: 0,
147
+ right: 0,
148
+ bottom: 0,
149
+ backgroundColor: "rgba(0, 0, 0, 0.6)",
150
+ zIndex: 10000,
151
+ display: "flex",
152
+ alignItems: "center",
153
+ justifyContent: "center",
154
+ },
155
+ modal: {
156
+ width: 480,
157
+ maxHeight: "80vh",
158
+ backgroundColor: "#131316",
159
+ border: "1px solid #27272A",
160
+ borderRadius: 12,
161
+ display: "flex",
162
+ flexDirection: "column",
163
+ overflow: "hidden",
164
+ },
165
+ header: {
166
+ display: "flex",
167
+ justifyContent: "space-between",
168
+ alignItems: "center",
169
+ padding: "14px 16px",
170
+ borderBottom: "1px solid #27272A",
171
+ backgroundColor: "#18181B",
172
+ },
173
+ headerTitle: {
174
+ fontSize: 14,
175
+ fontWeight: 600,
176
+ color: "#E4E4E7",
177
+ },
178
+ closeBtn: {
179
+ width: 26,
180
+ height: 26,
181
+ borderRadius: 6,
182
+ border: "1px solid #3F3F46",
183
+ background: "transparent",
184
+ color: "#A1A1AA",
185
+ fontSize: 16,
186
+ cursor: "pointer",
187
+ display: "flex",
188
+ alignItems: "center",
189
+ justifyContent: "center",
190
+ },
191
+ body: {
192
+ padding: "16px",
193
+ overflowY: "auto",
194
+ flex: 1,
195
+ },
196
+ label: {
197
+ display: "block",
198
+ fontSize: 12,
199
+ fontWeight: 600,
200
+ color: "#A1A1AA",
201
+ marginBottom: 6,
202
+ marginTop: 14,
203
+ },
204
+ input: {
205
+ width: "100%",
206
+ padding: "8px 10px",
207
+ borderRadius: 6,
208
+ border: "1px solid #3F3F46",
209
+ background: "#18181B",
210
+ color: "#E4E4E7",
211
+ fontSize: 13,
212
+ outline: "none",
213
+ boxSizing: "border-box",
214
+ },
215
+ radioGroup: {
216
+ display: "flex",
217
+ flexDirection: "column",
218
+ gap: 6,
219
+ },
220
+ radioItem: {
221
+ display: "flex",
222
+ alignItems: "flex-start",
223
+ gap: 10,
224
+ padding: "8px 10px",
225
+ borderRadius: 6,
226
+ border: "1px solid #27272A",
227
+ cursor: "pointer",
228
+ transition: "border-color 0.15s, background-color 0.15s",
229
+ },
230
+ textarea: {
231
+ width: "100%",
232
+ padding: "8px 10px",
233
+ borderRadius: 6,
234
+ border: "1px solid #3F3F46",
235
+ background: "#18181B",
236
+ color: "#E4E4E7",
237
+ fontSize: 12,
238
+ fontFamily: "monospace",
239
+ outline: "none",
240
+ resize: "vertical",
241
+ boxSizing: "border-box",
242
+ },
243
+ footer: {
244
+ display: "flex",
245
+ alignItems: "center",
246
+ gap: 8,
247
+ padding: "12px 16px",
248
+ borderTop: "1px solid #27272A",
249
+ },
250
+ cancelBtn: {
251
+ padding: "6px 14px",
252
+ borderRadius: 6,
253
+ border: "1px solid #3F3F46",
254
+ background: "transparent",
255
+ color: "#A1A1AA",
256
+ fontSize: 12,
257
+ cursor: "pointer",
258
+ },
259
+ saveBtn: {
260
+ padding: "6px 14px",
261
+ borderRadius: 6,
262
+ border: "none",
263
+ background: "#3B82F6",
264
+ color: "#fff",
265
+ fontSize: 12,
266
+ fontWeight: 600,
267
+ cursor: "pointer",
268
+ },
269
+ deleteBtn: {
270
+ padding: "6px 14px",
271
+ borderRadius: 6,
272
+ border: "1px solid rgba(239, 68, 68, 0.3)",
273
+ background: "transparent",
274
+ color: "#EF4444",
275
+ fontSize: 12,
276
+ cursor: "pointer",
277
+ },
278
+ };
frontend/components/EnvironmentSelector.jsx ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useState } from "react";
2
+ import { apiUrl } from "../utils/api.js";
3
+ import EnvironmentEditor from "./EnvironmentEditor.jsx";
4
+
5
+ /**
6
+ * EnvironmentSelector — Claude-Code-on-Web parity environment dropdown.
7
+ *
8
+ * Shows current environment name + gear icon. Gear opens the editor modal.
9
+ * Fetches environments from /api/environments.
10
+ */
11
+ export default function EnvironmentSelector({ activeEnvId, onEnvChange }) {
12
+ const [envs, setEnvs] = useState([]);
13
+ const [editorOpen, setEditorOpen] = useState(false);
14
+ const [editingEnv, setEditingEnv] = useState(null);
15
+
16
+ const fetchEnvs = async () => {
17
+ try {
18
+ const res = await fetch(apiUrl("/api/environments"), { cache: "no-cache" });
19
+ if (!res.ok) return;
20
+ const data = await res.json();
21
+ setEnvs(data.environments || []);
22
+ } catch (err) {
23
+ console.warn("Failed to fetch environments:", err);
24
+ }
25
+ };
26
+
27
+ useEffect(() => {
28
+ fetchEnvs();
29
+ }, []);
30
+
31
+ const activeEnv =
32
+ envs.find((e) => e.id === activeEnvId) || envs[0] || { name: "Default", id: "default" };
33
+
34
+ const handleSave = async (config) => {
35
+ try {
36
+ const method = config.id ? "PUT" : "POST";
37
+ const url = config.id ? `/api/environments/${config.id}` : "/api/environments";
38
+ await fetch(apiUrl(url), {
39
+ method,
40
+ headers: { "Content-Type": "application/json" },
41
+ body: JSON.stringify(config),
42
+ });
43
+ await fetchEnvs();
44
+ setEditorOpen(false);
45
+ setEditingEnv(null);
46
+ } catch (err) {
47
+ console.warn("Failed to save environment:", err);
48
+ }
49
+ };
50
+
51
+ const handleDelete = async (envId) => {
52
+ try {
53
+ await fetch(apiUrl(`/api/environments/${envId}`), { method: "DELETE" });
54
+ await fetchEnvs();
55
+ if (activeEnvId === envId) {
56
+ onEnvChange?.(null);
57
+ }
58
+ } catch (err) {
59
+ console.warn("Failed to delete environment:", err);
60
+ }
61
+ };
62
+
63
+ return (
64
+ <div style={styles.container}>
65
+ <div style={styles.label}>ENVIRONMENT</div>
66
+ <div style={styles.row}>
67
+ <div style={styles.envCard}>
68
+ {/* Env selector */}
69
+ <select
70
+ value={activeEnv.id || "default"}
71
+ onChange={(e) => onEnvChange?.(e.target.value)}
72
+ style={styles.select}
73
+ >
74
+ {envs.map((env) => (
75
+ <option key={env.id} value={env.id}>
76
+ {env.name}
77
+ </option>
78
+ ))}
79
+ </select>
80
+
81
+ {/* Network badge */}
82
+ <span style={{
83
+ ...styles.networkBadge,
84
+ color: activeEnv.network_access === "full"
85
+ ? "#10B981"
86
+ : activeEnv.network_access === "none"
87
+ ? "#EF4444"
88
+ : "#F59E0B",
89
+ }}>
90
+ {activeEnv.network_access || "limited"}
91
+ </span>
92
+ </div>
93
+
94
+ {/* Gear icon */}
95
+ <button
96
+ type="button"
97
+ style={styles.gearBtn}
98
+ onClick={() => {
99
+ setEditingEnv(activeEnv);
100
+ setEditorOpen(true);
101
+ }}
102
+ title="Configure environment"
103
+ >
104
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
105
+ <circle cx="12" cy="12" r="3" />
106
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
107
+ </svg>
108
+ </button>
109
+
110
+ {/* Add new */}
111
+ <button
112
+ type="button"
113
+ style={styles.gearBtn}
114
+ onClick={() => {
115
+ setEditingEnv(null);
116
+ setEditorOpen(true);
117
+ }}
118
+ title="Add environment"
119
+ >
120
+ +
121
+ </button>
122
+ </div>
123
+
124
+ {/* Editor modal */}
125
+ {editorOpen && (
126
+ <EnvironmentEditor
127
+ environment={editingEnv}
128
+ onSave={handleSave}
129
+ onDelete={editingEnv?.id ? () => handleDelete(editingEnv.id) : null}
130
+ onClose={() => {
131
+ setEditorOpen(false);
132
+ setEditingEnv(null);
133
+ }}
134
+ />
135
+ )}
136
+ </div>
137
+ );
138
+ }
139
+
140
+ const styles = {
141
+ container: {
142
+ padding: "10px 14px",
143
+ },
144
+ label: {
145
+ fontSize: 10,
146
+ fontWeight: 700,
147
+ letterSpacing: "0.08em",
148
+ color: "#71717A",
149
+ textTransform: "uppercase",
150
+ marginBottom: 6,
151
+ },
152
+ row: {
153
+ display: "flex",
154
+ alignItems: "center",
155
+ gap: 6,
156
+ },
157
+ envCard: {
158
+ flex: 1,
159
+ display: "flex",
160
+ alignItems: "center",
161
+ gap: 8,
162
+ padding: "4px 8px",
163
+ borderRadius: 6,
164
+ border: "1px solid #27272A",
165
+ backgroundColor: "#18181B",
166
+ minWidth: 0,
167
+ },
168
+ select: {
169
+ flex: 1,
170
+ background: "transparent",
171
+ border: "none",
172
+ color: "#E4E4E7",
173
+ fontSize: 12,
174
+ fontWeight: 500,
175
+ outline: "none",
176
+ cursor: "pointer",
177
+ minWidth: 0,
178
+ },
179
+ networkBadge: {
180
+ fontSize: 9,
181
+ fontWeight: 600,
182
+ textTransform: "uppercase",
183
+ letterSpacing: "0.04em",
184
+ flexShrink: 0,
185
+ },
186
+ gearBtn: {
187
+ width: 28,
188
+ height: 28,
189
+ borderRadius: 6,
190
+ border: "1px solid #27272A",
191
+ background: "transparent",
192
+ color: "#71717A",
193
+ cursor: "pointer",
194
+ display: "flex",
195
+ alignItems: "center",
196
+ justifyContent: "center",
197
+ fontSize: 14,
198
+ flexShrink: 0,
199
+ },
200
+ };
frontend/components/ExecutionPlanCard.jsx ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/ExecutionPlanCard.jsx
2
+ //
3
+ // The approval-first surface for sandbox runs. Renders a
4
+ // deterministic ExecutionPlan returned by POST /api/sandbox/plan
5
+ // and gates the actual run on an explicit user click.
6
+ //
7
+ // Two visual variants, same component:
8
+ //
9
+ // variant = "full" — used in chat for file-run and chat-command
10
+ // plans. Big card, every safety check / warning
11
+ // visible, primary CTA "Run in Sandbox".
12
+ // variant = "compact" — used as a popover above a code-block ▶ click.
13
+ // Same info, less chrome.
14
+ //
15
+ // The component is stateless about the run itself: it produces an
16
+ // approval event (onApprove with the plan object) and lets the
17
+ // parent decide how to execute. This keeps the streaming/state
18
+ // machine work for Batch 3 — here we only render and consent.
19
+
20
+ import React from "react";
21
+ import { apiUrl } from "../utils/api.js";
22
+
23
+ const SEVERITY_STYLE = {
24
+ high: { bg: "#3d1111", fg: "#fca5a5", border: "#7f1d1d", icon: "⛔" },
25
+ medium: { bg: "#3d2d11", fg: "#fde68a", border: "#854d0e", icon: "⚠" },
26
+ low: { bg: "#1f2937", fg: "#a5b4fc", border: "#3730a3", icon: "ⓘ" },
27
+ };
28
+
29
+ const BACKEND_LABELS = {
30
+ subprocess: "Local",
31
+ matrixlab: "MatrixLab",
32
+ off: "Pass-through",
33
+ };
34
+
35
+ export default function ExecutionPlanCard({
36
+ plan,
37
+ variant = "full",
38
+ busy = false,
39
+ onApprove,
40
+ onCancel,
41
+ onOpenFile,
42
+ }) {
43
+ if (!plan) return null;
44
+ const isCompact = variant === "compact";
45
+ const styles = isCompact ? compactStyles : fullStyles;
46
+
47
+ const commandStr = Array.isArray(plan.command)
48
+ ? plan.command.join(" ")
49
+ : String(plan.command || "");
50
+
51
+ return (
52
+ <div style={styles.card} role="region" aria-label="Execution plan">
53
+ <header style={styles.header}>
54
+ <span style={styles.badge}>EXECUTION PLAN</span>
55
+ <h3 style={styles.title}>{plan.goal || "Run in sandbox"}</h3>
56
+ </header>
57
+
58
+ <dl style={styles.fields}>
59
+ {plan.file && (
60
+ <Field label="File" value={<code>{plan.file}</code>} />
61
+ )}
62
+ <Field label="Command" value={<code>{commandStr}</code>} />
63
+ <Field
64
+ label="Sandbox"
65
+ value={BACKEND_LABELS[plan.sandbox] || plan.sandbox}
66
+ />
67
+ <Field label="Timeout" value={`${plan.timeout_sec}s`} />
68
+ <Field
69
+ label="Network"
70
+ value={plan.network ? "Enabled" : "Disabled"}
71
+ />
72
+ {plan.workdir && plan.workdir !== "." && (
73
+ <Field label="Working dir" value={<code>{plan.workdir}</code>} />
74
+ )}
75
+ </dl>
76
+
77
+ {/* Safety checks — always green, no opinion */}
78
+ {Array.isArray(plan.safety?.checks) && plan.safety.checks.length > 0 && (
79
+ <ul style={styles.checks}>
80
+ {plan.safety.checks.map((c, i) => (
81
+ <li key={i} style={styles.check}>
82
+ <span style={styles.checkIcon}>✓</span>
83
+ {c.label}
84
+ </li>
85
+ ))}
86
+ </ul>
87
+ )}
88
+
89
+ {/* Warnings — non-blocking, sorted high → low by the backend */}
90
+ {Array.isArray(plan.safety?.warnings) && plan.safety.warnings.length > 0 && (
91
+ <ul style={styles.warnings}>
92
+ {plan.safety.warnings.map((w, i) => {
93
+ const st = SEVERITY_STYLE[w.severity] || SEVERITY_STYLE.low;
94
+ return (
95
+ <li key={i} style={{
96
+ ...styles.warning,
97
+ background: st.bg, color: st.fg, borderColor: st.border,
98
+ }}>
99
+ <span style={styles.warnIcon}>{st.icon}</span>
100
+ <span>
101
+ <strong>{w.label}</strong>
102
+ {w.detail && <span style={styles.warnDetail}> — {w.detail}</span>}
103
+ </span>
104
+ </li>
105
+ );
106
+ })}
107
+ </ul>
108
+ )}
109
+
110
+ {plan.inline_code && (
111
+ <details style={styles.snippetWrap}>
112
+ <summary style={styles.snippetLabel}>
113
+ Snippet to run ({plan.inline_code.length} chars)
114
+ </summary>
115
+ <pre style={styles.snippet}>{plan.inline_code}</pre>
116
+ </details>
117
+ )}
118
+
119
+ <footer style={styles.footer}>
120
+ <button
121
+ type="button"
122
+ style={{ ...styles.primary, opacity: busy ? 0.6 : 1 }}
123
+ onClick={() => onApprove?.(plan)}
124
+ disabled={busy}
125
+ autoFocus
126
+ >
127
+ {busy ? "Starting…" : "▶ Run in Sandbox"}
128
+ </button>
129
+ {plan.file && onOpenFile && (
130
+ <button type="button" style={styles.secondary}
131
+ onClick={() => onOpenFile(plan.file)}>
132
+ Open {plan.file.split("/").pop()}
133
+ </button>
134
+ )}
135
+ <button
136
+ type="button"
137
+ style={styles.tertiary}
138
+ onClick={() => onCancel?.(plan)}
139
+ disabled={busy}
140
+ >
141
+ Cancel
142
+ </button>
143
+ </footer>
144
+ </div>
145
+ );
146
+ }
147
+
148
+ function Field({ label, value }) {
149
+ return (
150
+ <>
151
+ <dt style={dtStyle}>{label}</dt>
152
+ <dd style={ddStyle}>{value}</dd>
153
+ </>
154
+ );
155
+ }
156
+
157
+ // ---------------------------------------------------------------------------
158
+ // Approve helper — single source of truth so chat, codeblock, canvas
159
+ // all build the plan the same way. Returns the plan object or throws.
160
+ // ---------------------------------------------------------------------------
161
+
162
+ export async function fetchExecutionPlan(payload) {
163
+ const res = await fetch(apiUrl("/api/sandbox/plan"), {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify(payload),
167
+ });
168
+ const data = await res.json().catch(() => ({}));
169
+ if (!res.ok) {
170
+ throw new Error(data.detail || `Plan failed (HTTP ${res.status})`);
171
+ }
172
+ return data.plan;
173
+ }
174
+
175
+ /** Approve a plan and return the body to POST to /api/sandbox/run.
176
+ *
177
+ * The card's UX is unchanged; what changed is that the server now requires
178
+ * proof of approval. Until Batch V4-D6 the approval was entirely client-side:
179
+ * /api/sandbox/run executed whatever it was handed, so anything that could
180
+ * reach it ran arbitrary code. One helper for all three run buttons, so a
181
+ * future call site cannot forget the token and silently lose the gate. */
182
+ export async function approveAndBuildRunBody(plan, { sessionId } = {}) {
183
+ const res = await fetch(apiUrl("/api/sandbox/approve"), {
184
+ method: "POST",
185
+ headers: { "Content-Type": "application/json" },
186
+ body: JSON.stringify({ plan_id: plan.plan_id, session_id: sessionId || null }),
187
+ });
188
+ const data = await res.json().catch(() => ({}));
189
+ if (!res.ok) {
190
+ throw new Error(data.detail || `Approval failed (HTTP ${res.status})`);
191
+ }
192
+ return {
193
+ language: plan.language,
194
+ code: plan.inline_code,
195
+ timeout_sec: plan.timeout_sec,
196
+ approval_token: data.approval_token,
197
+ session_id: sessionId || null,
198
+ };
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // Styles
203
+ // ---------------------------------------------------------------------------
204
+
205
+ const dtStyle = {
206
+ fontSize: 11, color: "#9092b5", textTransform: "uppercase",
207
+ letterSpacing: "0.05em", margin: 0,
208
+ };
209
+ const ddStyle = { margin: "0 0 6px", fontSize: 13, color: "#e4e4e7" };
210
+
211
+ const fullStyles = {
212
+ card: {
213
+ margin: "8px 0",
214
+ background: "#0d1117",
215
+ border: "1px solid #1f2937",
216
+ borderLeft: "3px solid #10B981",
217
+ borderRadius: 10,
218
+ padding: 16,
219
+ color: "#e4e4e7",
220
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
221
+ },
222
+ header: { display: "flex", alignItems: "center", gap: 10, marginBottom: 10 },
223
+ badge: {
224
+ fontSize: 10, fontWeight: 700, letterSpacing: "0.06em",
225
+ padding: "2px 8px", borderRadius: 4,
226
+ background: "#0d3320", color: "#86efac", textTransform: "uppercase",
227
+ },
228
+ title: { margin: 0, fontSize: 15, fontWeight: 600 },
229
+ fields: {
230
+ display: "grid", gridTemplateColumns: "120px 1fr",
231
+ rowGap: 4, columnGap: 12, margin: "10px 0",
232
+ },
233
+ checks: {
234
+ listStyle: "none", padding: 0, margin: "8px 0",
235
+ display: "flex", flexWrap: "wrap", gap: 6,
236
+ },
237
+ check: {
238
+ fontSize: 11, color: "#86efac",
239
+ background: "rgba(16,185,129,0.08)",
240
+ border: "1px solid rgba(16,185,129,0.25)",
241
+ borderRadius: 4, padding: "2px 8px",
242
+ },
243
+ checkIcon: { marginRight: 4 },
244
+ warnings: { listStyle: "none", padding: 0, margin: "10px 0 4px" },
245
+ warning: {
246
+ fontSize: 12,
247
+ padding: "6px 10px", borderRadius: 4, border: "1px solid",
248
+ marginBottom: 4, display: "flex", gap: 8, alignItems: "flex-start",
249
+ },
250
+ warnIcon: { fontSize: 14, lineHeight: 1 },
251
+ warnDetail: { opacity: 0.8 },
252
+ snippetWrap: {
253
+ margin: "8px 0",
254
+ border: "1px solid #1f2937", borderRadius: 6, padding: "6px 10px",
255
+ },
256
+ snippetLabel: { fontSize: 11, color: "#9092b5", cursor: "pointer" },
257
+ snippet: {
258
+ margin: "6px 0 0", padding: 8, fontSize: 12,
259
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
260
+ background: "#000", color: "#d4d4d8", borderRadius: 4,
261
+ maxHeight: 240, overflow: "auto", whiteSpace: "pre-wrap",
262
+ },
263
+ footer: { display: "flex", gap: 8, marginTop: 12 },
264
+ primary: {
265
+ background: "#10B981", color: "#052e1c", border: "0",
266
+ borderRadius: 6, padding: "8px 16px", fontSize: 13, fontWeight: 600,
267
+ cursor: "pointer",
268
+ },
269
+ secondary: {
270
+ background: "transparent", color: "#a1a1aa",
271
+ border: "1px solid #3F3F46", borderRadius: 6,
272
+ padding: "7px 14px", fontSize: 13, cursor: "pointer",
273
+ },
274
+ tertiary: {
275
+ background: "transparent", color: "#71717a",
276
+ border: "1px solid #27272a", borderRadius: 6,
277
+ padding: "7px 14px", fontSize: 13, cursor: "pointer",
278
+ marginLeft: "auto",
279
+ },
280
+ };
281
+
282
+ // Compact variant — same structure, denser padding, no inline snippet
283
+ // expander. Used for code-block Run confirmation popovers.
284
+ const compactStyles = {
285
+ ...fullStyles,
286
+ card: {
287
+ ...fullStyles.card,
288
+ padding: 10,
289
+ margin: "6px 0",
290
+ borderRadius: 8,
291
+ },
292
+ title: { margin: 0, fontSize: 13, fontWeight: 600 },
293
+ fields: {
294
+ ...fullStyles.fields,
295
+ gridTemplateColumns: "90px 1fr",
296
+ rowGap: 2,
297
+ margin: "6px 0",
298
+ },
299
+ primary: { ...fullStyles.primary, padding: "6px 12px", fontSize: 12 },
300
+ secondary: { ...fullStyles.secondary, padding: "5px 10px", fontSize: 12 },
301
+ tertiary: { ...fullStyles.tertiary, padding: "5px 10px", fontSize: 12 },
302
+ };
frontend/components/FilePreviewPanel.jsx ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/FilePreviewPanel.jsx
2
+ //
3
+ // Read-first file viewer with two density modes.
4
+ //
5
+ // mode="preview" Narrow right-side drawer for a quick look.
6
+ // ~520px wide, primary CTA "Prepare Run".
7
+ // mode="workspace" Wide right-side editor for serious review.
8
+ // ~85vw, same actions, much more reading room.
9
+ //
10
+ // Header vocabulary follows the enterprise verbs the design review
11
+ // nailed down:
12
+ //
13
+ // [▶ Prepare Run] only on runnable files (hidden on README etc.)
14
+ // [Open Workspace] upgrades preview → workspace (or back)
15
+ // [⋯] overflow: Ask GitPilot · Open Canvas ·
16
+ // Copy path · Copy contents
17
+ //
18
+ // "Prepare Run" never runs anything directly — it dispatches the
19
+ // gitpilot:run-file event which lands on the green ExecutionPlanCard
20
+ // in chat, where the user approves before the sandbox starts.
21
+ //
22
+ // Error state: when the file content fetch fails we hide every action
23
+ // that depends on having content (Prepare Run / Canvas / Ask). Only
24
+ // safe actions remain (Retry / Copy path).
25
+
26
+ import React, { useEffect, useMemo, useRef, useState } from "react";
27
+
28
+ const RUNNABLE_FILE_EXTS = new Set(["py", "js", "mjs", "cjs", "sh", "bash"]);
29
+
30
+ const LANG_LABEL = {
31
+ py: "Python", js: "JavaScript", mjs: "JavaScript", cjs: "JavaScript",
32
+ sh: "Shell", bash: "Shell",
33
+ md: "Markdown", json: "JSON", yml: "YAML", yaml: "YAML", toml: "TOML",
34
+ html: "HTML", css: "CSS", ts: "TypeScript", tsx: "TypeScript",
35
+ rs: "Rust", go: "Go", java: "Java", c: "C", cpp: "C++", h: "C/C++",
36
+ };
37
+
38
+ function extOf(path) {
39
+ if (!path || !path.includes(".")) return "";
40
+ return path.split(".").pop().toLowerCase();
41
+ }
42
+
43
+ function bytesPretty(n) {
44
+ if (n == null) return "";
45
+ if (n < 1024) return `${n} B`;
46
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
47
+ return `${(n / 1024 / 1024).toFixed(2)} MB`;
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Overflow menu — secondary actions live here so the header stays calm.
52
+ // ---------------------------------------------------------------------------
53
+
54
+ function OverflowMenu({ path, content, runnable, onClose }) {
55
+ useEffect(() => {
56
+ const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
57
+ const onDown = () => onClose?.();
58
+ window.addEventListener("keydown", onKey);
59
+ window.addEventListener("mousedown", onDown);
60
+ return () => {
61
+ window.removeEventListener("keydown", onKey);
62
+ window.removeEventListener("mousedown", onDown);
63
+ };
64
+ }, [onClose]);
65
+
66
+ const copy = (text) => {
67
+ if (navigator?.clipboard && text != null) navigator.clipboard.writeText(text).catch(() => {});
68
+ };
69
+ const items = [
70
+ { label: "Ask GitPilot",
71
+ onClick: () => window.dispatchEvent(new CustomEvent("gitpilot:ask-about-file", { detail: { path } })) },
72
+ { label: "Open in Canvas", runnable: true,
73
+ onClick: () => window.dispatchEvent(new CustomEvent("gitpilot:open-in-canvas", { detail: { path } })) },
74
+ { divider: true },
75
+ { label: "Copy path", onClick: () => copy(path) },
76
+ { label: "Copy contents", onClick: () => copy(content), disabled: !content },
77
+ ];
78
+
79
+ return (
80
+ <div role="menu"
81
+ onMouseDown={(e) => e.stopPropagation()}
82
+ style={{
83
+ position: "absolute", right: 6, top: 36, zIndex: 50,
84
+ minWidth: 200,
85
+ background: "#18181B", border: "1px solid #3F3F46",
86
+ borderRadius: 6, padding: "4px 0",
87
+ boxShadow: "0 8px 20px rgba(0,0,0,0.45)",
88
+ }}>
89
+ {items.map((it, i) => {
90
+ if (it.divider) return <div key={i} style={{ height: 1, background: "#27272A", margin: "4px 0" }} />;
91
+ if (it.runnable && !runnable) return null;
92
+ return (
93
+ <button
94
+ key={i}
95
+ role="menuitem"
96
+ type="button"
97
+ disabled={!!it.disabled}
98
+ onClick={(e) => { e.stopPropagation(); it.onClick(); onClose?.(); }}
99
+ style={{
100
+ width: "100%", textAlign: "left",
101
+ background: "transparent",
102
+ color: it.disabled ? "#52525B" : "#E4E4E7",
103
+ border: "none",
104
+ padding: "6px 12px", fontSize: 12,
105
+ cursor: it.disabled ? "not-allowed" : "pointer",
106
+ }}
107
+ onMouseEnter={(e) => { if (!it.disabled) e.currentTarget.style.background = "#27272A"; }}
108
+ onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
109
+ >
110
+ {it.label}
111
+ </button>
112
+ );
113
+ })}
114
+ </div>
115
+ );
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Main panel
120
+ // ---------------------------------------------------------------------------
121
+
122
+ export default function FilePreviewPanel({
123
+ path,
124
+ content,
125
+ loading,
126
+ error,
127
+ errorCode, // numeric HTTP status when known (e.g. 404)
128
+ notFoundKind, // "deleted" | "syncing" | "unavailable"
129
+ mode = "preview", // "preview" | "workspace"
130
+ branch,
131
+ onModeChange,
132
+ onClose,
133
+ onRetry,
134
+ onRefreshTree,
135
+ }) {
136
+ const ext = extOf(path);
137
+ const lang = LANG_LABEL[ext] || ext.toUpperCase() || "Text";
138
+ const runnable = RUNNABLE_FILE_EXTS.has(ext);
139
+ const size = content ? new Blob([content]).size : null;
140
+ const filename = path ? path.split("/").pop() : "";
141
+ const [menuOpen, setMenuOpen] = useState(false);
142
+ const menuBtnRef = useRef(null);
143
+
144
+ // Esc closes — keyboard contract every modal/drawer in GitPilot uses.
145
+ useEffect(() => {
146
+ const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
147
+ window.addEventListener("keydown", onKey);
148
+ return () => window.removeEventListener("keydown", onKey);
149
+ }, [onClose]);
150
+
151
+ const prepareRun = () => {
152
+ window.dispatchEvent(new CustomEvent("gitpilot:run-file", { detail: { path } }));
153
+ onClose?.();
154
+ };
155
+ const toggleWorkspace = () => {
156
+ if (onModeChange) onModeChange(mode === "workspace" ? "preview" : "workspace");
157
+ };
158
+
159
+ const lines = useMemo(() => (content || "").split("\n"), [content]);
160
+
161
+ // Width contract: preview = peek, workspace = serious reading.
162
+ const widthCss = mode === "workspace"
163
+ ? "min(1280px, 86vw)"
164
+ : "min(520px, 44vw)";
165
+
166
+ // Decide which actions to show. Two rules:
167
+ // 1. While loading, secondary actions exist but disabled.
168
+ // 2. On error, hide every action that requires content; we show
169
+ // Retry + Copy path only.
170
+ const showActions = !error;
171
+
172
+ return (
173
+ <aside style={{ ...s.shell, width: widthCss }} role="region" aria-label="File preview">
174
+ <header style={s.header}>
175
+ <div style={s.titleRow}>
176
+ <div style={{ minWidth: 0 }}>
177
+ <div style={s.filename}>{filename || "Untitled"}</div>
178
+ <div style={s.subpath}>
179
+ <span style={{ opacity: 0.8 }}>Path:</span> {path}
180
+ {branch && (
181
+ <>
182
+ <span style={s.dot}>·</span>
183
+ <span style={{ opacity: 0.8 }}>Branch:</span> {branch}
184
+ </>
185
+ )}
186
+ </div>
187
+ </div>
188
+ <div style={s.metaPills}>
189
+ <span style={s.pill}>{lang}</span>
190
+ {size != null && <span style={s.pillDim}>{bytesPretty(size)}</span>}
191
+ <button type="button" style={s.btnClose} onClick={onClose} aria-label="Close preview">
192
+ ✕
193
+ </button>
194
+ </div>
195
+ </div>
196
+
197
+ <div style={s.actions}>
198
+ {showActions && runnable && (
199
+ <button
200
+ type="button" style={s.btnPrimary} onClick={prepareRun}
201
+ disabled={loading || !content}
202
+ title="Build an Execution Plan you can review before running"
203
+ >
204
+ ▶ Prepare Run
205
+ </button>
206
+ )}
207
+ {showActions && (
208
+ <button type="button" style={s.btnSecondary} onClick={toggleWorkspace}
209
+ title={mode === "workspace" ? "Collapse to preview" : "Open a wider editor view"}>
210
+ {mode === "workspace" ? "Collapse" : "Open Workspace"}
211
+ </button>
212
+ )}
213
+ {/* Error-only actions */}
214
+ {error && (
215
+ <button type="button" style={s.btnPrimary} onClick={onRetry}>
216
+ Retry
217
+ </button>
218
+ )}
219
+ {error && (
220
+ <button
221
+ type="button" style={s.btnSecondary}
222
+ onClick={() => {
223
+ if (navigator?.clipboard && path) navigator.clipboard.writeText(path).catch(() => {});
224
+ }}
225
+ >
226
+ Copy path
227
+ </button>
228
+ )}
229
+
230
+ {/* Overflow menu — only on the happy path; on error we
231
+ already trimmed the safe-only action set above. */}
232
+ {showActions && (
233
+ <div style={{ marginLeft: "auto", position: "relative" }}>
234
+ <button
235
+ type="button" ref={menuBtnRef}
236
+ style={s.btnSecondary}
237
+ aria-haspopup="menu" aria-expanded={menuOpen}
238
+ onMouseDown={(e) => e.stopPropagation()}
239
+ onClick={() => setMenuOpen((v) => !v)}
240
+ title="More actions"
241
+ >
242
+ ⋯
243
+ </button>
244
+ {menuOpen && (
245
+ <OverflowMenu
246
+ path={path}
247
+ content={content}
248
+ runnable={runnable}
249
+ onClose={() => setMenuOpen(false)}
250
+ />
251
+ )}
252
+ </div>
253
+ )}
254
+ </div>
255
+ </header>
256
+
257
+ <div style={s.body}>
258
+ {loading && <div style={s.empty}>Loading {path}…</div>}
259
+
260
+ {error && !loading && (
261
+ <NotAvailableCard
262
+ path={path}
263
+ branch={branch}
264
+ error={error}
265
+ errorCode={errorCode}
266
+ kind={notFoundKind}
267
+ onRetry={onRetry}
268
+ onRefreshTree={onRefreshTree}
269
+ />
270
+ )}
271
+
272
+ {!loading && !error && (
273
+ <pre style={s.code}>
274
+ {lines.map((line, i) => (
275
+ <div key={i} style={s.lineRow}>
276
+ <span style={s.lineNo}>{i + 1}</span>
277
+ <span style={s.lineCode}>{line || " "}</span>
278
+ </div>
279
+ ))}
280
+ </pre>
281
+ )}
282
+ </div>
283
+ </aside>
284
+ );
285
+ }
286
+
287
+ // ---------------------------------------------------------------------------
288
+ // Calm empty state — replaces the harsh red "Couldn't load this file"
289
+ // box. Same component, classifies the situation into one of:
290
+ // deleted → execution removed the file from this branch
291
+ // syncing → execution created the file but content isn't ready yet
292
+ // unavailable → file simply isn't on this branch
293
+ // ---------------------------------------------------------------------------
294
+
295
+ function NotAvailableCard({ path, branch, error, errorCode, kind, onRetry, onRefreshTree }) {
296
+ const isNotFound =
297
+ errorCode === 404 ||
298
+ /not\s*found/i.test(String(error || "")) ||
299
+ /HTTP\s*404/i.test(String(error || ""));
300
+
301
+ const effectiveKind = isNotFound ? (kind || "unavailable") : "error";
302
+
303
+ const copy = {
304
+ deleted: {
305
+ icon: "🗑",
306
+ title: "File deleted",
307
+ body: `${path ? path.split("/").pop() : "This file"} was removed by the latest execution. View the execution summary for details.`,
308
+ tone: "muted",
309
+ },
310
+ syncing: {
311
+ icon: "↻",
312
+ title: "File still syncing",
313
+ body: "GitPilot just created this file. Its content is being published to the active branch — try again in a moment.",
314
+ tone: "info",
315
+ },
316
+ unavailable: {
317
+ icon: "○",
318
+ title: "File unavailable",
319
+ body: "This file isn't available on the current branch. It may have been moved, renamed, or never committed here.",
320
+ tone: "muted",
321
+ },
322
+ error: {
323
+ icon: "!",
324
+ title: "Couldn't load this file",
325
+ body: "Something went wrong fetching the file content. Try again, or refresh the file tree.",
326
+ tone: "warn",
327
+ },
328
+ }[effectiveKind];
329
+
330
+ return (
331
+ <div
332
+ className={`file-notavail file-notavail--${copy.tone}`}
333
+ role="status"
334
+ aria-live="polite"
335
+ >
336
+ <div className="file-notavail__icon" aria-hidden="true">{copy.icon}</div>
337
+ <div className="file-notavail__title">{copy.title}</div>
338
+ <div className="file-notavail__body">{copy.body}</div>
339
+
340
+ <dl className="file-notavail__fields">
341
+ <dt>Path</dt>
342
+ <dd><code>{path}</code></dd>
343
+ {branch && (
344
+ <>
345
+ <dt>Branch</dt>
346
+ <dd><code>{branch}</code></dd>
347
+ </>
348
+ )}
349
+ </dl>
350
+
351
+ <div className="file-notavail__actions">
352
+ <button type="button" className="file-notavail__btn file-notavail__btn--primary" onClick={onRetry}>
353
+ Retry
354
+ </button>
355
+ {onRefreshTree && (
356
+ <button type="button" className="file-notavail__btn" onClick={onRefreshTree}>
357
+ Refresh files
358
+ </button>
359
+ )}
360
+ <button
361
+ type="button"
362
+ className="file-notavail__btn"
363
+ onClick={() => {
364
+ if (navigator?.clipboard && path) {
365
+ navigator.clipboard.writeText(path).catch(() => {});
366
+ }
367
+ }}
368
+ >
369
+ Copy path
370
+ </button>
371
+ </div>
372
+
373
+ {effectiveKind === "error" && error && (
374
+ <details className="file-notavail__details">
375
+ <summary>Technical details</summary>
376
+ <pre>{String(error)}</pre>
377
+ </details>
378
+ )}
379
+ </div>
380
+ );
381
+ }
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // Styles
385
+ // ---------------------------------------------------------------------------
386
+
387
+ const s = {
388
+ shell: {
389
+ position: "fixed",
390
+ top: 0, right: 0, bottom: 0,
391
+ // ``width`` is set per-mode in the component.
392
+ background: "#0d0e17",
393
+ borderLeft: "1px solid #2a2b36",
394
+ display: "flex", flexDirection: "column",
395
+ zIndex: 90,
396
+ color: "#e4e4e7",
397
+ fontFamily: "system-ui, sans-serif",
398
+ boxShadow: "-12px 0 32px rgba(0,0,0,0.45)",
399
+ transition: "width 0.15s ease",
400
+ },
401
+ header: {
402
+ padding: "12px 16px 10px",
403
+ borderBottom: "1px solid #2a2b36",
404
+ background: "#14152a",
405
+ },
406
+ titleRow: { display: "flex", justifyContent: "space-between", gap: 12 },
407
+ filename: {
408
+ fontSize: 16, fontWeight: 600,
409
+ fontFamily: "ui-monospace, monospace",
410
+ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
411
+ },
412
+ subpath: {
413
+ fontSize: 11, color: "#9092b5", marginTop: 2,
414
+ fontFamily: "ui-monospace, monospace",
415
+ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
416
+ },
417
+ dot: { margin: "0 6px", color: "#52525B" },
418
+ metaPills: { display: "flex", alignItems: "flex-start", gap: 6, flexShrink: 0 },
419
+ pill: {
420
+ fontSize: 11, padding: "2px 8px", borderRadius: 4,
421
+ background: "#1e3a5f", color: "#93c5fd",
422
+ border: "1px solid #3B82F6",
423
+ },
424
+ pillDim: {
425
+ fontSize: 11, padding: "2px 8px", borderRadius: 4,
426
+ background: "#0d0e17", color: "#9092b5",
427
+ border: "1px solid #2c2d46",
428
+ },
429
+ actions: { display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap", alignItems: "center" },
430
+ btnPrimary: {
431
+ padding: "6px 14px", fontSize: 12, fontWeight: 600,
432
+ background: "#10B981", color: "#052e1c",
433
+ border: "0", borderRadius: 6, cursor: "pointer",
434
+ },
435
+ btnSecondary: {
436
+ padding: "6px 12px", fontSize: 12,
437
+ background: "transparent", color: "#c3c5dd",
438
+ border: "1px solid #2c2d46", borderRadius: 6, cursor: "pointer",
439
+ },
440
+ btnClose: {
441
+ marginLeft: 6,
442
+ padding: "2px 8px", fontSize: 14,
443
+ background: "transparent", color: "#9092b5",
444
+ border: "1px solid #2c2d46", borderRadius: 6, cursor: "pointer",
445
+ },
446
+ body: { flex: 1, overflow: "auto", padding: "12px 0" },
447
+ empty: { padding: 30, textAlign: "center", color: "#9092b5", fontSize: 13 },
448
+ code: {
449
+ margin: 0, padding: 0,
450
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
451
+ fontSize: 12.5, lineHeight: 1.55,
452
+ color: "#D4D4D8",
453
+ background: "transparent",
454
+ whiteSpace: "pre",
455
+ },
456
+ lineRow: { display: "grid", gridTemplateColumns: "48px 1fr", gap: 12, padding: "0 18px" },
457
+ lineNo: {
458
+ color: "#52525B", textAlign: "right",
459
+ userSelect: "none",
460
+ fontVariantNumeric: "tabular-nums",
461
+ },
462
+ lineCode: { whiteSpace: "pre-wrap", wordBreak: "break-word" },
463
+ };
frontend/components/FileTree.jsx ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from "react";
2
+ import { apiUrl } from "../utils/api.js";
3
+
4
+ /**
5
+ * Simple recursive file tree viewer with refresh support
6
+ * Fetches tree data directly using the API.
7
+ */
8
+ export default function FileTree({ repo, refreshTrigger, branch }) {
9
+ const [tree, setTree] = useState([]);
10
+ const [loading, setLoading] = useState(false);
11
+ const [isSwitchingBranch, setIsSwitchingBranch] = useState(false);
12
+ const [error, setError] = useState(null);
13
+ const [localRefresh, setLocalRefresh] = useState(0);
14
+ // Search query for the in-sidebar filter. Empty string == no filter.
15
+ // Filter runs case-insensitively on path basenames *and* full paths
16
+ // so users can pinpoint a file even in deeply nested folders.
17
+ const [query, setQuery] = useState("");
18
+ // Which file is currently focused in the preview panel — populated
19
+ // by the ``gitpilot:file-opened`` event ChatPanel emits when the
20
+ // preview finishes loading. Drives the ◄ marker + active row tint.
21
+ const [selectedPath, setSelectedPath] = useState(null);
22
+
23
+ useEffect(() => {
24
+ const onOpened = (e) => setSelectedPath(e?.detail?.path || null);
25
+ const onClosed = () => setSelectedPath(null);
26
+ const onRefresh = () => setLocalRefresh((n) => n + 1);
27
+ window.addEventListener("gitpilot:file-opened", onOpened);
28
+ window.addEventListener("gitpilot:file-closed", onClosed);
29
+ window.addEventListener("gitpilot:refresh-tree", onRefresh);
30
+ return () => {
31
+ window.removeEventListener("gitpilot:file-opened", onOpened);
32
+ window.removeEventListener("gitpilot:file-closed", onClosed);
33
+ window.removeEventListener("gitpilot:refresh-tree", onRefresh);
34
+ };
35
+ }, []);
36
+
37
+ useEffect(() => {
38
+ if (!repo) return;
39
+
40
+ // Determine if this is a branch switch (we already have data)
41
+ const hasExistingData = tree.length > 0;
42
+ if (hasExistingData) {
43
+ setIsSwitchingBranch(true);
44
+ } else {
45
+ setLoading(true);
46
+ }
47
+ setError(null);
48
+
49
+ // Construct headers manually
50
+ let headers = {};
51
+ try {
52
+ const token = localStorage.getItem("github_token");
53
+ if (token) {
54
+ headers = { Authorization: `Bearer ${token}` };
55
+ }
56
+ } catch (e) {
57
+ console.warn("Unable to read github_token", e);
58
+ }
59
+
60
+ // Add cache busting + selected branch ref
61
+ const refParam = branch ? `&ref=${encodeURIComponent(branch)}` : "";
62
+ const cacheBuster = `?_t=${Date.now()}${refParam}`;
63
+
64
+ let cancelled = false;
65
+
66
+ fetch(apiUrl(`/api/repos/${repo.owner}/${repo.name}/tree${cacheBuster}`), { headers })
67
+ .then(async (res) => {
68
+ if (!res.ok) {
69
+ const errData = await res.json().catch(() => ({}));
70
+ throw new Error(errData.detail || "Failed to load files");
71
+ }
72
+ return res.json();
73
+ })
74
+ .then((data) => {
75
+ if (cancelled) return;
76
+ if (data.files && Array.isArray(data.files)) {
77
+ setTree(buildTree(data.files));
78
+ setError(null);
79
+ } else {
80
+ setError("No files found in repository");
81
+ }
82
+ })
83
+ .catch((err) => {
84
+ if (cancelled) return;
85
+ setError(err.message);
86
+ console.error("FileTree error:", err);
87
+ })
88
+ .finally(() => {
89
+ if (cancelled) return;
90
+ setIsSwitchingBranch(false);
91
+ setLoading(false);
92
+ });
93
+
94
+ return () => { cancelled = true; };
95
+ }, [repo, branch, refreshTrigger, localRefresh]); // eslint-disable-line react-hooks/exhaustive-deps
96
+
97
+ const handleRefresh = () => {
98
+ setLocalRefresh(prev => prev + 1);
99
+ };
100
+
101
+ // Theme matching parent component
102
+ const theme = {
103
+ border: "#27272A",
104
+ textPrimary: "#EDEDED",
105
+ textSecondary: "#A1A1AA",
106
+ accent: "#D95C3D",
107
+ warningText: "#F59E0B",
108
+ warningBg: "rgba(245, 158, 11, 0.1)",
109
+ warningBorder: "rgba(245, 158, 11, 0.2)",
110
+ };
111
+
112
+ const styles = {
113
+ header: {
114
+ display: "flex",
115
+ alignItems: "center",
116
+ justifyContent: "space-between",
117
+ padding: "8px 20px 8px 10px",
118
+ marginBottom: "8px",
119
+ borderBottom: `1px solid ${theme.border}`,
120
+ },
121
+ headerTitle: {
122
+ fontSize: "12px",
123
+ fontWeight: "600",
124
+ color: theme.textSecondary,
125
+ textTransform: "uppercase",
126
+ letterSpacing: "0.5px",
127
+ },
128
+ refreshButton: {
129
+ backgroundColor: "transparent",
130
+ border: `1px solid ${theme.border}`,
131
+ color: theme.textSecondary,
132
+ padding: "4px 8px",
133
+ borderRadius: "4px",
134
+ fontSize: "11px",
135
+ cursor: loading ? "not-allowed" : "pointer",
136
+ display: "flex",
137
+ alignItems: "center",
138
+ gap: "4px",
139
+ transition: "all 0.2s",
140
+ opacity: loading ? 0.5 : 1,
141
+ },
142
+ switchingBar: {
143
+ padding: "6px 20px",
144
+ fontSize: "11px",
145
+ color: theme.textSecondary,
146
+ backgroundColor: "rgba(59, 130, 246, 0.06)",
147
+ borderBottom: `1px solid ${theme.border}`,
148
+ },
149
+ loadingText: {
150
+ padding: "0 20px",
151
+ color: theme.textSecondary,
152
+ fontSize: "13px",
153
+ },
154
+ errorBox: {
155
+ padding: "12px 20px",
156
+ color: theme.warningText,
157
+ fontSize: "12px",
158
+ backgroundColor: theme.warningBg,
159
+ border: `1px solid ${theme.warningBorder}`,
160
+ borderRadius: "6px",
161
+ margin: "0 10px",
162
+ },
163
+ emptyText: {
164
+ padding: "0 20px",
165
+ color: theme.textSecondary,
166
+ fontSize: "13px",
167
+ },
168
+ treeContainer: {
169
+ fontSize: "13px",
170
+ color: theme.textSecondary,
171
+ padding: "0 10px 20px 10px",
172
+ },
173
+ };
174
+
175
+ return (
176
+ <div>
177
+ {/* Header with Refresh Button */}
178
+ <div style={styles.header}>
179
+ <span style={styles.headerTitle}>Files</span>
180
+ <button
181
+ type="button"
182
+ style={styles.refreshButton}
183
+ onClick={handleRefresh}
184
+ disabled={loading}
185
+ onMouseOver={(e) => {
186
+ if (!loading) {
187
+ e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.05)";
188
+ }
189
+ }}
190
+ onMouseOut={(e) => {
191
+ e.currentTarget.style.backgroundColor = "transparent";
192
+ }}
193
+ >
194
+ <svg
195
+ width="12"
196
+ height="12"
197
+ viewBox="0 0 24 24"
198
+ fill="none"
199
+ stroke="currentColor"
200
+ strokeWidth="2"
201
+ style={{
202
+ transform: loading ? "rotate(360deg)" : "rotate(0deg)",
203
+ transition: "transform 0.6s ease",
204
+ }}
205
+ >
206
+ <path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2" />
207
+ </svg>
208
+ {loading ? "..." : "Refresh"}
209
+ </button>
210
+ </div>
211
+
212
+ {/* Branch switch indicator (shown above existing tree, doesn't clear it) */}
213
+ {isSwitchingBranch && (
214
+ <div style={styles.switchingBar}>Loading branch...</div>
215
+ )}
216
+
217
+ {/* Content */}
218
+ {loading && tree.length === 0 && (
219
+ <div style={styles.loadingText}>Loading files...</div>
220
+ )}
221
+
222
+ {!loading && !isSwitchingBranch && error && (
223
+ <div style={styles.errorBox}>{error}</div>
224
+ )}
225
+
226
+ {!loading && !isSwitchingBranch && !error && tree.length === 0 && (
227
+ <div style={styles.emptyText}>No files found</div>
228
+ )}
229
+
230
+ {tree.length > 0 && (
231
+ <>
232
+ {/* In-sidebar file search. Enterprise repos run to hundreds
233
+ of files; the explorer needs a quick narrowing affordance
234
+ before any of the contextual menus matter. */}
235
+ <input
236
+ type="text"
237
+ value={query}
238
+ onChange={(e) => setQuery(e.target.value)}
239
+ placeholder="🔍 Search files…"
240
+ spellCheck={false}
241
+ style={{
242
+ width: "100%", boxSizing: "border-box",
243
+ margin: "4px 0 8px",
244
+ padding: "6px 10px", fontSize: 12,
245
+ background: "#0d0e17", color: "#e4e4e7",
246
+ border: "1px solid #27272A", borderRadius: 6,
247
+ outline: "none",
248
+ fontFamily: "system-ui, sans-serif",
249
+ }}
250
+ />
251
+
252
+ <div style={{
253
+ ...styles.treeContainer,
254
+ opacity: isSwitchingBranch ? 0.5 : 1,
255
+ transition: "opacity 0.15s ease",
256
+ }}>
257
+ {tree.map((node) => (
258
+ <TreeNode
259
+ key={node.path}
260
+ node={node}
261
+ level={0}
262
+ filter={query.trim().toLowerCase()}
263
+ selectedPath={selectedPath}
264
+ />
265
+ ))}
266
+ </div>
267
+ </>
268
+ )}
269
+ </div>
270
+ );
271
+ }
272
+
273
+ // Files with these extensions get a "Prepare Run" menu item. Mirrors
274
+ // the backend's _RUNNABLE_EXTENSIONS so the menu only offers a run
275
+ // where the sandbox planner would actually accept the file.
276
+ const RUNNABLE_FILE_EXTS = new Set(["py", "js", "mjs", "cjs", "sh", "bash"]);
277
+
278
+ function isRunnableFile(name, type) {
279
+ if (type === "tree") return false;
280
+ if (!name || !name.includes(".")) return false;
281
+ const ext = name.split(".").pop().toLowerCase();
282
+ return RUNNABLE_FILE_EXTS.has(ext);
283
+ }
284
+
285
+ // Window-event dispatch helpers — keep FileTree decoupled from
286
+ // ChatPanel. Same pattern as the existing approval-flow events.
287
+ function dispatchOpenFile(path) {
288
+ try {
289
+ window.dispatchEvent(new CustomEvent("gitpilot:open-file", { detail: { path } }));
290
+ } catch (_e) { /* old browser */ }
291
+ }
292
+ function dispatchOpenInCanvas(path) {
293
+ try {
294
+ window.dispatchEvent(new CustomEvent("gitpilot:open-in-canvas", { detail: { path } }));
295
+ } catch (_e) { /* old browser */ }
296
+ }
297
+ function dispatchRunFile(path) {
298
+ try {
299
+ window.dispatchEvent(new CustomEvent("gitpilot:run-file", { detail: { path } }));
300
+ } catch (_e) { /* old browser */ }
301
+ }
302
+ function dispatchAskAboutFile(path) {
303
+ try {
304
+ window.dispatchEvent(new CustomEvent("gitpilot:ask-about-file", { detail: { path } }));
305
+ } catch (_e) { /* old browser */ }
306
+ }
307
+ function copyToClipboard(text) {
308
+ if (navigator?.clipboard) navigator.clipboard.writeText(text).catch(() => {});
309
+ }
310
+
311
+ // Tiny dropdown — positioned absolutely below the row's ⋯ trigger.
312
+ // Closes on outside click or Escape. Built-in <select> would be
313
+ // faster to write but the visual contract for an enterprise file
314
+ // explorer demands a real menu (icons, separators, descriptions).
315
+ function FileActionsMenu({ path, runnable, onClose }) {
316
+ React.useEffect(() => {
317
+ const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
318
+ const onDown = () => onClose?.();
319
+ window.addEventListener("keydown", onKey);
320
+ window.addEventListener("mousedown", onDown);
321
+ return () => {
322
+ window.removeEventListener("keydown", onKey);
323
+ window.removeEventListener("mousedown", onDown);
324
+ };
325
+ }, [onClose]);
326
+
327
+ // Menu vocabulary maps 1:1 to the design's recommended verbs. "Open
328
+ // Preview" is the calm default; "Open Workspace" widens the panel
329
+ // for serious reading/editing; "Prepare Run…" surfaces the
330
+ // ExecutionPlanCard. Canvas (the runnable split editor) is moved
331
+ // to the overflow because it's the heaviest mode and shouldn't
332
+ // compete with Preview / Workspace for attention.
333
+ const items = [
334
+ { label: "Open Preview", onClick: () => dispatchOpenFile(path) },
335
+ {
336
+ label: "Open Workspace",
337
+ onClick: () => window.dispatchEvent(
338
+ new CustomEvent("gitpilot:open-workspace", { detail: { path } })
339
+ ),
340
+ },
341
+ {
342
+ label: "Prepare Run…",
343
+ onClick: () => dispatchRunFile(path),
344
+ runnable: true,
345
+ primary: true,
346
+ },
347
+ { divider: true },
348
+ { label: "Ask GitPilot", onClick: () => dispatchAskAboutFile(path) },
349
+ { label: "Open in Canvas", onClick: () => dispatchOpenInCanvas(path), runnable: true },
350
+ { label: "Copy path", onClick: () => copyToClipboard(path) },
351
+ ];
352
+
353
+ return (
354
+ <div
355
+ role="menu"
356
+ onMouseDown={(e) => e.stopPropagation()}
357
+ style={{
358
+ position: "absolute", right: 4, top: 22, zIndex: 50,
359
+ minWidth: 180,
360
+ background: "#18181B", border: "1px solid #3F3F46",
361
+ borderRadius: 6, padding: "4px 0",
362
+ boxShadow: "0 8px 20px rgba(0,0,0,0.45)",
363
+ fontFamily: "system-ui, sans-serif",
364
+ }}
365
+ >
366
+ {items.map((it, i) => {
367
+ if (it.divider) {
368
+ return <div key={i} style={{ height: 1, background: "#27272A", margin: "4px 0" }} />;
369
+ }
370
+ if (it.runnable && !runnable) return null;
371
+ return (
372
+ <button
373
+ key={i}
374
+ role="menuitem"
375
+ type="button"
376
+ onClick={(e) => { e.stopPropagation(); it.onClick(); onClose?.(); }}
377
+ style={{
378
+ width: "100%", textAlign: "left",
379
+ background: "transparent",
380
+ color: it.primary ? "#86efac" : "#E4E4E7",
381
+ border: "none",
382
+ padding: "6px 12px", fontSize: 12, cursor: "pointer",
383
+ }}
384
+ onMouseEnter={(e) => e.currentTarget.style.background = "#27272A"}
385
+ onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
386
+ >
387
+ {it.label}
388
+ </button>
389
+ );
390
+ })}
391
+ </div>
392
+ );
393
+ }
394
+
395
+ // True when ``node`` or any descendant path/basename contains ``filter``.
396
+ // Folders are rendered if any descendant matches so the filter looks
397
+ // like a flat search even though the tree is recursive.
398
+ function _matchesFilter(node, filter) {
399
+ if (!filter) return true;
400
+ const inThis =
401
+ (node.path && node.path.toLowerCase().includes(filter)) ||
402
+ (node.name && node.name.toLowerCase().includes(filter));
403
+ if (inThis) return true;
404
+ if (!node.children) return false;
405
+ return node.children.some((c) => _matchesFilter(c, filter));
406
+ }
407
+
408
+ // Recursive Node Component
409
+ function TreeNode({ node, level, filter = "", selectedPath = null }) {
410
+ const [userExpanded, setUserExpanded] = useState(false);
411
+ const [hovered, setHovered] = useState(false);
412
+ const [menuOpen, setMenuOpen] = useState(false);
413
+ const isFolder = node.children && node.children.length > 0;
414
+ const runnable = !isFolder && isRunnableFile(node.name, node.type);
415
+ const isSelected = !isFolder && selectedPath === node.path;
416
+
417
+ // Honor the filter: drop subtrees that don't match anywhere. When
418
+ // the filter is active, folders auto-expand so users see the matches
419
+ // without having to chase carets.
420
+ if (filter && !_matchesFilter(node, filter)) return null;
421
+ const expanded = userExpanded || Boolean(filter);
422
+
423
+ const icon = isFolder ? (expanded ? "📂" : "📁") : "📄";
424
+
425
+ const onRowClick = () => {
426
+ if (isFolder) setUserExpanded(!userExpanded);
427
+ else dispatchOpenFile(node.path);
428
+ };
429
+
430
+ return (
431
+ <div style={{ position: "relative" }}>
432
+ <div
433
+ onClick={onRowClick}
434
+ onMouseEnter={() => setHovered(true)}
435
+ onMouseLeave={() => { setHovered(false); /* menu closes on outside-click */ }}
436
+ style={{
437
+ padding: "4px 0",
438
+ paddingLeft: `${level * 12}px`,
439
+ paddingRight: 6,
440
+ cursor: "pointer",
441
+ display: "flex",
442
+ alignItems: "center",
443
+ gap: "6px",
444
+ color: isFolder
445
+ ? "#EDEDED"
446
+ : (isSelected ? "#86efac" : "#D4D4D8"),
447
+ whiteSpace: "nowrap",
448
+ borderRadius: 4,
449
+ background: isSelected
450
+ ? "rgba(16,185,129,0.10)"
451
+ : (hovered ? "#1f1f23" : "transparent"),
452
+ borderLeft: isSelected ? "2px solid #10B981" : "2px solid transparent",
453
+ }}
454
+ title={isFolder ? "" : "Click to open · ⋯ for actions"}
455
+ >
456
+ <span style={{ fontSize: "14px", opacity: 0.7 }}>{icon}</span>
457
+ <span style={{
458
+ flex: 1, overflow: "hidden", textOverflow: "ellipsis",
459
+ fontWeight: isSelected ? 600 : 400,
460
+ }}>
461
+ {node.name}
462
+ </span>
463
+ {/* Selected marker — orient users when scanning a long list. */}
464
+ {isSelected && (
465
+ <span style={{ color: "#10B981", fontSize: 11 }}>◄</span>
466
+ )}
467
+
468
+ {/* Per-row ⋯ menu trigger — visible on hover only so the
469
+ list reads as a clean inventory at rest. */}
470
+ {!isFolder && hovered && (
471
+ <button
472
+ type="button"
473
+ aria-haspopup="menu"
474
+ aria-expanded={menuOpen}
475
+ onMouseDown={(e) => e.stopPropagation()}
476
+ onClick={(e) => {
477
+ e.stopPropagation();
478
+ setMenuOpen((v) => !v);
479
+ }}
480
+ title="File actions"
481
+ style={{
482
+ background: "transparent",
483
+ border: "1px solid transparent",
484
+ color: "#A1A1AA",
485
+ cursor: "pointer",
486
+ fontSize: 14,
487
+ lineHeight: 1,
488
+ padding: "0 6px",
489
+ borderRadius: 4,
490
+ }}
491
+ >
492
+ ⋯
493
+ </button>
494
+ )}
495
+ </div>
496
+
497
+ {menuOpen && (
498
+ <FileActionsMenu
499
+ path={node.path}
500
+ runnable={runnable}
501
+ onClose={() => setMenuOpen(false)}
502
+ />
503
+ )}
504
+
505
+ {isFolder && expanded && (
506
+ <div>
507
+ {node.children.map(child => (
508
+ <TreeNode
509
+ key={child.path}
510
+ node={child}
511
+ level={level + 1}
512
+ filter={filter}
513
+ selectedPath={selectedPath}
514
+ />
515
+ ))}
516
+ </div>
517
+ )}
518
+ </div>
519
+ );
520
+ }
521
+
522
+ // Helper to build tree structure from flat file list
523
+ function buildTree(files) {
524
+ const root = [];
525
+
526
+ files.forEach(file => {
527
+ const parts = file.path.split('/');
528
+ let currentLevel = root;
529
+ let currentPath = "";
530
+
531
+ parts.forEach((part, idx) => {
532
+ currentPath = currentPath ? `${currentPath}/${part}` : part;
533
+
534
+ // Check if node exists at this level
535
+ let existingNode = currentLevel.find(n => n.name === part);
536
+
537
+ if (!existingNode) {
538
+ const newNode = {
539
+ name: part,
540
+ path: currentPath,
541
+ type: idx === parts.length - 1 ? file.type : 'tree',
542
+ children: []
543
+ };
544
+ currentLevel.push(newNode);
545
+ existingNode = newNode;
546
+ }
547
+
548
+ if (idx < parts.length - 1) {
549
+ currentLevel = existingNode.children;
550
+ }
551
+ });
552
+ });
553
+
554
+ // Sort folders first, then files
555
+ const sortNodes = (nodes) => {
556
+ nodes.sort((a, b) => {
557
+ const aIsFolder = a.children.length > 0;
558
+ const bIsFolder = b.children.length > 0;
559
+ if (aIsFolder && !bIsFolder) return -1;
560
+ if (!aIsFolder && bIsFolder) return 1;
561
+ return a.name.localeCompare(b.name);
562
+ });
563
+ nodes.forEach(n => {
564
+ if (n.children.length > 0) sortNodes(n.children);
565
+ });
566
+ };
567
+
568
+ sortNodes(root);
569
+ return root;
570
+ }
frontend/components/FlowViewer.jsx ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useState, useCallback, useRef } from "react";
2
+ import { apiUrl } from "../utils/api.js";
3
+ import ReactFlow, { Background, Controls, MiniMap } from "reactflow";
4
+ import "reactflow/dist/style.css";
5
+
6
+ /* ------------------------------------------------------------------ */
7
+ /* Node type → colour mapping */
8
+ /* ------------------------------------------------------------------ */
9
+ const NODE_COLOURS = {
10
+ agent: { border: "#ff7a3c", bg: "#20141a" },
11
+ router: { border: "#6c8cff", bg: "#141828" },
12
+ tool: { border: "#3a3b4d", bg: "#141821" },
13
+ tool_group: { border: "#3a3b4d", bg: "#141821" },
14
+ user: { border: "#4caf88", bg: "#14211a" },
15
+ output: { border: "#9c6cff", bg: "#1a1428" },
16
+ };
17
+ const DEFAULT_COLOUR = { border: "#3a3b4d", bg: "#141821" };
18
+
19
+ function colourFor(type) {
20
+ return NODE_COLOURS[type] || DEFAULT_COLOUR;
21
+ }
22
+
23
+ const STYLE_COLOURS = {
24
+ single_task: "#6c8cff",
25
+ react_loop: "#ff7a3c",
26
+ crew_pipeline: "#4caf88",
27
+ // The v4 engine (Batch V4-G1). Distinct from react_loop, which was only ever a
28
+ // label on a hand-drawn graph — this one names a topology the agent loop runs.
29
+ agentic_loop: "#b06cff",
30
+ };
31
+
32
+ const STYLE_LABELS = {
33
+ single_task: "Dispatch",
34
+ react_loop: "ReAct Loop",
35
+ crew_pipeline: "Pipeline",
36
+ agentic_loop: "Agentic Loop",
37
+ };
38
+
39
+ /* ------------------------------------------------------------------ */
40
+ /* TopologyCard — single clickable topology card */
41
+ /* ------------------------------------------------------------------ */
42
+ function TopologyCard({ topology, isActive, onClick }) {
43
+ const styleColor = STYLE_COLOURS[topology.execution_style] || "#9a9bb0";
44
+ const agentCount = topology.agents_used?.length || 0;
45
+
46
+ return (
47
+ <button
48
+ type="button"
49
+ onClick={onClick}
50
+ style={{
51
+ ...cardStyles.card,
52
+ borderColor: isActive ? styleColor : "#1e1f30",
53
+ backgroundColor: isActive ? `${styleColor}0D` : "#0c0d14",
54
+ }}
55
+ >
56
+ <div style={cardStyles.cardTop}>
57
+ <span style={cardStyles.icon}>{topology.icon}</span>
58
+ <span
59
+ style={{
60
+ ...cardStyles.styleBadge,
61
+ color: styleColor,
62
+ borderColor: `${styleColor}40`,
63
+ }}
64
+ >
65
+ {STYLE_LABELS[topology.execution_style] || topology.execution_style}
66
+ </span>
67
+ </div>
68
+ <div
69
+ style={{
70
+ ...cardStyles.name,
71
+ color: isActive ? "#f5f5f7" : "#c3c5dd",
72
+ }}
73
+ >
74
+ {topology.name}
75
+ </div>
76
+ <div style={cardStyles.desc}>{topology.description}</div>
77
+ <div style={cardStyles.agentCount}>
78
+ {agentCount} agent{agentCount !== 1 ? "s" : ""}
79
+ </div>
80
+ </button>
81
+ );
82
+ }
83
+
84
+ const cardStyles = {
85
+ card: {
86
+ display: "flex",
87
+ flexDirection: "column",
88
+ gap: 4,
89
+ padding: "10px 12px",
90
+ borderRadius: 8,
91
+ border: "1px solid #1e1f30",
92
+ cursor: "pointer",
93
+ textAlign: "left",
94
+ minWidth: 170,
95
+ maxWidth: 200,
96
+ flexShrink: 0,
97
+ transition: "border-color 0.2s, background-color 0.2s",
98
+ },
99
+ cardTop: {
100
+ display: "flex",
101
+ alignItems: "center",
102
+ justifyContent: "space-between",
103
+ gap: 6,
104
+ },
105
+ icon: {
106
+ fontSize: 18,
107
+ },
108
+ styleBadge: {
109
+ fontSize: 9,
110
+ fontWeight: 700,
111
+ textTransform: "uppercase",
112
+ letterSpacing: "0.05em",
113
+ padding: "1px 6px",
114
+ borderRadius: 4,
115
+ border: "1px solid",
116
+ },
117
+ name: {
118
+ fontSize: 12,
119
+ fontWeight: 600,
120
+ lineHeight: 1.3,
121
+ },
122
+ desc: {
123
+ fontSize: 10,
124
+ color: "#71717A",
125
+ lineHeight: 1.3,
126
+ overflow: "hidden",
127
+ display: "-webkit-box",
128
+ WebkitLineClamp: 2,
129
+ WebkitBoxOrient: "vertical",
130
+ },
131
+ agentCount: {
132
+ fontSize: 9,
133
+ color: "#52525B",
134
+ fontWeight: 600,
135
+ marginTop: 2,
136
+ },
137
+ };
138
+
139
+ /* ------------------------------------------------------------------ */
140
+ /* TopologyPanel — card grid grouped by category */
141
+ /* ------------------------------------------------------------------ */
142
+ function TopologyPanel({
143
+ topologies,
144
+ activeTopology,
145
+ autoMode,
146
+ autoResult,
147
+ onSelect,
148
+ onToggleAuto,
149
+ }) {
150
+ const systems = topologies.filter((t) => t.category === "system");
151
+ const pipelines = topologies.filter((t) => t.category === "pipeline");
152
+
153
+ return (
154
+ <div style={panelStyles.root}>
155
+ {/* Auto-detect toggle */}
156
+ <div style={panelStyles.autoRow}>
157
+ <button
158
+ type="button"
159
+ onClick={onToggleAuto}
160
+ style={{
161
+ ...panelStyles.autoBtn,
162
+ borderColor: autoMode ? "#ff7a3c" : "#27272A",
163
+ color: autoMode ? "#ff7a3c" : "#71717A",
164
+ backgroundColor: autoMode ? "rgba(255, 122, 60, 0.06)" : "transparent",
165
+ }}
166
+ >
167
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
168
+ <circle cx="12" cy="12" r="10" />
169
+ <path d="M12 6v6l4 2" />
170
+ </svg>
171
+ Auto
172
+ </button>
173
+ {autoMode && autoResult && (
174
+ <span style={panelStyles.autoHint}>
175
+ Detected: {autoResult.icon} {autoResult.name}
176
+ {autoResult.confidence != null && (
177
+ <span style={{ opacity: 0.6 }}>
178
+ {" "}({Math.round(autoResult.confidence * 100)}%)
179
+ </span>
180
+ )}
181
+ </span>
182
+ )}
183
+ </div>
184
+
185
+ {/* System architectures */}
186
+ <div style={panelStyles.section}>
187
+ <div style={panelStyles.sectionLabel}>System Architectures</div>
188
+ <div style={panelStyles.cardRow}>
189
+ {systems.map((t) => (
190
+ <TopologyCard
191
+ key={t.id}
192
+ topology={t}
193
+ isActive={activeTopology === t.id}
194
+ onClick={() => onSelect(t.id)}
195
+ />
196
+ ))}
197
+ </div>
198
+ </div>
199
+
200
+ {/* Task pipelines */}
201
+ <div style={panelStyles.section}>
202
+ <div style={panelStyles.sectionLabel}>Task Pipelines</div>
203
+ <div style={panelStyles.cardRow}>
204
+ {pipelines.map((t) => (
205
+ <TopologyCard
206
+ key={t.id}
207
+ topology={t}
208
+ isActive={activeTopology === t.id}
209
+ onClick={() => onSelect(t.id)}
210
+ />
211
+ ))}
212
+ </div>
213
+ </div>
214
+ </div>
215
+ );
216
+ }
217
+
218
+ const panelStyles = {
219
+ root: {
220
+ padding: "8px 16px 12px",
221
+ borderBottom: "1px solid #1e1f30",
222
+ backgroundColor: "#08090e",
223
+ },
224
+ autoRow: {
225
+ display: "flex",
226
+ alignItems: "center",
227
+ gap: 10,
228
+ marginBottom: 10,
229
+ },
230
+ autoBtn: {
231
+ display: "flex",
232
+ alignItems: "center",
233
+ gap: 5,
234
+ padding: "4px 10px",
235
+ borderRadius: 6,
236
+ border: "1px solid #27272A",
237
+ background: "transparent",
238
+ fontSize: 11,
239
+ fontWeight: 600,
240
+ cursor: "pointer",
241
+ transition: "border-color 0.15s, color 0.15s",
242
+ },
243
+ autoHint: {
244
+ fontSize: 11,
245
+ color: "#9a9bb0",
246
+ },
247
+ section: {
248
+ marginBottom: 8,
249
+ },
250
+ sectionLabel: {
251
+ fontSize: 9,
252
+ fontWeight: 700,
253
+ textTransform: "uppercase",
254
+ letterSpacing: "0.08em",
255
+ color: "#52525B",
256
+ marginBottom: 6,
257
+ },
258
+ cardRow: {
259
+ display: "flex",
260
+ gap: 8,
261
+ overflowX: "auto",
262
+ scrollbarWidth: "none",
263
+ paddingBottom: 2,
264
+ },
265
+ };
266
+
267
+ /* ------------------------------------------------------------------ */
268
+ /* Main FlowViewer component */
269
+ /* ------------------------------------------------------------------ */
270
+ export default function FlowViewer() {
271
+ const [nodes, setNodes] = useState([]);
272
+ const [edges, setEdges] = useState([]);
273
+ const [loading, setLoading] = useState(false);
274
+ const [error, setError] = useState("");
275
+
276
+ // Topology state
277
+ const [topologies, setTopologies] = useState([]);
278
+ const [activeTopology, setActiveTopology] = useState(null);
279
+ const [topologyMeta, setTopologyMeta] = useState(null);
280
+
281
+ // Auto-detection state
282
+ const [autoMode, setAutoMode] = useState(false);
283
+ const [autoResult, setAutoResult] = useState(null);
284
+ const [autoTestMessage, setAutoTestMessage] = useState("");
285
+
286
+ const initialLoadDone = useRef(false);
287
+
288
+ /* ---------- Load topology list on mount ---------- */
289
+ useEffect(() => {
290
+ (async () => {
291
+ try {
292
+ const [topoRes, prefRes] = await Promise.all([
293
+ fetch(apiUrl("/api/flow/topologies")),
294
+ fetch(apiUrl("/api/settings/topology")),
295
+ ]);
296
+ if (topoRes.ok) {
297
+ const data = await topoRes.json();
298
+ setTopologies(data);
299
+ }
300
+ if (prefRes.ok) {
301
+ const { topology } = await prefRes.json();
302
+ if (topology) {
303
+ setActiveTopology(topology);
304
+ }
305
+ }
306
+ } catch (e) {
307
+ console.warn("Failed to load topologies:", e);
308
+ }
309
+ initialLoadDone.current = true;
310
+ })();
311
+ }, []);
312
+
313
+ /* ---------- Load graph when topology changes ---------- */
314
+ const loadGraph = useCallback(async (topologyId) => {
315
+ setLoading(true);
316
+ setError("");
317
+ try {
318
+ const url = topologyId
319
+ ? `/api/flow/current?topology=${encodeURIComponent(topologyId)}`
320
+ : "/api/flow/current";
321
+ const res = await fetch(apiUrl(url));
322
+ const data = await res.json();
323
+ if (!res.ok) throw new Error(data.error || "Failed to load flow");
324
+
325
+ // Track topology metadata from response
326
+ if (data.topology_id) {
327
+ setTopologyMeta({
328
+ id: data.topology_id,
329
+ name: data.topology_name,
330
+ icon: data.topology_icon,
331
+ description: data.topology_description,
332
+ execution_style: data.execution_style,
333
+ agents_used: topologies.find((t) => t.id === data.topology_id)?.agents_used || [],
334
+ });
335
+ }
336
+
337
+ // Build ReactFlow nodes
338
+ const RFnodes = data.nodes.map((n, i) => {
339
+ const nodeType = n.type || "default";
340
+ const colour = colourFor(nodeType);
341
+ const d = n.data || {};
342
+
343
+ const label = d.label || n.label || n.id;
344
+ const description = d.description || n.description || "";
345
+ const model = d.model;
346
+ const mode = d.mode;
347
+
348
+ const pos = n.position || {
349
+ x: 50 + (i % 3) * 250,
350
+ y: 50 + Math.floor(i / 3) * 180,
351
+ };
352
+
353
+ return {
354
+ id: n.id,
355
+ data: {
356
+ label: (
357
+ <div style={{ textAlign: "center" }}>
358
+ <div style={{ fontWeight: 600, marginBottom: 2 }}>
359
+ {label}
360
+ </div>
361
+ {model && (
362
+ <div style={{ fontSize: 9, color: "#6c8cff", marginBottom: 2, fontFamily: "monospace" }}>
363
+ {model}
364
+ </div>
365
+ )}
366
+ {mode && (
367
+ <div
368
+ style={{
369
+ fontSize: 9,
370
+ color: mode === "read-only" ? "#4caf88" : mode === "git-ops" ? "#9c6cff" : "#ff7a3c",
371
+ marginBottom: 2,
372
+ }}
373
+ >
374
+ {mode}
375
+ </div>
376
+ )}
377
+ <div style={{ fontSize: 10, color: "#9a9bb0", maxWidth: 160, lineHeight: 1.3 }}>
378
+ {description}
379
+ </div>
380
+ </div>
381
+ ),
382
+ },
383
+ position: pos,
384
+ type: "default",
385
+ style: {
386
+ borderRadius: 12,
387
+ padding: "12px 16px",
388
+ border: `2px solid ${colour.border}`,
389
+ background: colour.bg,
390
+ color: "#f5f5f7",
391
+ fontSize: 13,
392
+ minWidth: 180,
393
+ maxWidth: 220,
394
+ },
395
+ };
396
+ });
397
+
398
+ // Build ReactFlow edges
399
+ const RFedges = data.edges.map((e) => ({
400
+ id: e.id,
401
+ source: e.source,
402
+ target: e.target,
403
+ label: e.label,
404
+ animated: e.animated !== false,
405
+ style: { stroke: "#7a7b8e", strokeWidth: 2 },
406
+ labelStyle: { fill: "#c3c5dd", fontSize: 11, fontWeight: 500 },
407
+ labelBgStyle: { fill: "#101117", fillOpacity: 0.9 },
408
+ ...(e.type === "bidirectional" && {
409
+ markerEnd: { type: "arrowclosed", color: "#7a7b8e" },
410
+ markerStart: { type: "arrowclosed", color: "#7a7b8e" },
411
+ animated: false,
412
+ style: { stroke: "#555670", strokeWidth: 1.5, strokeDasharray: "5 5" },
413
+ }),
414
+ }));
415
+
416
+ setNodes(RFnodes);
417
+ setEdges(RFedges);
418
+ } catch (e) {
419
+ console.error(e);
420
+ setError(e.message);
421
+ } finally {
422
+ setLoading(false);
423
+ }
424
+ }, [topologies]);
425
+
426
+ // Load graph whenever activeTopology changes
427
+ useEffect(() => {
428
+ loadGraph(activeTopology);
429
+ }, [activeTopology, loadGraph]);
430
+
431
+ /* ---------- Topology selection handler ---------- */
432
+ const handleTopologyChange = useCallback(
433
+ async (newTopologyId) => {
434
+ setActiveTopology(newTopologyId);
435
+ setAutoMode(false); // Manual selection disables auto
436
+ // Persist preference (fire-and-forget)
437
+ try {
438
+ await fetch(apiUrl("/api/settings/topology"), {
439
+ method: "POST",
440
+ headers: { "Content-Type": "application/json" },
441
+ body: JSON.stringify({ topology: newTopologyId }),
442
+ });
443
+ } catch (e) {
444
+ console.warn("Failed to save topology preference:", e);
445
+ }
446
+ },
447
+ []
448
+ );
449
+
450
+ /* ---------- Auto-detection ---------- */
451
+ const handleToggleAuto = useCallback(() => {
452
+ setAutoMode((prev) => !prev);
453
+ if (!autoMode) {
454
+ setAutoResult(null);
455
+ }
456
+ }, [autoMode]);
457
+
458
+ const handleAutoClassify = useCallback(
459
+ async (message) => {
460
+ if (!message.trim()) return;
461
+ try {
462
+ const res = await fetch(apiUrl("/api/flow/classify"), {
463
+ method: "POST",
464
+ headers: { "Content-Type": "application/json" },
465
+ body: JSON.stringify({ message }),
466
+ });
467
+ if (!res.ok) return;
468
+ const data = await res.json();
469
+ const recommendedId = data.recommended_topology;
470
+ const topo = topologies.find((t) => t.id === recommendedId);
471
+ setAutoResult({
472
+ id: recommendedId,
473
+ name: topo?.name || recommendedId,
474
+ icon: topo?.icon || "",
475
+ confidence: data.confidence,
476
+ alternatives: data.alternatives || [],
477
+ });
478
+ setActiveTopology(recommendedId);
479
+ } catch (e) {
480
+ console.warn("Auto-classify failed:", e);
481
+ }
482
+ },
483
+ [topologies]
484
+ );
485
+
486
+ // Debounced auto-classify when test message changes
487
+ useEffect(() => {
488
+ if (!autoMode || !autoTestMessage.trim()) return;
489
+ const t = setTimeout(() => handleAutoClassify(autoTestMessage), 500);
490
+ return () => clearTimeout(t);
491
+ }, [autoTestMessage, autoMode, handleAutoClassify]);
492
+
493
+ /* ---------- Render ---------- */
494
+ const activeStyleColor = STYLE_COLOURS[topologyMeta?.execution_style] || "#9a9bb0";
495
+
496
+ return (
497
+ <div className="flow-root">
498
+ {/* Header */}
499
+ <div className="flow-header">
500
+ <div>
501
+ <h1>Agent Workflow</h1>
502
+ <p>
503
+ Visual view of the multi-agent system that GitPilot uses to
504
+ plan and apply changes to your repositories.
505
+ </p>
506
+ </div>
507
+ <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
508
+ {topologyMeta && (
509
+ <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "#9a9bb0" }}>
510
+ <span style={{ fontSize: 18 }}>{topologyMeta.icon}</span>
511
+ <span style={{ fontWeight: 600, color: "#e0e1f0" }}>{topologyMeta.name}</span>
512
+ <span
513
+ style={{
514
+ padding: "2px 8px",
515
+ borderRadius: 6,
516
+ border: `1px solid ${activeStyleColor}40`,
517
+ color: activeStyleColor,
518
+ fontSize: 10,
519
+ fontWeight: 700,
520
+ textTransform: "uppercase",
521
+ }}
522
+ >
523
+ {STYLE_LABELS[topologyMeta.execution_style] || topologyMeta.execution_style}
524
+ </span>
525
+ <span>{topologyMeta.agents_used?.length || 0} agents</span>
526
+ </div>
527
+ )}
528
+ {loading && <span style={{ fontSize: 11, color: "#6c8cff" }}>Loading...</span>}
529
+ </div>
530
+ </div>
531
+
532
+ {/* Topology selector panel */}
533
+ {topologies.length > 0 && (
534
+ <TopologyPanel
535
+ topologies={topologies}
536
+ activeTopology={activeTopology}
537
+ autoMode={autoMode}
538
+ autoResult={autoResult}
539
+ onSelect={handleTopologyChange}
540
+ onToggleAuto={handleToggleAuto}
541
+ />
542
+ )}
543
+
544
+ {/* Auto-detection test input (shown when auto mode is on) */}
545
+ {autoMode && (
546
+ <div style={autoInputStyles.wrap}>
547
+ <div style={autoInputStyles.label}>
548
+ Test auto-detection: type a task description to see which topology is recommended
549
+ </div>
550
+ <input
551
+ type="text"
552
+ placeholder='e.g. "Fix the 403 error in auth middleware" or "Add a REST endpoint for users"'
553
+ value={autoTestMessage}
554
+ onChange={(e) => setAutoTestMessage(e.target.value)}
555
+ style={autoInputStyles.input}
556
+ />
557
+ {autoResult && autoResult.alternatives?.length > 0 && (
558
+ <div style={autoInputStyles.altRow}>
559
+ <span style={{ color: "#52525B", fontSize: 10 }}>Alternatives:</span>
560
+ {autoResult.alternatives.slice(0, 3).map((alt) => {
561
+ const altTopo = topologies.find((t) => t.id === alt.id);
562
+ return (
563
+ <button
564
+ key={alt.id}
565
+ type="button"
566
+ style={autoInputStyles.altBtn}
567
+ onClick={() => handleTopologyChange(alt.id)}
568
+ >
569
+ {altTopo?.icon} {altTopo?.name || alt.id}
570
+ <span style={{ opacity: 0.5 }}>
571
+ {alt.confidence != null ? ` ${Math.round(alt.confidence * 100)}%` : ""}
572
+ </span>
573
+ </button>
574
+ );
575
+ })}
576
+ </div>
577
+ )}
578
+ </div>
579
+ )}
580
+
581
+ {/* Description bar */}
582
+ {topologyMeta && topologyMeta.description && !autoMode && (
583
+ <div
584
+ style={{
585
+ padding: "8px 16px",
586
+ fontSize: 12,
587
+ color: "#9a9bb0",
588
+ background: "#0a0b12",
589
+ borderBottom: "1px solid #1e1f30",
590
+ }}
591
+ >
592
+ {topologyMeta.icon} {topologyMeta.description}
593
+ </div>
594
+ )}
595
+
596
+ {/* ReactFlow canvas */}
597
+ <div className="flow-canvas">
598
+ {error ? (
599
+ <div className="flow-error">
600
+ <div className="error-icon">!!!</div>
601
+ <div className="error-text">{error}</div>
602
+ </div>
603
+ ) : (
604
+ <ReactFlow nodes={nodes} edges={edges} fitView>
605
+ <Background color="#272832" gap={16} />
606
+ <MiniMap
607
+ nodeColor={(node) => {
608
+ const border = node.style?.border || "";
609
+ if (border.includes("#ff7a3c")) return "#ff7a3c";
610
+ if (border.includes("#6c8cff")) return "#6c8cff";
611
+ if (border.includes("#4caf88")) return "#4caf88";
612
+ if (border.includes("#9c6cff")) return "#9c6cff";
613
+ return "#3a3b4d";
614
+ }}
615
+ maskColor="rgba(0, 0, 0, 0.6)"
616
+ />
617
+ <Controls />
618
+ </ReactFlow>
619
+ )}
620
+ </div>
621
+ </div>
622
+ );
623
+ }
624
+
625
+ const autoInputStyles = {
626
+ wrap: {
627
+ padding: "8px 16px 10px",
628
+ borderBottom: "1px solid #1e1f30",
629
+ backgroundColor: "#0c0d14",
630
+ },
631
+ label: {
632
+ fontSize: 10,
633
+ color: "#71717A",
634
+ marginBottom: 6,
635
+ },
636
+ input: {
637
+ width: "100%",
638
+ padding: "8px 12px",
639
+ borderRadius: 6,
640
+ border: "1px solid #27272A",
641
+ background: "#08090e",
642
+ color: "#e0e1f0",
643
+ fontSize: 12,
644
+ fontFamily: "monospace",
645
+ outline: "none",
646
+ boxSizing: "border-box",
647
+ },
648
+ altRow: {
649
+ display: "flex",
650
+ alignItems: "center",
651
+ gap: 6,
652
+ marginTop: 6,
653
+ flexWrap: "wrap",
654
+ },
655
+ altBtn: {
656
+ padding: "2px 8px",
657
+ borderRadius: 4,
658
+ border: "1px solid #27272A",
659
+ background: "transparent",
660
+ color: "#9a9bb0",
661
+ fontSize: 10,
662
+ cursor: "pointer",
663
+ },
664
+ };
frontend/components/Footer.jsx ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from "react";
2
+
3
+ export default function Footer() {
4
+ return (
5
+ <footer className="gp-footer">
6
+ <div className="gp-footer-left">
7
+ <a
8
+ href="https://github.com/ruslanmv/gitpilot"
9
+ target="_blank"
10
+ rel="noopener noreferrer"
11
+ style={{
12
+ color: "inherit",
13
+ textDecoration: "none",
14
+ display: "flex",
15
+ alignItems: "center",
16
+ gap: "6px",
17
+ transition: "color 0.2s ease",
18
+ }}
19
+ onMouseOver={(e) => {
20
+ e.currentTarget.style.color = "#ff7a3c";
21
+ }}
22
+ onMouseOut={(e) => {
23
+ e.currentTarget.style.color = "#c3c5dd";
24
+ }}
25
+ >
26
+ ⭐ Star our GitHub project
27
+ </a>
28
+ </div>
29
+ <div className="gp-footer-right">
30
+ <span>© 2025 GitPilot</span>
31
+ <a
32
+ href="https://github.com/ruslanmv/gitpilot"
33
+ target="_blank"
34
+ rel="noopener noreferrer"
35
+ >
36
+ Docs
37
+ </a>
38
+ <a
39
+ href="https://github.com/ruslanmv/gitpilot"
40
+ target="_blank"
41
+ rel="noopener noreferrer"
42
+ >
43
+ GitHub
44
+ </a>
45
+ </div>
46
+ </footer>
47
+ );
48
+ }
frontend/components/LandingPage.jsx ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useRef, useState } from "react";
2
+ import "./landing.css";
3
+
4
+ // Premium GitPilot landing page — dark, minimal, animated.
5
+ // Public page only: "Get started" / "Sign in" route to the separate /auth page.
6
+
7
+ const GITHUB_URL = "https://github.com/ruslanmv/gitpilot";
8
+ const DOCS_URL = "https://ruslanmv.com/gitpilot/";
9
+
10
+ // --- tiny inline icons (no dependencies) ----------------------------------
11
+ const I = {
12
+ shield: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>,
13
+ target: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9" /><circle cx="12" cy="12" r="4" /></svg>,
14
+ code: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></svg>,
15
+ brain: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z" /><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z" /></svg>,
16
+ map: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21 3 6" /><line x1="9" y1="3" x2="9" y2="18" /><line x1="15" y1="6" x2="15" y2="21" /></svg>,
17
+ bolt: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>,
18
+ check2: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 11l3 3L22 4" /><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" /></svg>,
19
+ bot: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="8" width="16" height="11" rx="3" /><path d="M12 8V4" /><circle cx="9" cy="13" r="1" /><circle cx="15" cy="13" r="1" /></svg>,
20
+ home: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-8 9 8" /><path d="M5 10v10h14V10" /></svg>,
21
+ flow: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="6" cy="6" r="2" /><circle cx="18" cy="18" r="2" /><path d="M8 6h6a2 2 0 0 1 2 2v8" /></svg>,
22
+ gear: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" /><path d="M19 12a7 7 0 0 0-.1-1l2-1.5-2-3.5-2.3 1a7 7 0 0 0-1.7-1L14.5 2h-5l-.4 2.5a7 7 0 0 0-1.7 1l-2.3-1-2 3.5L5 11a7 7 0 0 0 0 2l-2 1.5 2 3.5 2.3-1a7 7 0 0 0 1.7 1l.4 2.5h5l.4-2.5a7 7 0 0 0 1.7-1l2.3 1 2-3.5-2-1.5a7 7 0 0 0 .1-1z" /></svg>,
23
+ copy: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V5a2 2 0 0 1 2-2h10" /></svg>,
24
+ ext: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 3h6v6" /><path d="M10 14 21 3" /><path d="M21 14v7H3V3h7" /></svg>,
25
+ lock: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="9" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></svg>,
26
+ arrowL: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>,
27
+ arrowR: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>,
28
+ ask: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.1 9a3 3 0 0 1 5.8 1c0 2-3 3-3 3" /><line x1="12" y1="17" x2="12" y2="17" /><circle cx="12" cy="12" r="10" /></svg>,
29
+ play: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3" /></svg>,
30
+ eye: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>,
31
+ git: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="18" r="3" /><circle cx="6" cy="6" r="3" /><path d="M6 9v6a6 6 0 0 0 6 6h3" /></svg>,
32
+ };
33
+
34
+ // The multi-agent pipeline — the heart of GitPilot, shown as a carousel.
35
+ const AGENTS = [
36
+ {
37
+ n: "01", name: "Explorer", role: "Context", ic: I.brain,
38
+ title: "It reads your repo before it writes a line.",
39
+ desc: "Explorer scans your full repository, git history, test suite, and dependencies — so every plan starts from real knowledge, not guesses.",
40
+ mock: (
41
+ <div className="gp-mock gp-mock-scan">
42
+ <div className="gp-mock-bar"><span className="gp-mdot r" /><span className="gp-mdot y" /><span className="gp-mdot g" /><b>explorer</b></div>
43
+ <ul>
44
+ <li><span className="ok">✓</span> Reading <em>src/auth/login.ts</em></li>
45
+ <li><span className="ok">✓</span> Indexed <em>142 files</em> · 18 modules</li>
46
+ <li><span className="ok">✓</span> Parsed <em>git log</em> — 1,204 commits</li>
47
+ <li><span className="run">⟳</span> Mapping <em>854 tests</em> to sources…</li>
48
+ </ul>
49
+ </div>
50
+ ),
51
+ },
52
+ {
53
+ n: "02", name: "Planner", role: "Strategy", ic: I.map,
54
+ title: "A step-by-step plan you approve first.",
55
+ desc: "Planner drafts a safe, reviewable plan with diffs and surfaces risks before any file is touched. Nothing runs until you say go.",
56
+ mock: (
57
+ <div className="gp-mock gp-mock-plan">
58
+ <div className="gp-mock-bar"><span className="gp-mdot r" /><span className="gp-mdot y" /><span className="gp-mdot g" /><b>plan · 3 steps</b></div>
59
+ <ol>
60
+ <li><b>1</b> Add <em>validateEmail()</em> to login.ts</li>
61
+ <li><b>2</b> Wire validation into the submit handler</li>
62
+ <li><b>3</b> Add 2 unit tests for edge cases</li>
63
+ </ol>
64
+ <div className="gp-mock-approve"><span>Approve &amp; Execute</span><span className="muted">Dismiss</span></div>
65
+ </div>
66
+ ),
67
+ },
68
+ {
69
+ n: "03", name: "Coder", role: "Execution", ic: I.bolt,
70
+ title: "It writes the code and runs your tests.",
71
+ desc: "Coder applies the plan, runs your test suite, and self-corrects on failure — iterating until everything passes. Diffs are shown before they're applied.",
72
+ mock: (
73
+ <div className="gp-mock gp-mock-diff">
74
+ <div className="gp-mock-bar"><span className="gp-mdot r" /><span className="gp-mdot y" /><span className="gp-mdot g" /><b>login.ts</b></div>
75
+ <pre>
76
+ <span className="add">+ if (!validateEmail(email)) {"{"}</span>
77
+ <span className="add">+ return error("Enter a valid email");</span>
78
+ <span className="add">+ {"}"}</span>
79
+ <span className="ctx"> await signIn(email, password);</span>
80
+ </pre>
81
+ <div className="gp-mock-test"><span className="ok">✓</span> npm test — <b>3 passed</b></div>
82
+ </div>
83
+ ),
84
+ },
85
+ {
86
+ n: "04", name: "Reviewer", role: "Quality", ic: I.check2,
87
+ title: "It reviews the work and ships it.",
88
+ desc: "Reviewer validates the output, re-runs the suite, and drafts your commit message and pull-request summary — ready for you to merge.",
89
+ mock: (
90
+ <div className="gp-mock gp-mock-pr">
91
+ <div className="gp-mock-bar"><span className="gp-mdot r" /><span className="gp-mdot y" /><span className="gp-mdot g" /><b>pull request</b></div>
92
+ <div className="gp-pr-title">feat(auth): validate email on login</div>
93
+ <ul>
94
+ <li><span className="ok">✓</span> All 854 tests passing</li>
95
+ <li><span className="ok">✓</span> Commit message drafted</li>
96
+ <li><span className="ok">✓</span> PR summary ready to merge</li>
97
+ </ul>
98
+ </div>
99
+ ),
100
+ },
101
+ ];
102
+
103
+ const MODES = [
104
+ { ic: I.ask, t: "Ask", tag: "Default", d: "Approve every dangerous action. You see the diff and click Allow or Deny before anything is written." },
105
+ { ic: I.play, t: "Auto", tag: "Fastest", d: "Trust the plan and let every tool run automatically — no prompts. Best for experienced users." },
106
+ { ic: I.eye, t: "Plan", tag: "Read-only", d: "Generate and display the full plan with diffs, but block all file writes and commands." },
107
+ ];
108
+
109
+ const STEPS = [
110
+ { t: "Connect a repository", d: "Authorize GitPilot securely with GitHub device flow — or run fully local with Ollama." },
111
+ { t: "Describe the task", d: "Ask in plain language. Explorer and Planner turn it into a reviewable plan." },
112
+ { t: "Approve & ship", d: "Coder writes and tests the change; Reviewer drafts the commit and PR. You stay in control." },
113
+ ];
114
+
115
+ // Reveal-on-scroll wrapper (IntersectionObserver, no dependency).
116
+ function Reveal({ children, className = "", style, delay = 0 }) {
117
+ const ref = useRef(null);
118
+ const [shown, setShown] = useState(false);
119
+ useEffect(() => {
120
+ const el = ref.current;
121
+ if (!el) return undefined;
122
+ if (typeof IntersectionObserver === "undefined") { setShown(true); return undefined; }
123
+ const io = new IntersectionObserver(
124
+ ([e]) => { if (e.isIntersecting) { setShown(true); io.disconnect(); } },
125
+ { threshold: 0.12 }
126
+ );
127
+ io.observe(el);
128
+ return () => io.disconnect();
129
+ }, []);
130
+ return (
131
+ <div ref={ref} style={{ ...style, transitionDelay: `${delay}ms` }} className={`gp-reveal ${shown ? "in" : ""} ${className}`}>
132
+ {children}
133
+ </div>
134
+ );
135
+ }
136
+
137
+ function AgentCarousel() {
138
+ const [active, setActive] = useState(0);
139
+ const [paused, setPaused] = useState(false);
140
+ const n = AGENTS.length;
141
+
142
+ useEffect(() => {
143
+ if (paused) return undefined;
144
+ const t = setInterval(() => setActive((a) => (a + 1) % n), 5200);
145
+ return () => clearInterval(t);
146
+ }, [paused, n]);
147
+
148
+ const go = (i) => setActive(((i % n) + n) % n);
149
+ const cur = AGENTS[active];
150
+
151
+ return (
152
+ <div
153
+ className="gp-car"
154
+ onMouseEnter={() => setPaused(true)}
155
+ onMouseLeave={() => setPaused(false)}
156
+ >
157
+ <div className="gp-car-head">
158
+ <div className="gp-car-badge">{cur.ic}<span>Agent {cur.n} · {cur.role}</span></div>
159
+ <div className="gp-car-ctrls">
160
+ <button type="button" aria-label="Previous agent" onClick={() => go(active - 1)}>{I.arrowL}</button>
161
+ <span className="gp-car-count">{cur.n} / {String(n).padStart(2, "0")}</span>
162
+ <button type="button" aria-label="Next agent" onClick={() => go(active + 1)}>{I.arrowR}</button>
163
+ </div>
164
+ </div>
165
+
166
+ <div className="gp-car-view">
167
+ <div className="gp-car-track" style={{ transform: `translateX(-${active * 100}%)` }}>
168
+ {AGENTS.map((a) => (
169
+ <div className="gp-slide" key={a.name} aria-hidden={a.name !== cur.name}>
170
+ <div className="gp-slide-text">
171
+ <div className="gp-slide-name">{a.name}</div>
172
+ <h3>{a.title}</h3>
173
+ <p>{a.desc}</p>
174
+ </div>
175
+ <div className="gp-slide-visual">{a.mock}</div>
176
+ </div>
177
+ ))}
178
+ </div>
179
+ </div>
180
+
181
+ <div className="gp-car-dots" role="tablist">
182
+ {AGENTS.map((a, i) => (
183
+ <button
184
+ type="button"
185
+ key={a.name}
186
+ className={i === active ? "on" : ""}
187
+ aria-label={`Show ${a.name}`}
188
+ aria-selected={i === active}
189
+ onClick={() => go(i)}
190
+ />
191
+ ))}
192
+ </div>
193
+ </div>
194
+ );
195
+ }
196
+
197
+ // Real GitPilot app screens, shown as a carousel inside the hero preview box.
198
+ const SCREENS = [
199
+ {
200
+ key: "workspace", label: "Workspace",
201
+ body: (
202
+ <>
203
+ <div className="gp-ps-head"><b>Connect a repository</b><span className="gp-ps-pill ok">Write access ✓</span></div>
204
+ <div className="gp-ps-rows">
205
+ <div className="gp-ps-row on"><span className="gp-rdot" /> ai-doctor/medical-data <em>main · 26 files</em></div>
206
+ <div className="gp-ps-row"><span className="gp-rdot off" /> gitpilot</div>
207
+ <div className="gp-ps-row"><span className="gp-rdot off" /> signalforge</div>
208
+ <div className="gp-ps-row"><span className="gp-rdot off" /> matrix-builder</div>
209
+ </div>
210
+ <div className="gp-ps-cta">{I.git} Connect with GitHub</div>
211
+ </>
212
+ ),
213
+ },
214
+ {
215
+ key: "agents", label: "Agent workflow",
216
+ body: (
217
+ <div className="gp-flowmini">
218
+ <div className="gp-fnode top">User request</div>
219
+ <span className="gp-fline" />
220
+ <div className="gp-fnode router">Task Router</div>
221
+ <span className="gp-fline" />
222
+ <div className="gp-frow">
223
+ <span>Explorer</span><span>Planner</span><span>Coder</span><span>Reviewer</span>
224
+ </div>
225
+ </div>
226
+ ),
227
+ },
228
+ {
229
+ key: "plan", label: "Plan & approve",
230
+ body: (
231
+ <>
232
+ <div className="gp-ps-head"><b>Action plan</b><span className="gp-ps-meta2">Replace README.md</span></div>
233
+ <div className="gp-plan-chips"><span className="c create">1 create</span><span className="c modify">1 modify</span><span className="c delete">1 delete</span></div>
234
+ <div className="gp-plan-steps">
235
+ <div><span className="k">STEP 1</span> Delete existing README.md</div>
236
+ <div><span className="k">STEP 2</span> Rename README.md.new → README.md</div>
237
+ </div>
238
+ <div className="gp-ps-approve"><span>Approve &amp; execute</span><em>Dismiss</em></div>
239
+ </>
240
+ ),
241
+ },
242
+ {
243
+ key: "exec", label: "Execution",
244
+ body: (
245
+ <>
246
+ <div className="gp-ps-head"><b>Execution log</b></div>
247
+ <ul className="gp-exec">
248
+ <li><span className="ok">✓</span> Deleted <em>README.md</em></li>
249
+ <li><span className="ok">✓</span> Created <em>README.md</em></li>
250
+ <li><span className="ok">✓</span> Ran <em>npm test</em> — 3 passed</li>
251
+ <li><span className="run">⟳</span> Re-checking suite…</li>
252
+ </ul>
253
+ <div className="gp-ps-note ok">Successfully executed 2 steps</div>
254
+ </>
255
+ ),
256
+ },
257
+ {
258
+ key: "review", label: "Review & PR",
259
+ body: (
260
+ <>
261
+ <div className="gp-ps-head"><b>Pull request</b><span className="gp-ps-pill ok">Ready</span></div>
262
+ <div className="gp-pr-name">feat(auth): validate email on login</div>
263
+ <ul className="gp-exec">
264
+ <li><span className="ok">✓</span> All 854 tests passing</li>
265
+ <li><span className="ok">✓</span> Commit message drafted</li>
266
+ <li><span className="ok">✓</span> PR summary ready to merge</li>
267
+ </ul>
268
+ </>
269
+ ),
270
+ },
271
+ ];
272
+
273
+ // Animated carousel that lives inside the existing hero preview window.
274
+ function PreviewCarousel() {
275
+ const [i, setI] = useState(0);
276
+ const [paused, setPaused] = useState(false);
277
+ const n = SCREENS.length;
278
+
279
+ useEffect(() => {
280
+ if (paused) return undefined;
281
+ const t = setInterval(() => setI((p) => (p + 1) % n), 4200);
282
+ return () => clearInterval(t);
283
+ }, [paused, n]);
284
+
285
+ const go = (k) => setI(((k % n) + n) % n);
286
+
287
+ return (
288
+ <div
289
+ className="gp-preview gp-float"
290
+ onMouseEnter={() => setPaused(true)}
291
+ onMouseLeave={() => setPaused(false)}
292
+ >
293
+ <div className="gp-titlebar">
294
+ <i /><i /><i />
295
+ <span className="gp-tb-label">{SCREENS[i].label}</span>
296
+ </div>
297
+
298
+ <div className="gp-pcar">
299
+ <div className="gp-pcar-track" style={{ transform: `translateX(-${i * 100}%)` }}>
300
+ {SCREENS.map((s) => (
301
+ <div className="gp-pscreen" key={s.key} aria-hidden={s.key !== SCREENS[i].key}>
302
+ <div className="gp-ps-body">{s.body}</div>
303
+ </div>
304
+ ))}
305
+ </div>
306
+ <button type="button" className="gp-pcar-arrow l" aria-label="Previous screen" onClick={() => go(i - 1)}>{I.arrowL}</button>
307
+ <button type="button" className="gp-pcar-arrow r" aria-label="Next screen" onClick={() => go(i + 1)}>{I.arrowR}</button>
308
+ </div>
309
+
310
+ <div className="gp-pcar-foot">
311
+ <div className="gp-pcar-dots">
312
+ {SCREENS.map((s, k) => (
313
+ <button type="button" key={s.key} className={k === i ? "on" : ""} aria-label={s.label} onClick={() => go(k)} />
314
+ ))}
315
+ </div>
316
+ <div className="gp-pcar-prog"><span style={{ width: `${((i + 1) / n) * 100}%` }} /></div>
317
+ </div>
318
+ </div>
319
+ );
320
+ }
321
+
322
+ export default function LandingPage() {
323
+ // The app shell sets `body { overflow: hidden }` for the fixed workspace
324
+ // layout, which freezes mouse-wheel scrolling on this public page. Allow the
325
+ // page to scroll while the landing is mounted; restore on unmount.
326
+ useEffect(() => {
327
+ const prevBody = document.body.style.overflow;
328
+ const prevHtml = document.documentElement.style.overflow;
329
+ document.body.style.overflow = "auto";
330
+ document.documentElement.style.overflow = "auto";
331
+ return () => {
332
+ document.body.style.overflow = prevBody;
333
+ document.documentElement.style.overflow = prevHtml;
334
+ };
335
+ }, []);
336
+
337
+ return (
338
+ <div className="gp-landing">
339
+ {/* sticky top bar — keeps brand/home reachable from anywhere on the page */}
340
+ <header className="gp-topbar">
341
+ <nav className="gp-nav gp-wrap">
342
+ <a className="gp-brand" href="/">
343
+ <span className="gp-logo">GP</span>
344
+ <span>
345
+ <span className="gp-brand-name">GitPilot</span>
346
+ <br />
347
+ <span className="gp-brand-sub">Multi-agent coding assistant</span>
348
+ </span>
349
+ </a>
350
+ <div className="gp-nav-links">
351
+ <a href="#agents">Agents</a>
352
+ <a href="#modes">Control</a>
353
+ <a href={DOCS_URL} target="_blank" rel="noreferrer">Docs</a>
354
+ <a href={GITHUB_URL} target="_blank" rel="noreferrer">GitHub ↗</a>
355
+ </div>
356
+ <div className="gp-nav-right">
357
+ <a className="gp-signin" href="/auth?mode=signin">Sign in</a>
358
+ <a className="gp-btn gp-btn-primary" href="/auth?mode=signup">Get started</a>
359
+ </div>
360
+ </nav>
361
+ </header>
362
+
363
+ <div className="gp-wrap">
364
+ {/* above-the-fold: hero + capabilities occupy one viewport */}
365
+ <div className="gp-fold">
366
+ {/* hero — vertically centered in the remaining fold space */}
367
+ <div className="gp-fold-main">
368
+ <header className="gp-hero">
369
+ <div className="gp-hero-copy">
370
+ <span className="gp-badge gp-up"><span className="dot">✦</span> The first open-source multi-agent coding assistant</span>
371
+ <h1 className="gp-h1 gp-up d1">Your AI engineering<br />team, <span className="accent">under your control.</span></h1>
372
+ <p className="gp-sub gp-up d2">
373
+ Specialized agents — in configurable topologies — read your repo,
374
+ plan changes you approve, write code, and run your tests.
375
+ On any LLM. Open source.
376
+ </p>
377
+ <div className="gp-cta gp-up d3">
378
+ <a className="gp-btn gp-btn-primary gp-btn-sm" href="/auth?mode=signup">Get started — free</a>
379
+ <a className="gp-btn gp-btn-ghost gp-btn-sm" href={GITHUB_URL} target="_blank" rel="noreferrer">{I.git} Star on GitHub</a>
380
+ </div>
381
+ <div className="gp-trust gp-up d4">
382
+ <span>{I.shield} Apache 2.0 open source</span>
383
+ <span>{I.check2} 854 tests passing</span>
384
+ <span>{I.lock} Private by default</span>
385
+ </div>
386
+ </div>
387
+
388
+ {/* product preview — animated carousel of real GitPilot app screens */}
389
+ <PreviewCarousel />
390
+ </header>
391
+ </div>
392
+
393
+ {/* capabilities — enterprise value prop, no brand names */}
394
+ <Reveal className="gp-llm-sec">
395
+ <div className="gp-llm-title">Any LLM, Zero Lock-In</div>
396
+ <div className="gp-llm-caps">
397
+ Proprietary Cloud APIs&nbsp;&nbsp;•&nbsp;&nbsp;Local &amp; Private Models&nbsp;&nbsp;•&nbsp;&nbsp;Open-Source Weights&nbsp;&nbsp;•&nbsp;&nbsp;Custom Deployments
398
+ </div>
399
+ </Reveal>
400
+ </div>{/* /gp-fold */}
401
+
402
+ {/* agent carousel */}
403
+ <section id="agents" className="gp-section gp-after-fold">
404
+ <Reveal className="gp-sec-head">
405
+ <div className="gp-eyebrow">Multi-agent topologies</div>
406
+ <h2>One request. A whole engineering team.</h2>
407
+ <p>Most AI tools are a single model behind a chat box. GitPilot orchestrates configurable agent topologies — routing dispatch, ReAct loops with subagents, and task pipelines — so specialized roles explore, plan, build, and review your code.</p>
408
+ </Reveal>
409
+ <Reveal delay={80}><AgentCarousel /></Reveal>
410
+ </section>
411
+
412
+ {/* execution modes */}
413
+ <section id="modes" className="gp-section">
414
+ <Reveal className="gp-sec-head">
415
+ <div className="gp-eyebrow">You hold the controls</div>
416
+ <h2>Three modes. You decide how far it goes.</h2>
417
+ <p>Switch per session. Diffs are shown before they're applied; tests run before anything is committed. No surprises.</p>
418
+ </Reveal>
419
+ <div className="gp-modes">
420
+ {MODES.map((m, i) => (
421
+ <Reveal key={m.t} delay={i * 90}>
422
+ <div className="gp-mode">
423
+ <div className="gp-mode-top">
424
+ <div className="ic">{m.ic}</div>
425
+ <span className="gp-mode-tag">{m.tag}</span>
426
+ </div>
427
+ <h3>{m.t}</h3>
428
+ <p>{m.d}</p>
429
+ </div>
430
+ </Reveal>
431
+ ))}
432
+ </div>
433
+ </section>
434
+
435
+ {/* how it works */}
436
+ <section className="gp-section gp-how">
437
+ <Reveal className="gp-sec-head"><h2>From idea to pull request</h2></Reveal>
438
+ <div className="gp-steps">
439
+ {STEPS.map((s, i) => (
440
+ <Reveal key={s.t} delay={i * 90}>
441
+ <div className="gp-step">
442
+ <div className="n">{i + 1}</div>
443
+ <h4>{s.t}</h4>
444
+ <p>{s.d}</p>
445
+ </div>
446
+ </Reveal>
447
+ ))}
448
+ </div>
449
+ </section>
450
+
451
+ {/* CTA band */}
452
+ <Reveal className="gp-cta-band">
453
+ <h2>Ship better code, without giving up control.</h2>
454
+ <p>Start free and local with Ollama, or bring your own OpenAI, Claude, or watsonx key.</p>
455
+ <div className="gp-cta">
456
+ <a className="gp-btn gp-btn-primary" href="/auth?mode=signup">Get started — free</a>
457
+ <a className="gp-btn gp-btn-ghost" href={DOCS_URL} target="_blank" rel="noreferrer">View docs</a>
458
+ </div>
459
+ </Reveal>
460
+
461
+ {/* footer */}
462
+ <footer className="gp-foot">
463
+ <div className="lock">{I.lock} Your code stays private. Your workflow stays in control.</div>
464
+ <div className="gp-foot-links">
465
+ <a href={DOCS_URL} target="_blank" rel="noreferrer">Docs</a>
466
+ <a href={GITHUB_URL} target="_blank" rel="noreferrer">GitHub</a>
467
+ <a href="/auth?mode=signin">Sign in</a>
468
+ </div>
469
+ <div className="gp-foot-copy">© {new Date().getFullYear()} GitPilot · Apache 2.0 · Made by ruslanmv</div>
470
+ </footer>
471
+ </div>
472
+ </div>
473
+ );
474
+ }
frontend/components/LlmSettings.jsx ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useState } from "react";
2
+ import { testProvider, apiUrl } from "../utils/api";
3
+
4
+ const PROVIDERS = ["ollabridge", "openai", "claude", "watsonx", "ollama"];
5
+
6
+ const PROVIDER_LABELS = {
7
+ ollabridge: "OllaBridge Cloud",
8
+ openai: "OpenAI",
9
+ claude: "Claude",
10
+ watsonx: "Watsonx",
11
+ ollama: "Ollama",
12
+ };
13
+
14
+ const AUTH_MODES = [
15
+ { id: "device", label: "Device Pairing", icon: "📱" },
16
+ { id: "apikey", label: "API Key", icon: "🔑" },
17
+ { id: "local", label: "Local Trust", icon: "🏠" },
18
+ ];
19
+
20
+ function LoadingState({ loadingMessage, loadingSlow, onRetry }) {
21
+ return (
22
+ <div className="settings-loading-shell">
23
+ <div className="settings-loading-card">
24
+ <div className="settings-loading-spinner" aria-hidden="true" />
25
+ <h1>AI Providers</h1>
26
+ <div className="settings-loading-subtitle">Admin / LLM Settings</div>
27
+ <p className="settings-loading-text">{loadingMessage}</p>
28
+
29
+ {loadingSlow && (
30
+ <div className="settings-loading-slow">
31
+ <p>
32
+ This is taking longer than expected. The backend may still be
33
+ starting or the settings endpoint may be slow.
34
+ </p>
35
+ <button
36
+ type="button"
37
+ className="settings-secondary-btn"
38
+ onClick={onRetry}
39
+ >
40
+ Retry
41
+ </button>
42
+ </div>
43
+ )}
44
+ </div>
45
+ </div>
46
+ );
47
+ }
48
+
49
+ export default function LlmSettings() {
50
+ const [settings, setSettings] = useState(null);
51
+ const [initialLoading, setInitialLoading] = useState(true);
52
+ const [loadingSlow, setLoadingSlow] = useState(false);
53
+
54
+ const [saving, setSaving] = useState(false);
55
+ const [error, setError] = useState("");
56
+ const [savedMsg, setSavedMsg] = useState("");
57
+
58
+ const [modelsByProvider, setModelsByProvider] = useState({});
59
+ const [modelsError, setModelsError] = useState("");
60
+ const [loadingModelsFor, setLoadingModelsFor] = useState("");
61
+
62
+ const [testResult, setTestResult] = useState(null);
63
+ const [testing, setTesting] = useState(false);
64
+
65
+ const [authMode, setAuthMode] = useState("local");
66
+ const [pairCode, setPairCode] = useState("");
67
+ const [pairing, setPairing] = useState(false);
68
+ const [pairResult, setPairResult] = useState(null);
69
+
70
+ const loadingMessage = useMemo(() => {
71
+ if (loadingSlow) {
72
+ return "Still loading provider configuration…";
73
+ }
74
+ return "Loading current configuration…";
75
+ }, [loadingSlow]);
76
+
77
+ const loadSettings = async () => {
78
+ setInitialLoading(true);
79
+ setError("");
80
+ setLoadingSlow(false);
81
+
82
+ let slowTimer;
83
+ try {
84
+ slowTimer = window.setTimeout(() => {
85
+ setLoadingSlow(true);
86
+ }, 1500);
87
+
88
+ const res = await fetch(apiUrl("/api/settings"));
89
+ const data = await res.json();
90
+
91
+ if (!res.ok) {
92
+ throw new Error(data.error || "Failed to load settings");
93
+ }
94
+
95
+ setSettings(data);
96
+ } catch (e) {
97
+ console.error(e);
98
+ setError(e.message || "Failed to load settings");
99
+ } finally {
100
+ window.clearTimeout(slowTimer);
101
+ setInitialLoading(false);
102
+ }
103
+ };
104
+
105
+ useEffect(() => {
106
+ loadSettings();
107
+ }, []);
108
+
109
+ const updateField = (section, field, value) => {
110
+ setSettings((prev) => ({
111
+ ...prev,
112
+ [section]: {
113
+ ...prev[section],
114
+ [field]: value,
115
+ },
116
+ }));
117
+ };
118
+
119
+ const handleSave = async () => {
120
+ setSaving(true);
121
+ setError("");
122
+ setSavedMsg("");
123
+
124
+ try {
125
+ const res = await fetch(apiUrl("/api/settings/llm"), {
126
+ method: "PUT",
127
+ headers: { "Content-Type": "application/json" },
128
+ body: JSON.stringify(settings),
129
+ });
130
+
131
+ const data = await res.json();
132
+ if (!res.ok) throw new Error(data.error || "Failed to save settings");
133
+
134
+ setSettings(data);
135
+ setSavedMsg("Settings saved successfully!");
136
+ setTimeout(() => setSavedMsg(""), 3000);
137
+ } catch (e) {
138
+ console.error(e);
139
+ setError(e.message || "Failed to save settings");
140
+ } finally {
141
+ setSaving(false);
142
+ }
143
+ };
144
+
145
+ const loadModelsForProvider = async (provider) => {
146
+ setModelsError("");
147
+ setLoadingModelsFor(provider);
148
+
149
+ try {
150
+ const res = await fetch(apiUrl(`/api/settings/models?provider=${provider}`));
151
+ const data = await res.json();
152
+
153
+ if (!res.ok || data.error) {
154
+ throw new Error(data.error || "Failed to load models");
155
+ }
156
+
157
+ setModelsByProvider((prev) => ({
158
+ ...prev,
159
+ [provider]: data.models || [],
160
+ }));
161
+ } catch (e) {
162
+ console.error(e);
163
+ setModelsError(e.message || "Failed to load models");
164
+ } finally {
165
+ setLoadingModelsFor("");
166
+ }
167
+ };
168
+
169
+ const handlePair = async () => {
170
+ if (!pairCode.trim()) return;
171
+
172
+ setPairing(true);
173
+ setPairResult(null);
174
+
175
+ try {
176
+ const baseUrl =
177
+ settings?.ollabridge?.base_url || "https://ruslanmv-ollabridge.hf.space";
178
+
179
+ const res = await fetch(apiUrl("/api/ollabridge/pair"), {
180
+ method: "POST",
181
+ headers: { "Content-Type": "application/json" },
182
+ body: JSON.stringify({ base_url: baseUrl, code: pairCode.trim() }),
183
+ });
184
+
185
+ const data = await res.json();
186
+
187
+ if (data.success) {
188
+ setPairResult({ ok: true, message: "Paired successfully!" });
189
+ if (data.token) {
190
+ updateField("ollabridge", "api_key", data.token);
191
+ }
192
+ } else {
193
+ setPairResult({
194
+ ok: false,
195
+ message: data.error || "Pairing failed",
196
+ });
197
+ }
198
+ } catch (e) {
199
+ setPairResult({ ok: false, message: e.message || "Pairing failed" });
200
+ } finally {
201
+ setPairing(false);
202
+ }
203
+ };
204
+
205
+ const handleTestConnection = async () => {
206
+ setTesting(true);
207
+ setTestResult(null);
208
+
209
+ try {
210
+ const activeProvider = settings?.provider || "ollama";
211
+ const config = { provider: activeProvider };
212
+
213
+ if (activeProvider === "openai" && settings?.openai) {
214
+ config.openai = {
215
+ api_key: settings.openai.api_key,
216
+ base_url: settings.openai.base_url,
217
+ model: settings.openai.model,
218
+ };
219
+ } else if (activeProvider === "claude" && settings?.claude) {
220
+ config.claude = {
221
+ api_key: settings.claude.api_key,
222
+ base_url: settings.claude.base_url,
223
+ model: settings.claude.model,
224
+ };
225
+ } else if (activeProvider === "watsonx" && settings?.watsonx) {
226
+ config.watsonx = {
227
+ api_key: settings.watsonx.api_key,
228
+ project_id: settings.watsonx.project_id,
229
+ base_url: settings.watsonx.base_url,
230
+ model_id: settings.watsonx.model_id,
231
+ };
232
+ } else if (activeProvider === "ollama" && settings?.ollama) {
233
+ config.ollama = {
234
+ base_url: settings.ollama.base_url,
235
+ model: settings.ollama.model,
236
+ };
237
+ } else if (activeProvider === "ollabridge" && settings?.ollabridge) {
238
+ config.ollabridge = {
239
+ base_url: settings.ollabridge.base_url,
240
+ model: settings.ollabridge.model,
241
+ api_key: settings.ollabridge.api_key,
242
+ };
243
+ }
244
+
245
+ const result = await testProvider(config);
246
+ setTestResult(result);
247
+ } catch (err) {
248
+ setTestResult({
249
+ health: "error",
250
+ warning: err.message || "Test failed",
251
+ });
252
+ } finally {
253
+ setTesting(false);
254
+ }
255
+ };
256
+
257
+ if (initialLoading) {
258
+ return (
259
+ <LoadingState
260
+ loadingMessage={loadingMessage}
261
+ loadingSlow={loadingSlow}
262
+ onRetry={loadSettings}
263
+ />
264
+ );
265
+ }
266
+
267
+ if (!settings) {
268
+ return (
269
+ <div className="settings-root">
270
+ <div className="settings-inline-error-card">
271
+ <h1>AI Providers</h1>
272
+ <div className="settings-loading-subtitle">Admin / LLM Settings</div>
273
+ <p className="settings-error-text">
274
+ {error || "Unable to load current configuration."}
275
+ </p>
276
+ <button
277
+ type="button"
278
+ className="settings-secondary-btn"
279
+ onClick={loadSettings}
280
+ >
281
+ Retry
282
+ </button>
283
+ </div>
284
+ </div>
285
+ );
286
+ }
287
+
288
+ const { provider } = settings;
289
+ const availableModels = modelsByProvider[provider] || [];
290
+
291
+ return (
292
+ <div className="settings-root">
293
+ <h1>AI Providers</h1>
294
+ <p className="settings-muted">
295
+ Choose which LLM provider GitPilot should use for planning and agent
296
+ workflows. Provider settings are stored on the server.
297
+ </p>
298
+
299
+ <div className="settings-upsell">
300
+ <div className="settings-upsell-icon" aria-hidden="true">✨</div>
301
+ <div className="settings-upsell-body">
302
+ <div className="settings-upsell-title">
303
+ {provider === "ollabridge"
304
+ ? "You're on OllaBridge Cloud — free, no setup required."
305
+ : "Tip: OllaBridge Cloud is free and needs no setup."}
306
+ </div>
307
+ <div className="settings-upsell-text">
308
+ Perfect for getting started. Need sharper results? Switch to a premium
309
+ provider (OpenAI, Claude, Watsonx) below using your own API key — or run
310
+ your own models on your machine and connect them with{" "}
311
+ <a
312
+ href="https://huggingface.co/spaces/ruslanmv/ollabridge"
313
+ target="_blank"
314
+ rel="noopener noreferrer"
315
+ >
316
+ OllaBridge ↗
317
+ </a>
318
+ .
319
+ </div>
320
+ </div>
321
+ </div>
322
+
323
+ {error && <div className="settings-error-banner">{error}</div>}
324
+ {savedMsg && <div className="settings-success-banner">{savedMsg}</div>}
325
+
326
+ <div className="settings-card">
327
+ <label className="settings-label">Active provider</label>
328
+ <div className="settings-provider-tabs">
329
+ {PROVIDERS.map((p) => (
330
+ <button
331
+ key={p}
332
+ type="button"
333
+ className={
334
+ "settings-provider-tab" +
335
+ (provider === p ? " settings-provider-tab-active" : "")
336
+ }
337
+ onClick={() => setSettings((prev) => ({ ...prev, provider: p }))}
338
+ >
339
+ {PROVIDER_LABELS[p] || p}
340
+ </button>
341
+ ))}
342
+ </div>
343
+ </div>
344
+
345
+ {provider === "ollabridge" && (
346
+ <div className="settings-card">
347
+ <div className="settings-title">OllaBridge Cloud Configuration</div>
348
+ <div className="settings-hint" style={{ marginBottom: 12 }}>
349
+ Connect to OllaBridge Cloud or any OllaBridge instance for LLM
350
+ inference. No API key required for public endpoints.
351
+ </div>
352
+
353
+ <label className="settings-label">Authentication Mode</label>
354
+ <div className="ob-auth-tabs">
355
+ {AUTH_MODES.map((m) => (
356
+ <button
357
+ key={m.id}
358
+ type="button"
359
+ className={
360
+ "ob-auth-tab" +
361
+ (authMode === m.id ? " ob-auth-tab-active" : "")
362
+ }
363
+ onClick={() => setAuthMode(m.id)}
364
+ >
365
+ <span className="ob-auth-tab-icon">{m.icon}</span>
366
+ <span>{m.label}</span>
367
+ </button>
368
+ ))}
369
+ </div>
370
+
371
+ {authMode === "device" && (
372
+ <div className="ob-auth-panel">
373
+ <div className="ob-auth-desc">
374
+ Enter the pairing code from your OllaBridge console and click
375
+ Pair.
376
+ </div>
377
+ <div className="ob-pair-row">
378
+ <input
379
+ className="settings-input ob-pair-input"
380
+ type="text"
381
+ maxLength={9}
382
+ placeholder="ABCD-1234"
383
+ value={pairCode}
384
+ onChange={(e) => setPairCode(e.target.value.toUpperCase())}
385
+ onKeyDown={(e) => e.key === "Enter" && handlePair()}
386
+ />
387
+ <button
388
+ type="button"
389
+ className="ob-pair-btn"
390
+ onClick={handlePair}
391
+ disabled={pairing || !pairCode.trim()}
392
+ >
393
+ {pairing ? "Pairing…" : "Pair"}
394
+ </button>
395
+ </div>
396
+ {pairResult && (
397
+ <div
398
+ className={
399
+ pairResult.ok ? "settings-success-banner" : "settings-error-banner"
400
+ }
401
+ >
402
+ {pairResult.message}
403
+ </div>
404
+ )}
405
+ </div>
406
+ )}
407
+
408
+ <label className="settings-label">Base URL</label>
409
+ <input
410
+ className="settings-input"
411
+ value={settings.ollabridge?.base_url || ""}
412
+ onChange={(e) =>
413
+ updateField("ollabridge", "base_url", e.target.value)
414
+ }
415
+ placeholder="https://your-ollabridge-endpoint"
416
+ />
417
+
418
+ {(authMode === "apikey" || authMode === "local") && (
419
+ <>
420
+ <label className="settings-label">API Key</label>
421
+ <input
422
+ className="settings-input"
423
+ type="password"
424
+ value={settings.ollabridge?.api_key || ""}
425
+ onChange={(e) =>
426
+ updateField("ollabridge", "api_key", e.target.value)
427
+ }
428
+ placeholder="Optional API key"
429
+ />
430
+ </>
431
+ )}
432
+
433
+ <label className="settings-label">Model</label>
434
+ <div className="settings-inline-row">
435
+ <input
436
+ className="settings-input"
437
+ value={settings.ollabridge?.model || ""}
438
+ onChange={(e) =>
439
+ updateField("ollabridge", "model", e.target.value)
440
+ }
441
+ placeholder="qwen2.5:1.5b"
442
+ />
443
+ <button
444
+ type="button"
445
+ className="settings-secondary-btn"
446
+ onClick={() => loadModelsForProvider("ollabridge")}
447
+ disabled={loadingModelsFor === "ollabridge"}
448
+ >
449
+ {loadingModelsFor === "ollabridge" ? "Loading…" : "Load Models"}
450
+ </button>
451
+ </div>
452
+ </div>
453
+ )}
454
+
455
+ {provider === "openai" && (
456
+ <div className="settings-card">
457
+ <div className="settings-title">OpenAI Configuration</div>
458
+
459
+ <label className="settings-label">API Key</label>
460
+ <input
461
+ className="settings-input"
462
+ type="password"
463
+ value={settings.openai?.api_key || ""}
464
+ onChange={(e) => updateField("openai", "api_key", e.target.value)}
465
+ placeholder="sk-..."
466
+ />
467
+
468
+ <label className="settings-label">Base URL</label>
469
+ <input
470
+ className="settings-input"
471
+ value={settings.openai?.base_url || ""}
472
+ onChange={(e) => updateField("openai", "base_url", e.target.value)}
473
+ placeholder="Optional custom base URL"
474
+ />
475
+
476
+ <label className="settings-label">Model</label>
477
+ <input
478
+ className="settings-input"
479
+ value={settings.openai?.model || ""}
480
+ onChange={(e) => updateField("openai", "model", e.target.value)}
481
+ placeholder="gpt-4o-mini"
482
+ />
483
+ </div>
484
+ )}
485
+
486
+ {provider === "claude" && (
487
+ <div className="settings-card">
488
+ <div className="settings-title">Claude Configuration</div>
489
+
490
+ <label className="settings-label">API Key</label>
491
+ <input
492
+ className="settings-input"
493
+ type="password"
494
+ value={settings.claude?.api_key || ""}
495
+ onChange={(e) => updateField("claude", "api_key", e.target.value)}
496
+ placeholder="Anthropic API key"
497
+ />
498
+
499
+ <label className="settings-label">Base URL</label>
500
+ <input
501
+ className="settings-input"
502
+ value={settings.claude?.base_url || ""}
503
+ onChange={(e) => updateField("claude", "base_url", e.target.value)}
504
+ placeholder="Optional custom base URL"
505
+ />
506
+
507
+ <label className="settings-label">Model</label>
508
+ <input
509
+ className="settings-input"
510
+ value={settings.claude?.model || ""}
511
+ onChange={(e) => updateField("claude", "model", e.target.value)}
512
+ placeholder="claude-sonnet-4-5"
513
+ />
514
+ </div>
515
+ )}
516
+
517
+ {provider === "watsonx" && (
518
+ <div className="settings-card">
519
+ <div className="settings-title">Watsonx Configuration</div>
520
+
521
+ <label className="settings-label">API Key</label>
522
+ <input
523
+ className="settings-input"
524
+ type="password"
525
+ value={settings.watsonx?.api_key || ""}
526
+ onChange={(e) => updateField("watsonx", "api_key", e.target.value)}
527
+ placeholder="Watsonx API key"
528
+ />
529
+
530
+ <label className="settings-label">Project ID</label>
531
+ <input
532
+ className="settings-input"
533
+ value={settings.watsonx?.project_id || ""}
534
+ onChange={(e) =>
535
+ updateField("watsonx", "project_id", e.target.value)
536
+ }
537
+ placeholder="Watsonx project ID"
538
+ />
539
+
540
+ <label className="settings-label">Base URL</label>
541
+ <input
542
+ className="settings-input"
543
+ value={settings.watsonx?.base_url || ""}
544
+ onChange={(e) => updateField("watsonx", "base_url", e.target.value)}
545
+ placeholder="https://api.watsonx.ai/v1"
546
+ />
547
+
548
+ <label className="settings-label">Model</label>
549
+ <input
550
+ className="settings-input"
551
+ value={settings.watsonx?.model_id || ""}
552
+ onChange={(e) =>
553
+ updateField("watsonx", "model_id", e.target.value)
554
+ }
555
+ placeholder="meta-llama/llama-3-3-70b-instruct"
556
+ />
557
+ </div>
558
+ )}
559
+
560
+ {provider === "ollama" && (
561
+ <div className="settings-card">
562
+ <div className="settings-title">Ollama Configuration</div>
563
+
564
+ <label className="settings-label">Base URL</label>
565
+ <input
566
+ className="settings-input"
567
+ value={settings.ollama?.base_url || ""}
568
+ onChange={(e) => updateField("ollama", "base_url", e.target.value)}
569
+ placeholder="http://localhost:11434"
570
+ />
571
+
572
+ <label className="settings-label">Model</label>
573
+ <div className="settings-inline-row">
574
+ <input
575
+ className="settings-input"
576
+ value={settings.ollama?.model || ""}
577
+ onChange={(e) => updateField("ollama", "model", e.target.value)}
578
+ placeholder="llama3"
579
+ />
580
+ <button
581
+ type="button"
582
+ className="settings-secondary-btn"
583
+ onClick={() => loadModelsForProvider("ollama")}
584
+ disabled={loadingModelsFor === "ollama"}
585
+ >
586
+ {loadingModelsFor === "ollama" ? "Loading…" : "Load Models"}
587
+ </button>
588
+ </div>
589
+ </div>
590
+ )}
591
+
592
+ {availableModels.length > 0 && (
593
+ <div className="settings-card">
594
+ <div className="settings-title">Available Models</div>
595
+ <div className="settings-model-list">
596
+ {availableModels.map((model) => (
597
+ <button
598
+ key={model}
599
+ type="button"
600
+ className="settings-model-chip"
601
+ onClick={() => updateField(provider, "model", model)}
602
+ >
603
+ {model}
604
+ </button>
605
+ ))}
606
+ </div>
607
+ </div>
608
+ )}
609
+
610
+ {modelsError && <div className="settings-error-banner">{modelsError}</div>}
611
+
612
+ {testResult && (
613
+ <div
614
+ className={
615
+ testResult.health === "ok"
616
+ ? "settings-success-banner"
617
+ : "settings-error-banner"
618
+ }
619
+ >
620
+ {testResult.health === "ok"
621
+ ? testResult.details || "Provider connection successful."
622
+ : testResult.warning || "Provider connection failed."}
623
+ </div>
624
+ )}
625
+
626
+ <div className="settings-actions">
627
+ <button
628
+ type="button"
629
+ className="settings-save-btn"
630
+ onClick={handleSave}
631
+ disabled={saving}
632
+ >
633
+ {saving ? "Saving…" : "Save Settings"}
634
+ </button>
635
+
636
+ <button
637
+ type="button"
638
+ className="settings-secondary-btn"
639
+ onClick={handleTestConnection}
640
+ disabled={testing}
641
+ >
642
+ {testing ? "Testing…" : "Test Connection"}
643
+ </button>
644
+ </div>
645
+ </div>
646
+ );
647
+ }
frontend/components/LoginPage.jsx ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // frontend/components/LoginPage.jsx
2
+ import React, { useState, useEffect, useRef } from "react";
3
+ import { apiUrl, safeFetchJSON } from "../utils/api.js";
4
+ import { initApp } from "../utils/appInit.js";
5
+
6
+ /**
7
+ * GitPilot – Enterprise Agentic Login
8
+ * Theme: "Claude Code" / Anthropic Enterprise (Dark + Warm Orange)
9
+ */
10
+
11
+ export default function LoginPage({ onAuthenticated, backendReady = false }) {
12
+ // Auth State
13
+ const [authProcessing, setAuthProcessing] = useState(false);
14
+ const [error, setError] = useState("");
15
+
16
+ // Mode State: 'loading' | 'web' (Has Secret) | 'device' (No Secret)
17
+ const [mode, setMode] = useState("loading");
18
+
19
+ // Device Flow State
20
+ const [deviceData, setDeviceData] = useState(null);
21
+ const pollTimer = useRef(null);
22
+ const stopPolling = useRef(false); // Flag to safely stop async polling
23
+
24
+ // Web Flow State
25
+ const [missingClientId, setMissingClientId] = useState(false);
26
+
27
+ // REF FIX: Prevents React StrictMode from running the auth exchange twice
28
+ const processingRef = useRef(false);
29
+ const authCheckDone = useRef(false);
30
+
31
+ // 1. Initialization Effect — runs once on mount AND when backendReady changes
32
+ useEffect(() => {
33
+ // Skip if already resolved
34
+ if (authCheckDone.current && mode !== "loading") return;
35
+
36
+ const params = new URLSearchParams(window.location.search);
37
+ const code = params.get("code");
38
+ const state = params.get("state");
39
+
40
+ // A. If returning from GitHub (Web Flow Callback)
41
+ if (code) {
42
+ if (!processingRef.current) {
43
+ processingRef.current = true;
44
+ setMode("web");
45
+ consumeOAuthCallback(code, state);
46
+ }
47
+ return;
48
+ }
49
+
50
+ // B. Use the shared singleton init — reuses App.jsx's result.
51
+ // No duplicate /api/auth/status calls, no separate retry loops.
52
+ initApp().then((result) => {
53
+ authCheckDone.current = true;
54
+ if (result.ready) {
55
+ setError("");
56
+ setMode(result.authMode === "web" ? "web" : "device");
57
+ } else {
58
+ // Backend unreachable — allow device flow as fallback
59
+ setError(result.error || "Backend unavailable");
60
+ setMode("device");
61
+ }
62
+ });
63
+
64
+ // Cleanup polling on unmount
65
+ return () => {
66
+ stopPolling.current = true;
67
+ if (pollTimer.current) clearTimeout(pollTimer.current);
68
+ };
69
+ // eslint-disable-next-line react-hooks/exhaustive-deps
70
+ }, [backendReady]);
71
+
72
+ // ===========================================================================
73
+ // WEB FLOW LOGIC (Standard OAuth2)
74
+ // ===========================================================================
75
+
76
+ async function consumeOAuthCallback(code, state) {
77
+ const expectedState = sessionStorage.getItem("gitpilot_oauth_state");
78
+ if (state && expectedState && expectedState !== state) {
79
+ console.warn("OAuth state mismatch - proceeding with caution.");
80
+ }
81
+
82
+ setAuthProcessing(true);
83
+ setError("");
84
+ window.history.replaceState({}, document.title, window.location.pathname);
85
+
86
+ try {
87
+ const data = await safeFetchJSON(apiUrl("/api/auth/callback"), {
88
+ method: "POST",
89
+ headers: { "Content-Type": "application/json" },
90
+ body: JSON.stringify({ code, state: state || "" }),
91
+ });
92
+
93
+ handleSuccess(data);
94
+ } catch (err) {
95
+ console.error("Login Error:", err);
96
+ setError(err instanceof Error ? err.message : "Login failed.");
97
+ setAuthProcessing(false);
98
+ }
99
+ }
100
+
101
+ async function handleSignInWithGitHub() {
102
+ setError("");
103
+ setMissingClientId(false);
104
+ setAuthProcessing(true);
105
+
106
+ try {
107
+ const data = await safeFetchJSON(apiUrl("/api/auth/url"));
108
+
109
+ if (data.state) {
110
+ sessionStorage.setItem("gitpilot_oauth_state", data.state);
111
+ }
112
+
113
+ window.location.href = data.authorization_url;
114
+ } catch (err) {
115
+ console.error("Auth Start Error:", err);
116
+ // Check for missing client ID (404/500 errors)
117
+ if (err.message && (err.message.includes('404') || err.message.includes('500'))) {
118
+ setMissingClientId(true);
119
+ } else {
120
+ setError(err instanceof Error ? err.message : "Could not start sign-in.");
121
+ }
122
+ setAuthProcessing(false);
123
+ }
124
+ }
125
+
126
+ // ===========================================================================
127
+ // DEVICE FLOW LOGIC (No Client Secret Required)
128
+ // ===========================================================================
129
+
130
+ const startDeviceFlow = async () => {
131
+ setError("");
132
+ setAuthProcessing(true);
133
+ stopPolling.current = false; // Reset stop flag
134
+
135
+ try {
136
+ const data = await safeFetchJSON(apiUrl("/api/auth/device/code"), { method: "POST" });
137
+
138
+ // Handle Errors
139
+ if (data.error) {
140
+ if (data.error.includes("400") || data.error.includes("Bad Request")) {
141
+ 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'.");
142
+ }
143
+ throw new Error(data.error);
144
+ }
145
+
146
+ if (!data.device_code) throw new Error("Invalid device code response");
147
+
148
+ setDeviceData(data);
149
+ setAuthProcessing(false);
150
+
151
+ // Start Polling (Recursive Timeout Pattern)
152
+ pollDeviceToken(data.device_code, data.interval || 5);
153
+
154
+ } catch (err) {
155
+ setError(err.message);
156
+ setAuthProcessing(false);
157
+ }
158
+ };
159
+
160
+ const pollDeviceToken = async (deviceCode, interval) => {
161
+ if (stopPolling.current) return;
162
+
163
+ try {
164
+ const response = await fetch(apiUrl("/api/auth/device/poll"), {
165
+ method: "POST",
166
+ headers: { "Content-Type": "application/json" },
167
+ body: JSON.stringify({ device_code: deviceCode })
168
+ });
169
+
170
+ // 1. Success (200)
171
+ if (response.status === 200) {
172
+ const data = await response.json();
173
+ handleSuccess(data);
174
+ return;
175
+ }
176
+
177
+ // 2. Pending (202) -> Continue Polling
178
+ if (response.status === 202) {
179
+ // Schedule next poll
180
+ pollTimer.current = setTimeout(
181
+ () => pollDeviceToken(deviceCode, interval),
182
+ interval * 1000
183
+ );
184
+ return;
185
+ }
186
+
187
+ // 3. Error (4xx/5xx) -> Stop Polling & Show Error
188
+ const errData = await response.json().catch(() => ({ error: "Unknown polling error" }));
189
+
190
+ // Special case: If it's just a 'slow_down' warning (sometimes 400), we just wait longer
191
+ if (errData.error === "slow_down") {
192
+ pollTimer.current = setTimeout(
193
+ () => pollDeviceToken(deviceCode, interval + 5),
194
+ (interval + 5) * 1000
195
+ );
196
+ return;
197
+ }
198
+
199
+ // Terminal errors
200
+ throw new Error(errData.error || `Polling failed: ${response.status}`);
201
+
202
+ } catch (e) {
203
+ console.error("Poll error:", e);
204
+ if (!stopPolling.current) {
205
+ setError(e.message || "Failed to connect to authentication server.");
206
+ setDeviceData(null); // Return to initial state
207
+ }
208
+ }
209
+ };
210
+
211
+ const handleManualCheck = async () => {
212
+ if (!deviceData?.device_code) return;
213
+
214
+ try {
215
+ const response = await fetch(apiUrl("/api/auth/device/poll"), {
216
+ method: "POST",
217
+ headers: { "Content-Type": "application/json" },
218
+ body: JSON.stringify({ device_code: deviceData.device_code })
219
+ });
220
+
221
+ if (response.status === 200) {
222
+ const data = await response.json();
223
+ handleSuccess(data);
224
+ } else if (response.status === 202) {
225
+ // Visual feedback for pending state
226
+ const btn = document.getElementById("manual-check-btn");
227
+ if (btn) {
228
+ const originalText = btn.innerText;
229
+ btn.innerText = "Still Pending...";
230
+ btn.disabled = true;
231
+ setTimeout(() => {
232
+ btn.innerText = originalText;
233
+ btn.disabled = false;
234
+ }, 2000);
235
+ }
236
+ }
237
+ } catch (e) {
238
+ console.error("Manual check failed", e);
239
+ }
240
+ };
241
+
242
+ const handleCancelDeviceFlow = () => {
243
+ stopPolling.current = true;
244
+ if (pollTimer.current) clearTimeout(pollTimer.current);
245
+ setDeviceData(null);
246
+ setError("");
247
+ };
248
+
249
+ // ===========================================================================
250
+ // SHARED HELPERS
251
+ // ===========================================================================
252
+
253
+ function handleSuccess(data) {
254
+ stopPolling.current = true; // Ensure polling stops
255
+ if (pollTimer.current) clearTimeout(pollTimer.current);
256
+
257
+ if (!data.access_token || !data.user) {
258
+ setError("Server returned incomplete session data.");
259
+ return;
260
+ }
261
+
262
+ try {
263
+ localStorage.setItem("github_token", data.access_token);
264
+ localStorage.setItem("github_user", JSON.stringify(data.user));
265
+ } catch (e) {
266
+ console.warn("LocalStorage access denied:", e);
267
+ }
268
+
269
+ if (typeof onAuthenticated === "function") {
270
+ onAuthenticated({
271
+ access_token: data.access_token,
272
+ user: data.user,
273
+ });
274
+ }
275
+ }
276
+
277
+ // --- Design Token System ---
278
+ const theme = {
279
+ bg: "#131316",
280
+ cardBg: "#1C1C1F",
281
+ border: "#27272A",
282
+ accent: "#D95C3D",
283
+ accentHover: "#C44F32",
284
+ textPrimary: "#EDEDED",
285
+ textSecondary: "#A1A1AA",
286
+ font: '"Söhne", "Inter", -apple-system, sans-serif',
287
+ };
288
+
289
+ const styles = {
290
+ container: {
291
+ minHeight: "100vh",
292
+ display: "flex",
293
+ alignItems: "center",
294
+ justifyContent: "center",
295
+ backgroundColor: theme.bg,
296
+ fontFamily: theme.font,
297
+ color: theme.textPrimary,
298
+ letterSpacing: "-0.01em",
299
+ },
300
+ card: {
301
+ backgroundColor: theme.cardBg,
302
+ width: "100%",
303
+ maxWidth: "440px",
304
+ borderRadius: "12px",
305
+ border: `1px solid ${theme.border}`,
306
+ boxShadow: "0 24px 48px -12px rgba(0, 0, 0, 0.6)",
307
+ padding: "48px 40px",
308
+ textAlign: "center",
309
+ position: "relative",
310
+ },
311
+ logoBadge: {
312
+ width: "48px",
313
+ height: "48px",
314
+ backgroundColor: "rgba(217, 92, 61, 0.15)",
315
+ color: theme.accent,
316
+ borderRadius: "10px",
317
+ display: "flex",
318
+ alignItems: "center",
319
+ justifyContent: "center",
320
+ fontSize: "22px",
321
+ fontWeight: "700",
322
+ margin: "0 auto 32px auto",
323
+ border: "1px solid rgba(217, 92, 61, 0.2)",
324
+ },
325
+ h1: {
326
+ fontSize: "24px",
327
+ fontWeight: "600",
328
+ marginBottom: "12px",
329
+ color: theme.textPrimary,
330
+ },
331
+ p: {
332
+ fontSize: "14px",
333
+ color: theme.textSecondary,
334
+ lineHeight: "1.6",
335
+ marginBottom: "40px",
336
+ },
337
+ button: {
338
+ width: "100%",
339
+ height: "48px",
340
+ backgroundColor: theme.accent,
341
+ color: "#FFFFFF",
342
+ border: "none",
343
+ borderRadius: "8px",
344
+ fontSize: "14px",
345
+ fontWeight: "500",
346
+ cursor: (authProcessing || (mode === 'loading')) ? "not-allowed" : "pointer",
347
+ opacity: (authProcessing || (mode === 'loading')) ? 0.7 : 1,
348
+ transition: "background-color 0.2s ease",
349
+ display: "flex",
350
+ alignItems: "center",
351
+ justifyContent: "center",
352
+ gap: "10px",
353
+ boxShadow: "0 4px 12px rgba(217, 92, 61, 0.25)",
354
+ },
355
+ secondaryButton: {
356
+ backgroundColor: "transparent",
357
+ color: "#A1A1AA",
358
+ border: "1px solid #3F3F46",
359
+ padding: "8px 16px",
360
+ borderRadius: "6px",
361
+ fontSize: "12px",
362
+ cursor: "pointer",
363
+ marginTop: "16px",
364
+ minWidth: "100px"
365
+ },
366
+ errorBox: {
367
+ backgroundColor: "rgba(185, 28, 28, 0.15)",
368
+ border: "1px solid rgba(185, 28, 28, 0.3)",
369
+ color: "#FCA5A5",
370
+ padding: "12px",
371
+ borderRadius: "8px",
372
+ fontSize: "13px",
373
+ marginBottom: "24px",
374
+ textAlign: "left",
375
+ },
376
+ configCard: {
377
+ textAlign: "left",
378
+ backgroundColor: "#111",
379
+ border: "1px solid #333",
380
+ padding: "24px",
381
+ borderRadius: "8px",
382
+ marginBottom: "24px",
383
+ },
384
+ codeDisplay: {
385
+ backgroundColor: "#27272A",
386
+ color: theme.accent,
387
+ fontSize: "20px",
388
+ fontWeight: "700",
389
+ padding: "12px",
390
+ borderRadius: "6px",
391
+ textAlign: "center",
392
+ letterSpacing: "2px",
393
+ margin: "12px 0",
394
+ border: `1px dashed ${theme.accent}`,
395
+ cursor: "pointer",
396
+ },
397
+ footer: {
398
+ marginTop: "48px",
399
+ fontSize: "12px",
400
+ color: "#52525B",
401
+ }
402
+ };
403
+
404
+ // --- RENDER: Device Flow UI ---
405
+ const renderDeviceFlow = () => {
406
+ if (!deviceData) {
407
+ return (
408
+ <button
409
+ onClick={startDeviceFlow}
410
+ disabled={authProcessing}
411
+ style={styles.button}
412
+ onMouseOver={(e) => !authProcessing && (e.currentTarget.style.backgroundColor = theme.accentHover)}
413
+ onMouseOut={(e) => !authProcessing && (e.currentTarget.style.backgroundColor = theme.accent)}
414
+ >
415
+ {authProcessing ? "Connecting..." : "Sign in with GitHub"}
416
+ </button>
417
+ );
418
+ }
419
+
420
+ return (
421
+ <div style={styles.configCard}>
422
+ <h3 style={{marginTop:0, color: '#FFF', fontSize: '16px'}}>Authorize Device</h3>
423
+ <p style={{color: '#AAA', fontSize: '13px', marginBottom:'16px'}}>
424
+ GitPilot needs authorization to access your repositories.
425
+ </p>
426
+
427
+ <div style={{marginBottom: '16px'}}>
428
+ <div style={{color: '#AAA', fontSize: '12px', marginBottom: '4px'}}>1. Copy code:</div>
429
+ <div
430
+ style={styles.codeDisplay}
431
+ onClick={() => {
432
+ navigator.clipboard.writeText(deviceData.user_code);
433
+ }}
434
+ title="Click to copy"
435
+ >
436
+ {deviceData.user_code}
437
+ </div>
438
+ </div>
439
+
440
+ <div>
441
+ <div style={{color: '#AAA', fontSize: '12px', marginBottom: '4px'}}>2. Paste at GitHub:</div>
442
+ <a
443
+ href={deviceData.verification_uri}
444
+ target="_blank"
445
+ rel="noreferrer"
446
+ style={{
447
+ display: 'block',
448
+ backgroundColor: '#FFF',
449
+ color: '#000',
450
+ textDecoration: 'none',
451
+ padding: '10px',
452
+ borderRadius: '6px',
453
+ textAlign: 'center',
454
+ fontWeight: '600',
455
+ fontSize: '14px'
456
+ }}
457
+ >
458
+ Open Activation Page ↗
459
+ </a>
460
+ </div>
461
+
462
+ <div style={{marginTop: '20px', fontSize: '12px', color: '#666', textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px'}}>
463
+ <span style={{animation: 'spin 1s linear infinite', display: 'inline-block'}}>↻</span>
464
+ Waiting for authorization...
465
+ <style>{`@keyframes spin { 100% { transform: rotate(360deg); } }`}</style>
466
+ </div>
467
+
468
+ <div style={{textAlign: 'center', display: 'flex', gap: '10px', justifyContent: 'center'}}>
469
+ <button
470
+ id="manual-check-btn"
471
+ onClick={handleManualCheck}
472
+ style={styles.secondaryButton}
473
+ >
474
+ Check Status
475
+ </button>
476
+ <button
477
+ onClick={handleCancelDeviceFlow}
478
+ style={styles.secondaryButton}
479
+ >
480
+ Cancel
481
+ </button>
482
+ </div>
483
+ </div>
484
+ );
485
+ };
486
+
487
+ // --- RENDER: Config Error ---
488
+ if (missingClientId) {
489
+ return (
490
+ <div style={styles.container}>
491
+ <div style={styles.card}>
492
+ <div style={{...styles.logoBadge, color: "#F59E0B", backgroundColor: "rgba(245, 158, 11, 0.1)", borderColor: "rgba(245, 158, 11, 0.2)"}}>⚠️</div>
493
+ <h1 style={styles.h1}>Configuration Error</h1>
494
+ <p style={styles.p}>Could not connect to GitHub Authentication services.</p>
495
+ <button onClick={() => setMissingClientId(false)} style={{...styles.button, backgroundColor: "#3F3F46"}}>Retry</button>
496
+ </div>
497
+ </div>
498
+ );
499
+ }
500
+
501
+ // --- RENDER: Main ---
502
+ return (
503
+ <div style={styles.container}>
504
+ <div style={styles.card}>
505
+ <div style={styles.logoBadge}>GP</div>
506
+
507
+ <h1 style={styles.h1}>GitPilot Enterprise</h1>
508
+ <p style={styles.p}>
509
+ Agentic AI workflow for your repositories.<br/>
510
+ Secure. Context-aware. Automated.
511
+ </p>
512
+
513
+ {error && <div style={styles.errorBox}>{error}</div>}
514
+
515
+ {mode === "loading" && (
516
+ <div style={{color: '#666', fontSize: '14px'}}>Initializing...</div>
517
+ )}
518
+
519
+ {mode === "web" && (
520
+ <button
521
+ onClick={handleSignInWithGitHub}
522
+ disabled={authProcessing}
523
+ style={styles.button}
524
+ onMouseOver={(e) => !authProcessing && (e.currentTarget.style.backgroundColor = theme.accentHover)}
525
+ onMouseOut={(e) => !authProcessing && (e.currentTarget.style.backgroundColor = theme.accent)}
526
+ >
527
+ {authProcessing ? "Connecting..." : (
528
+ <>
529
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405 1.02 0 2.04.135 3 .405 2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" /></svg>
530
+ Sign in with GitHub
531
+ </>
532
+ )}
533
+ </button>
534
+ )}
535
+
536
+ {mode === "device" && renderDeviceFlow()}
537
+
538
+ <div style={styles.footer}>
539
+ &copy; {new Date().getFullYear()} GitPilot Inc.
540
+ </div>
541
+ </div>
542
+ </div>
543
+ );
544
+ }
frontend/components/PlanView.jsx ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from "react";
2
+
3
+ /**
4
+ * PlanView — enterprise "Proposed execution plan" card.
5
+ *
6
+ * One main card. Subtle internal spacing instead of bordered nested boxes.
7
+ * Steps are rendered as a vertical numbered timeline; file actions become
8
+ * compact pill badges (READ / CREATE / MODIFY / DELETE / INDEX).
9
+ *
10
+ * The card itself is borderless — the surrounding AssistantMessage
11
+ * already provides the outer container.
12
+ */
13
+ export default function PlanView({ plan, planStatus }) {
14
+ if (!plan) return null;
15
+
16
+ const totals = { CREATE: 0, MODIFY: 0, DELETE: 0, INDEX: 0, READ: 0, EXECUTE: 0 };
17
+ plan.steps.forEach((step) => {
18
+ step.files.forEach((file) => {
19
+ totals[file.action] = (totals[file.action] || 0) + 1;
20
+ });
21
+ });
22
+
23
+ return (
24
+ <div className="exec-card exec-card--plan">
25
+ <div className="exec-card__head">
26
+ <div className="exec-card__icon exec-card__icon--plan" aria-hidden="true">
27
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
28
+ stroke="currentColor" strokeWidth="2" strokeLinecap="round"
29
+ strokeLinejoin="round">
30
+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
31
+ <polyline points="14 2 14 8 20 8" />
32
+ <line x1="8" y1="13" x2="16" y2="13" />
33
+ <line x1="8" y1="17" x2="13" y2="17" />
34
+ </svg>
35
+ </div>
36
+ <div className="exec-card__head-text">
37
+ <div className="exec-card__eyebrow">Proposed execution plan</div>
38
+ <div className="exec-card__title">{plan.goal}</div>
39
+ </div>
40
+
41
+ <div className="exec-card__head-right">
42
+ {planStatus === "executed" && (
43
+ <span className="exec-status-badge exec-status-badge--ok">
44
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
45
+ stroke="currentColor" strokeWidth="3" strokeLinecap="round"
46
+ strokeLinejoin="round" aria-hidden="true">
47
+ <polyline points="20 6 9 17 4 12" />
48
+ </svg>
49
+ Executed
50
+ </span>
51
+ )}
52
+ {planStatus === "rejected" && (
53
+ <span className="exec-status-badge exec-status-badge--muted">
54
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
55
+ stroke="currentColor" strokeWidth="2.6" strokeLinecap="round"
56
+ strokeLinejoin="round" aria-hidden="true">
57
+ <line x1="18" y1="6" x2="6" y2="18" />
58
+ <line x1="6" y1="6" x2="18" y2="18" />
59
+ </svg>
60
+ Rejected
61
+ </span>
62
+ )}
63
+
64
+ <div className="exec-card__totals">
65
+ {totals.CREATE > 0 && (
66
+ <span className="exec-total exec-total--create">
67
+ {totals.CREATE} create
68
+ </span>
69
+ )}
70
+ {totals.MODIFY > 0 && (
71
+ <span className="exec-total exec-total--modify">
72
+ {totals.MODIFY} modify
73
+ </span>
74
+ )}
75
+ {totals.DELETE > 0 && (
76
+ <span className="exec-total exec-total--delete">
77
+ {totals.DELETE} delete
78
+ </span>
79
+ )}
80
+ {totals.INDEX > 0 && (
81
+ <span className="exec-total exec-total--index">
82
+ {totals.INDEX === 1 ? "1 setup" : `${totals.INDEX} setup`}
83
+ </span>
84
+ )}
85
+ {/* Fallback surface: an EXECUTE plan normally renders the green
86
+ ExecutionPlanCard instead. This shows up when the sandbox
87
+ builder declined the file (unknown extension), so the card is
88
+ absent but the step is still real. */}
89
+ {totals.EXECUTE > 0 && (
90
+ <span className="exec-total exec-total--index">
91
+ {totals.EXECUTE === 1 ? "1 run" : `${totals.EXECUTE} runs`}
92
+ </span>
93
+ )}
94
+ </div>
95
+ </div>
96
+ </div>
97
+
98
+ <ol className="exec-timeline">
99
+ {plan.steps.map((s, idx) => (
100
+ <li key={s.step_number} className="exec-step">
101
+ <div className="exec-step__rail" aria-hidden="true">
102
+ <div className="exec-step__num">{s.step_number}</div>
103
+ {idx < plan.steps.length - 1 && (
104
+ <div className="exec-step__line" />
105
+ )}
106
+ </div>
107
+ <div className="exec-step__body">
108
+ <div className="exec-step__title">{s.title}</div>
109
+ {s.description && (
110
+ <p className="exec-step__desc">{s.description}</p>
111
+ )}
112
+
113
+ {s.files && s.files.length > 0 && (
114
+ <ul className="exec-actions">
115
+ {s.files.map((file, fi) => (
116
+ <li key={fi} className="exec-action-row">
117
+ <span
118
+ className={`exec-badge exec-badge--${file.action.toLowerCase()}`}
119
+ >
120
+ {file.action}
121
+ </span>
122
+ <code className="exec-action__path">
123
+ {file.action === "INDEX"
124
+ ? "Build semantic index for this repo"
125
+ : file.path}
126
+ </code>
127
+ </li>
128
+ ))}
129
+ </ul>
130
+ )}
131
+
132
+ {s.files && s.files.some((f) => f.action === "INDEX") && (
133
+ <div className="exec-notice">
134
+ One-time semantic index build (~80 MB model, ~30 s, ~12 MB on
135
+ disk). No cloud calls. Click <strong>Reject plan</strong> to
136
+ skip — you'll be offered the grep fallback.
137
+ </div>
138
+ )}
139
+
140
+ {s.risks && (
141
+ <div className="exec-risk">
142
+ <span aria-hidden="true">⚠</span>
143
+ <span>{s.risks}</span>
144
+ </div>
145
+ )}
146
+ </div>
147
+ </li>
148
+ ))}
149
+ </ol>
150
+ </div>
151
+ );
152
+ }
frontend/components/ProjectContextPanel.jsx ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useRef, useState } from "react";
2
+ import { apiUrl } from "../utils/api.js";
3
+ import FileTree from "./FileTree.jsx";
4
+ import BranchPicker from "./BranchPicker.jsx";
5
+ import SandboxStatusWidget from "./SandboxStatusWidget.jsx";
6
+
7
+ // --- INJECTED STYLES FOR ANIMATIONS ---
8
+ const animationStyles = `
9
+ @keyframes highlight-pulse {
10
+ 0% { background-color: rgba(59, 130, 246, 0.10); }
11
+ 50% { background-color: rgba(59, 130, 246, 0.22); }
12
+ 100% { background-color: transparent; }
13
+ }
14
+ .pulse-context {
15
+ animation: highlight-pulse 1.1s ease-out;
16
+ }
17
+ `;
18
+
19
+ /**
20
+ * ProjectContextPanel (Production-ready)
21
+ *
22
+ * Controlled component:
23
+ * - Branch source of truth is App.jsx:
24
+ * - defaultBranch (prod)
25
+ * - currentBranch (what user sees)
26
+ * - sessionBranches (list of all active AI session branches)
27
+ *
28
+ * Responsibilities:
29
+ * - Show project context + branch dropdown + AI badge/banner
30
+ * - Fetch access status + file count for the currentBranch
31
+ * - Trigger visual pulse on pulseNonce (Hard Switch)
32
+ */
33
+ export default function ProjectContextPanel({
34
+ repo,
35
+ defaultBranch,
36
+ currentBranch,
37
+ sessionBranch, // Active session branch (optional, for specific highlighting)
38
+ sessionBranches = [], // List of all AI branches
39
+ onBranchChange,
40
+ pulseNonce,
41
+ onSettingsClick,
42
+ runtime,
43
+ }) {
44
+ const [appUrl, setAppUrl] = useState("");
45
+ const [fileCount, setFileCount] = useState(0);
46
+
47
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
48
+
49
+ // Data Loading State
50
+ const [analyzing, setAnalyzing] = useState(false);
51
+ const [accessInfo, setAccessInfo] = useState(null);
52
+ const [treeError, setTreeError] = useState(null);
53
+
54
+ // Retry / Refresh Logic
55
+ const [refreshTrigger, setRefreshTrigger] = useState(0);
56
+ const [retryCount, setRetryCount] = useState(0);
57
+ const retryTimeoutRef = useRef(null);
58
+
59
+ // UX State
60
+ const [animateHeader, setAnimateHeader] = useState(false);
61
+ const [toast, setToast] = useState({ visible: false, title: "", msg: "" });
62
+
63
+ // Calculate effective default to prevent 'main' fallback errors
64
+ const effectiveDefaultBranch = defaultBranch || repo?.default_branch || "main";
65
+ const branch = currentBranch || effectiveDefaultBranch;
66
+
67
+ // Determine if we are currently viewing an AI Session branch
68
+ const isAiSession = (sessionBranches.includes(branch)) || (sessionBranch === branch && branch !== effectiveDefaultBranch);
69
+
70
+ // Fetch App URL on mount
71
+ useEffect(() => {
72
+ fetch(apiUrl("/api/auth/app-url"))
73
+ .then((res) => res.json())
74
+ .then((data) => {
75
+ if (data.app_url) setAppUrl(data.app_url);
76
+ })
77
+ .catch((err) => console.error("Failed to fetch App URL:", err));
78
+ }, []);
79
+
80
+ // Hard Switch pulse: whenever App increments pulseNonce
81
+ useEffect(() => {
82
+ if (!pulseNonce) return;
83
+ setAnimateHeader(true);
84
+ const t = window.setTimeout(() => setAnimateHeader(false), 1100);
85
+ return () => window.clearTimeout(t);
86
+ }, [pulseNonce]);
87
+
88
+ // Main data fetcher (Access + Tree stats) for currentBranch
89
+ // Stale-while-revalidate: keep previous data visible during fetch
90
+ useEffect(() => {
91
+ if (!repo) return;
92
+
93
+ // Only show full "analyzing" spinner if we have no data yet
94
+ if (!accessInfo) setAnalyzing(true);
95
+ setTreeError(null);
96
+
97
+ if (retryTimeoutRef.current) {
98
+ clearTimeout(retryTimeoutRef.current);
99
+ retryTimeoutRef.current = null;
100
+ }
101
+
102
+ let headers = {};
103
+ try {
104
+ const token = localStorage.getItem("github_token");
105
+ if (token) headers = { Authorization: `Bearer ${token}` };
106
+ } catch (e) {
107
+ console.warn("Unable to read github_token:", e);
108
+ }
109
+
110
+ let cancelled = false;
111
+ const cacheBuster = `&_t=${Date.now()}&retry=${retryCount}`;
112
+
113
+ // A) Access Check (with Stale Cache Fix)
114
+ fetch(apiUrl(`/api/auth/repo-access?owner=${repo.owner}&repo=${repo.name}${cacheBuster}`), {
115
+ headers,
116
+ cache: "no-cache",
117
+ })
118
+ .then(async (res) => {
119
+ if (cancelled) return;
120
+ const data = await res.json().catch(() => ({}));
121
+
122
+ if (!res.ok) {
123
+ setAccessInfo({ can_write: false, app_installed: false, auth_type: "none" });
124
+ return;
125
+ }
126
+
127
+ setAccessInfo(data);
128
+
129
+ // Auto-retry if user has push access but App is not detected yet (Stale Cache)
130
+ if (data.can_write && !data.app_installed && retryCount === 0) {
131
+ retryTimeoutRef.current = setTimeout(() => {
132
+ setRetryCount(1);
133
+ }, 1000);
134
+ }
135
+ })
136
+ .catch(() => {
137
+ if (!cancelled) setAccessInfo({ can_write: false, app_installed: false, auth_type: "none" });
138
+ });
139
+
140
+ // B) Tree count for the selected branch
141
+ // Don't clear fileCount — keep stale value visible until new one arrives
142
+ const hadFileCount = fileCount > 0;
143
+ if (!hadFileCount) setAnalyzing(true);
144
+
145
+ fetch(apiUrl(`/api/repos/${repo.owner}/${repo.name}/tree?ref=${encodeURIComponent(branch)}&_t=${Date.now()}`), {
146
+ headers,
147
+ cache: "no-cache",
148
+ })
149
+ .then(async (res) => {
150
+ if (cancelled) return;
151
+ const data = await res.json().catch(() => ({}));
152
+ if (!res.ok) {
153
+ setTreeError(data.detail || "Failed to load tree");
154
+ setFileCount(0);
155
+ return;
156
+ }
157
+ setFileCount(Array.isArray(data.files) ? data.files.length : 0);
158
+ })
159
+ .catch((err) => {
160
+ if (cancelled) return;
161
+ setTreeError(err.message);
162
+ setFileCount(0);
163
+ })
164
+ .finally(() => { if (!cancelled) setAnalyzing(false); });
165
+
166
+ return () => {
167
+ cancelled = true;
168
+ if (retryTimeoutRef.current) clearTimeout(retryTimeoutRef.current);
169
+ };
170
+ // eslint-disable-next-line react-hooks/exhaustive-deps
171
+ }, [repo?.owner, repo?.name, branch, refreshTrigger, retryCount]);
172
+
173
+ const showToast = (title, msg) => {
174
+ setToast({ visible: true, title, msg });
175
+ setTimeout(() => setToast((prev) => ({ ...prev, visible: false })), 3000);
176
+ };
177
+
178
+ const handleManualSwitch = (targetBranch) => {
179
+ if (!targetBranch || targetBranch === branch) {
180
+ setIsDropdownOpen(false);
181
+ return;
182
+ }
183
+
184
+ // Local UI feedback (App.jsx will handle the actual state change)
185
+ const goingAi = sessionBranches.includes(targetBranch);
186
+ showToast(
187
+ goingAi ? "Context Switched" : "Switched to Production",
188
+ goingAi ? `Viewing AI Session: ${targetBranch}` : `Viewing ${targetBranch}.`
189
+ );
190
+
191
+ setIsDropdownOpen(false);
192
+ if (onBranchChange) onBranchChange(targetBranch);
193
+ };
194
+
195
+ const handleRefresh = () => {
196
+ setAnalyzing(true);
197
+ setRetryCount(0);
198
+ setRefreshTrigger((prev) => prev + 1);
199
+ };
200
+
201
+ const handleInstallClick = () => {
202
+ if (!appUrl) return;
203
+ const targetUrl = appUrl.endsWith("/") ? `${appUrl}installations/new` : `${appUrl}/installations/new`;
204
+ window.open(targetUrl, "_blank", "noopener,noreferrer");
205
+ };
206
+
207
+ // --- STYLES ---
208
+ const theme = useMemo(
209
+ () => ({
210
+ bg: "#131316",
211
+ border: "#27272A",
212
+ textPrimary: "#EDEDED",
213
+ textSecondary: "#A1A1AA",
214
+ accent: "#3b82f6",
215
+ warningBorder: "rgba(245, 158, 11, 0.2)",
216
+ warningText: "#F59E0B",
217
+ successColor: "#10B981",
218
+ cardBg: "#18181B",
219
+ aiBg: "rgba(59, 130, 246, 0.10)",
220
+ aiBorder: "rgba(59, 130, 246, 0.30)",
221
+ aiText: "#60a5fa",
222
+ }),
223
+ []
224
+ );
225
+
226
+ const styles = useMemo(
227
+ () => ({
228
+ container: {
229
+ height: "100%",
230
+ borderRight: `1px solid ${theme.border}`,
231
+ backgroundColor: theme.bg,
232
+ display: "flex",
233
+ flexDirection: "column",
234
+ fontFamily: '"Söhne", "Inter", sans-serif',
235
+ position: "relative",
236
+ overflow: "hidden",
237
+ },
238
+ header: {
239
+ padding: "16px 20px",
240
+ borderBottom: `1px solid ${theme.border}`,
241
+ display: "flex",
242
+ alignItems: "center",
243
+ justifyContent: "space-between",
244
+ transition: "background-color 0.3s ease",
245
+ },
246
+ titleGroup: { display: "flex", alignItems: "center", gap: "8px" },
247
+ title: { fontSize: "13px", fontWeight: "600", color: theme.textPrimary },
248
+ repoBadge: {
249
+ backgroundColor: "#27272A",
250
+ color: theme.textSecondary,
251
+ fontSize: "11px",
252
+ padding: "2px 8px",
253
+ borderRadius: "12px",
254
+ border: `1px solid ${theme.border}`,
255
+ fontFamily: "monospace",
256
+ },
257
+ aiBadge: {
258
+ display: "flex",
259
+ alignItems: "center",
260
+ gap: "6px",
261
+ backgroundColor: theme.aiBg,
262
+ color: theme.aiText,
263
+ fontSize: "10px",
264
+ fontWeight: "bold",
265
+ padding: "2px 8px",
266
+ borderRadius: "12px",
267
+ border: `1px solid ${theme.aiBorder}`,
268
+ textTransform: "uppercase",
269
+ letterSpacing: "0.5px",
270
+ },
271
+ content: {
272
+ padding: "16px 20px 12px 20px",
273
+ display: "flex",
274
+ flexDirection: "column",
275
+ gap: "12px",
276
+ },
277
+ statRow: { display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "4px" },
278
+ label: { color: theme.textSecondary },
279
+ value: { color: theme.textPrimary, fontWeight: "500" },
280
+ dropdownContainer: { position: "relative" },
281
+ branchButton: {
282
+ display: "flex",
283
+ alignItems: "center",
284
+ gap: "6px",
285
+ padding: "4px 8px",
286
+ borderRadius: "4px",
287
+ border: `1px solid ${isAiSession ? theme.aiBorder : theme.border}`,
288
+ backgroundColor: isAiSession ? "rgba(59, 130, 246, 0.05)" : "transparent",
289
+ color: isAiSession ? theme.aiText : theme.textPrimary,
290
+ fontSize: "13px",
291
+ cursor: "pointer",
292
+ fontFamily: "monospace",
293
+ },
294
+ dropdownMenu: {
295
+ position: "absolute",
296
+ top: "100%",
297
+ left: 0,
298
+ marginTop: "4px",
299
+ width: "240px",
300
+ backgroundColor: "#1F1F23",
301
+ border: `1px solid ${theme.border}`,
302
+ borderRadius: "6px",
303
+ boxShadow: "0 4px 12px rgba(0,0,0,0.5)",
304
+ zIndex: 50,
305
+ display: isDropdownOpen ? "block" : "none",
306
+ overflow: "hidden",
307
+ },
308
+ dropdownItem: {
309
+ padding: "8px 12px",
310
+ fontSize: "13px",
311
+ color: theme.textSecondary,
312
+ cursor: "pointer",
313
+ display: "flex",
314
+ alignItems: "center",
315
+ gap: "8px",
316
+ borderBottom: `1px solid ${theme.border}`,
317
+ },
318
+ contextBanner: {
319
+ backgroundColor: theme.aiBg,
320
+ borderTop: `1px solid ${theme.aiBorder}`,
321
+ padding: "8px 20px",
322
+ fontSize: "11px",
323
+ color: theme.aiText,
324
+ display: "flex",
325
+ justifyContent: "space-between",
326
+ alignItems: "center",
327
+ },
328
+ toast: {
329
+ position: "absolute",
330
+ top: "16px",
331
+ right: "16px",
332
+ backgroundColor: "#18181B",
333
+ border: `1px solid ${theme.border}`,
334
+ borderLeft: `3px solid ${theme.accent}`,
335
+ borderRadius: "6px",
336
+ padding: "12px",
337
+ boxShadow: "0 4px 12px rgba(0,0,0,0.5)",
338
+ zIndex: 100,
339
+ minWidth: "240px",
340
+ transition: "all 0.3s cubic-bezier(0.16, 1, 0.3, 1)",
341
+ transform: toast.visible ? "translateX(0)" : "translateX(120%)",
342
+ opacity: toast.visible ? 1 : 0,
343
+ },
344
+ toastTitle: { fontSize: "13px", fontWeight: "bold", color: theme.textPrimary, marginBottom: "2px" },
345
+ toastMsg: { fontSize: "11px", color: theme.textSecondary },
346
+ refreshButton: {
347
+ marginTop: "8px",
348
+ height: "32px",
349
+ padding: "0 12px",
350
+ backgroundColor: "transparent",
351
+ color: theme.textSecondary,
352
+ border: `1px solid ${theme.border}`,
353
+ borderRadius: "6px",
354
+ fontSize: "12px",
355
+ cursor: analyzing ? "not-allowed" : "pointer",
356
+ display: "flex",
357
+ alignItems: "center",
358
+ justifyContent: "center",
359
+ gap: "6px",
360
+ },
361
+ settingsBtn: {
362
+ display: "flex",
363
+ alignItems: "center",
364
+ justifyContent: "center",
365
+ width: "28px",
366
+ height: "28px",
367
+ borderRadius: "6px",
368
+ border: `1px solid ${theme.border}`,
369
+ backgroundColor: "transparent",
370
+ color: theme.textSecondary,
371
+ cursor: "pointer",
372
+ padding: 0,
373
+ transition: "color 0.15s, border-color 0.15s",
374
+ },
375
+ treeWrapper: { flex: 1, overflow: "auto", borderTop: `1px solid ${theme.border}` },
376
+ installCard: {
377
+ marginTop: "8px",
378
+ padding: "12px",
379
+ borderRadius: "8px",
380
+ backgroundColor: theme.cardBg,
381
+ border: `1px solid ${theme.warningBorder}`,
382
+ },
383
+ installHeader: {
384
+ display: "flex",
385
+ alignItems: "center",
386
+ gap: "10px",
387
+ fontSize: "14px",
388
+ fontWeight: "600",
389
+ color: theme.textPrimary,
390
+ },
391
+ installText: {
392
+ fontSize: "13px",
393
+ color: theme.textSecondary,
394
+ lineHeight: "1.5",
395
+ },
396
+ }),
397
+ [analyzing, isAiSession, isDropdownOpen, theme, toast.visible]
398
+ );
399
+
400
+ // Determine status text
401
+ let statusText = "Checking...";
402
+ let statusColor = theme.textSecondary;
403
+ let showInstallCard = false;
404
+
405
+ if (!analyzing && accessInfo) {
406
+ if (accessInfo.app_installed) {
407
+ statusText = "Write Access ✓";
408
+ statusColor = theme.successColor;
409
+ } else if (accessInfo.can_write && retryCount === 0) {
410
+ statusText = "Verifying...";
411
+ } else if (accessInfo.can_write) {
412
+ statusText = "Push Access (No App)";
413
+ statusColor = theme.warningText;
414
+ showInstallCard = true;
415
+ } else {
416
+ statusText = "Read Only";
417
+ statusColor = theme.warningText;
418
+ showInstallCard = true;
419
+ }
420
+ }
421
+
422
+ if (!repo) {
423
+ return (
424
+ <div style={styles.container}>
425
+ <div style={styles.content}>Select a Repo</div>
426
+ </div>
427
+ );
428
+ }
429
+
430
+ return (
431
+ <div style={styles.container}>
432
+ <style>{animationStyles}</style>
433
+
434
+ {/* TOAST */}
435
+ <div style={styles.toast}>
436
+ <div style={styles.toastTitle}>{toast.title}</div>
437
+ <div style={styles.toastMsg}>{toast.msg}</div>
438
+ </div>
439
+
440
+ {/* HEADER */}
441
+ <div style={styles.header} className={animateHeader ? "pulse-context" : ""}>
442
+ <div style={styles.titleGroup}>
443
+ <span style={styles.title}>Project context</span>
444
+ {isAiSession && (
445
+ <span style={styles.aiBadge}>
446
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
447
+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
448
+ </svg>
449
+ AI Session
450
+ </span>
451
+ )}
452
+ </div>
453
+ <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
454
+ {!isAiSession && <span style={styles.repoBadge}>{repo.name}</span>}
455
+ {onSettingsClick && (
456
+ <button
457
+ type="button"
458
+ onClick={onSettingsClick}
459
+ title="Project settings"
460
+ style={styles.settingsBtn}
461
+ >
462
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
463
+ <circle cx="12" cy="12" r="3" />
464
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
465
+ </svg>
466
+ </button>
467
+ )}
468
+ </div>
469
+ </div>
470
+
471
+ {/* CONTENT */}
472
+ <div style={styles.content}>
473
+ {/* Branch selector (Claude-Code-on-Web parity — uses BranchPicker with search) */}
474
+ <div style={styles.statRow}>
475
+ <span style={styles.label}>Branch:</span>
476
+ <BranchPicker
477
+ repo={repo}
478
+ currentBranch={branch}
479
+ defaultBranch={effectiveDefaultBranch}
480
+ sessionBranches={sessionBranches}
481
+ onBranchChange={handleManualSwitch}
482
+ />
483
+ </div>
484
+
485
+ {/* Stats */}
486
+ <div style={styles.statRow}>
487
+ <span style={styles.label}>Files:</span>
488
+ <span style={styles.value}>{analyzing ? "…" : fileCount}</span>
489
+ </div>
490
+
491
+ <div style={styles.statRow}>
492
+ <span style={styles.label}>Status:</span>
493
+ <span style={{ ...styles.value, color: statusColor }}>{statusText}</span>
494
+ </div>
495
+
496
+ {/* Tree error (optional display) */}
497
+ {treeError && (
498
+ <div style={{ fontSize: 11, color: theme.warningText }}>
499
+ {treeError}
500
+ </div>
501
+ )}
502
+
503
+ {/* Refresh */}
504
+ <button type="button" style={styles.refreshButton} onClick={handleRefresh} disabled={analyzing}>
505
+ <svg
506
+ width="14"
507
+ height="14"
508
+ viewBox="0 0 24 24"
509
+ fill="none"
510
+ stroke="currentColor"
511
+ strokeWidth="2"
512
+ style={{
513
+ transform: analyzing ? "rotate(360deg)" : "rotate(0deg)",
514
+ transition: "transform 0.6s ease",
515
+ }}
516
+ >
517
+ <path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2" />
518
+ </svg>
519
+ {analyzing ? "Refreshing..." : "Refresh"}
520
+ </button>
521
+
522
+ {/* Install card */}
523
+ {showInstallCard && (
524
+ <div style={styles.installCard}>
525
+ <div style={styles.installHeader}>
526
+ <span>⚡</span>
527
+ <span>Enable Write Access</span>
528
+ </div>
529
+ <p style={{ ...styles.installText, margin: "8px 0" }}>
530
+ Install the GitPilot App to enable AI agent operations.
531
+ </p>
532
+ {runtime !== "cloud" && (
533
+ <p style={{ ...styles.installText, margin: "0 0 8px 0", fontSize: "11px", opacity: 0.7 }}>
534
+ Alternatively, use Folder or Local Git mode for local-first workflows without GitHub.
535
+ </p>
536
+ )}
537
+ <button
538
+ type="button"
539
+ style={{
540
+ ...styles.refreshButton,
541
+ width: "100%",
542
+ backgroundColor: theme.accent,
543
+ color: "#fff",
544
+ border: "none",
545
+ }}
546
+ onClick={handleInstallClick}
547
+ >
548
+ Install App
549
+ </button>
550
+ </div>
551
+ )}
552
+ </div>
553
+
554
+ {/* Context banner */}
555
+ {isAiSession && (
556
+ <div style={styles.contextBanner}>
557
+ <span style={{ display: "flex", alignItems: "center", gap: "6px" }}>
558
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
559
+ <circle cx="12" cy="12" r="10"></circle>
560
+ <line x1="12" y1="16" x2="12" y2="12"></line>
561
+ <line x1="12" y1="8" x2="12.01" y2="8"></line>
562
+ </svg>
563
+ You are viewing an AI Session branch.
564
+ </span>
565
+ <span style={{ textDecoration: "underline", cursor: "pointer" }} onClick={() => handleManualSwitch(effectiveDefaultBranch)}>
566
+ Return to {effectiveDefaultBranch}
567
+ </span>
568
+ </div>
569
+ )}
570
+
571
+ {/* File tree (branch-aware) */}
572
+ <div style={styles.treeWrapper}>
573
+ <FileTree repo={repo} refreshTrigger={refreshTrigger} branch={branch} />
574
+ </div>
575
+
576
+ {/* Sandbox status — always visible. Click "Change" / "Repair"
577
+ to open Settings (matches the existing settings affordance
578
+ at the top), or "Use Local" to one-click flip the backend
579
+ when MatrixLab is unreachable. */}
580
+ <div style={{ marginTop: 12 }}>
581
+ <SandboxStatusWidget onOpenSettings={onSettingsClick} />
582
+ </div>
583
+ </div>
584
+ );
585
+ }
frontend/components/ProjectSettings/ContextTab.jsx ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useRef, useState } from "react";
2
+ import { apiUrl } from "../../utils/api.js";
3
+
4
+ export default function ContextTab({ owner, repo }) {
5
+ const [assets, setAssets] = useState([]);
6
+ const [busy, setBusy] = useState(false);
7
+ const [error, setError] = useState("");
8
+ const [uploadHint, setUploadHint] = useState("");
9
+ const inputRef = useRef(null);
10
+
11
+ const canUse = useMemo(() => Boolean(owner && repo), [owner, repo]);
12
+
13
+ async function loadAssets() {
14
+ if (!canUse) return;
15
+ setError("");
16
+ try {
17
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${repo}/context/assets`));
18
+ if (!res.ok) throw new Error(`Failed to list assets (${res.status})`);
19
+ const data = await res.json();
20
+ setAssets(data.assets || []);
21
+ } catch (e) {
22
+ setError(e?.message || "Failed to load assets");
23
+ }
24
+ }
25
+
26
+ useEffect(() => {
27
+ loadAssets();
28
+ // eslint-disable-next-line react-hooks/exhaustive-deps
29
+ }, [owner, repo]);
30
+
31
+ async function uploadFiles(fileList) {
32
+ if (!canUse) return;
33
+ const files = Array.from(fileList || []);
34
+ if (!files.length) return;
35
+
36
+ setBusy(true);
37
+ setError("");
38
+ setUploadHint(`Uploading ${files.length} file(s)...`);
39
+
40
+ try {
41
+ for (const f of files) {
42
+ const form = new FormData();
43
+ form.append("file", f);
44
+
45
+ const res = await fetch(
46
+ `/api/repos/${owner}/${repo}/context/assets/upload`,
47
+ { method: "POST", body: form }
48
+ );
49
+ if (!res.ok) {
50
+ const txt = await res.text().catch(() => "");
51
+ throw new Error(`Upload failed (${res.status}) ${txt}`);
52
+ }
53
+ }
54
+ setUploadHint("Upload complete. Refreshing list...");
55
+ await loadAssets();
56
+ setUploadHint("");
57
+ } catch (e) {
58
+ setError(e?.message || "Upload failed");
59
+ setUploadHint("");
60
+ } finally {
61
+ setBusy(false);
62
+ if (inputRef.current) inputRef.current.value = "";
63
+ }
64
+ }
65
+
66
+ async function deleteAsset(assetId) {
67
+ if (!canUse) return;
68
+ const ok = window.confirm("Delete this asset? This cannot be undone.");
69
+ if (!ok) return;
70
+
71
+ setBusy(true);
72
+ setError("");
73
+ try {
74
+ const res = await fetch(
75
+ `/api/repos/${owner}/${repo}/context/assets/${assetId}`,
76
+ { method: "DELETE" }
77
+ );
78
+ if (!res.ok) throw new Error(`Delete failed (${res.status})`);
79
+ await loadAssets();
80
+ } catch (e) {
81
+ setError(e?.message || "Delete failed");
82
+ } finally {
83
+ setBusy(false);
84
+ }
85
+ }
86
+
87
+ function downloadAsset(assetId) {
88
+ if (!canUse) return;
89
+ window.open(
90
+ `/api/repos/${owner}/${repo}/context/assets/${assetId}/download`,
91
+ "_blank"
92
+ );
93
+ }
94
+
95
+ const empty = !assets || assets.length === 0;
96
+
97
+ return (
98
+ <div style={styles.wrap}>
99
+ <div style={styles.topRow}>
100
+ <div style={styles.left}>
101
+ <div style={styles.h1}>Project Context</div>
102
+ <div style={styles.h2}>
103
+ Upload documents, transcripts, screenshots, etc. (non-destructive,
104
+ additive).
105
+ </div>
106
+ </div>
107
+
108
+ <div style={styles.right}>
109
+ <input
110
+ ref={inputRef}
111
+ type="file"
112
+ multiple
113
+ disabled={!canUse || busy}
114
+ onChange={(e) => uploadFiles(e.target.files)}
115
+ style={styles.fileInput}
116
+ />
117
+ <button
118
+ style={styles.btn}
119
+ disabled={!canUse || busy}
120
+ onClick={() => inputRef.current?.click()}
121
+ >
122
+ Upload
123
+ </button>
124
+ <button
125
+ style={styles.btn}
126
+ disabled={!canUse || busy}
127
+ onClick={loadAssets}
128
+ >
129
+ Refresh
130
+ </button>
131
+ </div>
132
+ </div>
133
+
134
+ <div
135
+ style={styles.dropzone}
136
+ onDragOver={(e) => {
137
+ e.preventDefault();
138
+ e.stopPropagation();
139
+ }}
140
+ onDrop={(e) => {
141
+ e.preventDefault();
142
+ e.stopPropagation();
143
+ if (busy) return;
144
+ uploadFiles(e.dataTransfer.files);
145
+ }}
146
+ >
147
+ <div style={styles.dropText}>
148
+ Drag & drop files here, or click <b>Upload</b>.
149
+ </div>
150
+ <div style={styles.dropSub}>
151
+ Tip: For audio/video, upload a transcript file too.
152
+ </div>
153
+ </div>
154
+
155
+ {uploadHint ? <div style={styles.hint}>{uploadHint}</div> : null}
156
+ {error ? <div style={styles.error}>{error}</div> : null}
157
+
158
+ <div style={styles.tableWrap}>
159
+ <div style={styles.tableHeader}>
160
+ <div style={{ ...styles.col, ...styles.colName }}>File</div>
161
+ <div style={{ ...styles.col, ...styles.colMeta }}>Type</div>
162
+ <div style={{ ...styles.col, ...styles.colMeta }}>Size</div>
163
+ <div style={{ ...styles.col, ...styles.colMeta }}>Indexed</div>
164
+ <div style={{ ...styles.col, ...styles.colActions }}>Actions</div>
165
+ </div>
166
+
167
+ {empty ? (
168
+ <div style={styles.empty}>
169
+ No context assets yet. Upload docs, transcripts, and screenshots to
170
+ improve planning quality.
171
+ </div>
172
+ ) : (
173
+ assets.map((a) => (
174
+ <div key={a.asset_id} style={styles.row}>
175
+ <div style={{ ...styles.col, ...styles.colName }}>
176
+ <div style={styles.fileName}>{a.filename}</div>
177
+ <div style={styles.small}>
178
+ Added: {a.created_at || "-"} | Extracted:{" "}
179
+ {Number(a.extracted_chars || 0).toLocaleString()} chars
180
+ </div>
181
+ </div>
182
+
183
+ <div style={{ ...styles.col, ...styles.colMeta }}>
184
+ <span style={styles.badge}>{a.mime || "unknown"}</span>
185
+ </div>
186
+
187
+ <div style={{ ...styles.col, ...styles.colMeta }}>
188
+ {formatBytes(a.size_bytes || 0)}
189
+ </div>
190
+
191
+ <div style={{ ...styles.col, ...styles.colMeta }}>
192
+ {a.indexed_chunks || 0} chunks
193
+ </div>
194
+
195
+ <div style={{ ...styles.col, ...styles.colActions }}>
196
+ <button
197
+ style={styles.smallBtn}
198
+ disabled={busy}
199
+ onClick={() => downloadAsset(a.asset_id)}
200
+ >
201
+ Download
202
+ </button>
203
+ <button
204
+ style={{ ...styles.smallBtn, ...styles.dangerBtn }}
205
+ disabled={busy}
206
+ onClick={() => deleteAsset(a.asset_id)}
207
+ >
208
+ Delete
209
+ </button>
210
+ </div>
211
+ </div>
212
+ ))
213
+ )}
214
+ </div>
215
+ </div>
216
+ );
217
+ }
218
+
219
+ function formatBytes(bytes) {
220
+ const b = Number(bytes || 0);
221
+ if (!b) return "0 B";
222
+ const units = ["B", "KB", "MB", "GB", "TB"];
223
+ let i = 0;
224
+ let v = b;
225
+ while (v >= 1024 && i < units.length - 1) {
226
+ v /= 1024;
227
+ i += 1;
228
+ }
229
+ return `${v.toFixed(v >= 10 || i === 0 ? 0 : 1)} ${units[i]}`;
230
+ }
231
+
232
+ const styles = {
233
+ wrap: { display: "flex", flexDirection: "column", gap: 12 },
234
+ topRow: {
235
+ display: "flex",
236
+ justifyContent: "space-between",
237
+ gap: 12,
238
+ alignItems: "flex-start",
239
+ flexWrap: "wrap",
240
+ },
241
+ left: { minWidth: 280 },
242
+ right: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" },
243
+ h1: { fontSize: 14, fontWeight: 800, color: "#fff" },
244
+ h2: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 4 },
245
+ fileInput: { display: "none" },
246
+ btn: {
247
+ background: "rgba(255,255,255,0.10)",
248
+ border: "1px solid rgba(255,255,255,0.18)",
249
+ color: "#fff",
250
+ borderRadius: 10,
251
+ padding: "8px 10px",
252
+ cursor: "pointer",
253
+ fontSize: 13,
254
+ },
255
+ dropzone: {
256
+ border: "1px dashed rgba(255,255,255,0.22)",
257
+ borderRadius: 12,
258
+ padding: 16,
259
+ background: "rgba(255,255,255,0.03)",
260
+ },
261
+ dropText: { color: "rgba(255,255,255,0.85)", fontSize: 13 },
262
+ dropSub: { color: "rgba(255,255,255,0.55)", fontSize: 12, marginTop: 6 },
263
+ hint: {
264
+ color: "rgba(255,255,255,0.75)",
265
+ fontSize: 12,
266
+ padding: "8px 10px",
267
+ border: "1px solid rgba(255,255,255,0.12)",
268
+ borderRadius: 10,
269
+ background: "rgba(255,255,255,0.03)",
270
+ },
271
+ error: {
272
+ color: "#ffb3b3",
273
+ fontSize: 12,
274
+ padding: "8px 10px",
275
+ border: "1px solid rgba(255,120,120,0.25)",
276
+ borderRadius: 10,
277
+ background: "rgba(255,80,80,0.08)",
278
+ },
279
+ tableWrap: {
280
+ border: "1px solid rgba(255,255,255,0.12)",
281
+ borderRadius: 12,
282
+ overflow: "hidden",
283
+ },
284
+ tableHeader: {
285
+ display: "grid",
286
+ gridTemplateColumns: "1.6fr 1fr 0.6fr 0.6fr 0.8fr",
287
+ gap: 0,
288
+ padding: "10px 12px",
289
+ background: "rgba(255,255,255,0.03)",
290
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
291
+ fontSize: 12,
292
+ color: "rgba(255,255,255,0.65)",
293
+ },
294
+ row: {
295
+ display: "grid",
296
+ gridTemplateColumns: "1.6fr 1fr 0.6fr 0.6fr 0.8fr",
297
+ padding: "10px 12px",
298
+ borderBottom: "1px solid rgba(255,255,255,0.08)",
299
+ alignItems: "center",
300
+ },
301
+ col: { minWidth: 0 },
302
+ colName: {},
303
+ colMeta: { color: "rgba(255,255,255,0.75)", fontSize: 12 },
304
+ colActions: { display: "flex", gap: 8, justifyContent: "flex-end" },
305
+ fileName: {
306
+ color: "#fff",
307
+ fontSize: 13,
308
+ fontWeight: 700,
309
+ overflow: "hidden",
310
+ textOverflow: "ellipsis",
311
+ whiteSpace: "nowrap",
312
+ },
313
+ small: {
314
+ color: "rgba(255,255,255,0.55)",
315
+ fontSize: 11,
316
+ marginTop: 4,
317
+ overflow: "hidden",
318
+ textOverflow: "ellipsis",
319
+ whiteSpace: "nowrap",
320
+ },
321
+ badge: {
322
+ display: "inline-flex",
323
+ alignItems: "center",
324
+ padding: "2px 8px",
325
+ borderRadius: 999,
326
+ border: "1px solid rgba(255,255,255,0.16)",
327
+ background: "rgba(255,255,255,0.04)",
328
+ fontSize: 11,
329
+ color: "rgba(255,255,255,0.80)",
330
+ maxWidth: "100%",
331
+ overflow: "hidden",
332
+ textOverflow: "ellipsis",
333
+ whiteSpace: "nowrap",
334
+ },
335
+ smallBtn: {
336
+ background: "rgba(255,255,255,0.08)",
337
+ border: "1px solid rgba(255,255,255,0.16)",
338
+ color: "#fff",
339
+ borderRadius: 10,
340
+ padding: "6px 8px",
341
+ cursor: "pointer",
342
+ fontSize: 12,
343
+ },
344
+ dangerBtn: {
345
+ border: "1px solid rgba(255,90,90,0.35)",
346
+ background: "rgba(255,90,90,0.10)",
347
+ },
348
+ empty: {
349
+ padding: 14,
350
+ color: "rgba(255,255,255,0.65)",
351
+ fontSize: 13,
352
+ },
353
+ };
frontend/components/ProjectSettings/ConventionsTab.jsx ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useState } from "react";
2
+ import { apiUrl } from "../../utils/api.js";
3
+
4
+ export default function ConventionsTab({ owner, repo }) {
5
+ const [content, setContent] = useState("");
6
+ const [busy, setBusy] = useState(false);
7
+ const [error, setError] = useState("");
8
+
9
+ const canUse = useMemo(() => Boolean(owner && repo), [owner, repo]);
10
+
11
+ async function load() {
12
+ if (!canUse) return;
13
+ setError("");
14
+ setBusy(true);
15
+ try {
16
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${repo}/context`));
17
+ if (!res.ok) throw new Error(`Failed to load conventions (${res.status})`);
18
+ const data = await res.json();
19
+ // backend may return { context: "..."} or { conventions: "..."} depending on implementation
20
+ setContent(data.context || data.conventions || data.memory || data.text || "");
21
+ } catch (e) {
22
+ setError(e?.message || "Failed to load conventions");
23
+ } finally {
24
+ setBusy(false);
25
+ }
26
+ }
27
+
28
+ async function initialize() {
29
+ if (!canUse) return;
30
+ setError("");
31
+ setBusy(true);
32
+ try {
33
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${repo}/context/init`), {
34
+ method: "POST",
35
+ });
36
+ if (!res.ok) {
37
+ const txt = await res.text().catch(() => "");
38
+ throw new Error(`Init failed (${res.status}) ${txt}`);
39
+ }
40
+ await load();
41
+ } catch (e) {
42
+ setError(e?.message || "Init failed");
43
+ } finally {
44
+ setBusy(false);
45
+ }
46
+ }
47
+
48
+ useEffect(() => {
49
+ load();
50
+ // eslint-disable-next-line react-hooks/exhaustive-deps
51
+ }, [owner, repo]);
52
+
53
+ return (
54
+ <div style={styles.wrap}>
55
+ <div style={styles.topRow}>
56
+ <div>
57
+ <div style={styles.h1}>Project Conventions</div>
58
+ <div style={styles.h2}>
59
+ This is the project memory/conventions file used by GitPilot.
60
+ </div>
61
+ </div>
62
+ <div style={styles.actions}>
63
+ <button style={styles.btn} disabled={!canUse || busy} onClick={load}>
64
+ Refresh
65
+ </button>
66
+ <button
67
+ style={styles.btn}
68
+ disabled={!canUse || busy}
69
+ onClick={initialize}
70
+ >
71
+ Initialize
72
+ </button>
73
+ </div>
74
+ </div>
75
+
76
+ {error ? <div style={styles.error}>{error}</div> : null}
77
+
78
+ <div style={styles.box}>
79
+ {content ? (
80
+ <pre style={styles.pre}>{content}</pre>
81
+ ) : (
82
+ <div style={styles.empty}>
83
+ No conventions found yet. Click <b>Initialize</b> to create default
84
+ project memory if supported.
85
+ </div>
86
+ )}
87
+ </div>
88
+
89
+ <div style={styles.note}>
90
+ Editing conventions is intentionally not included here to keep this
91
+ feature additive/non-destructive. You can extend this later with an
92
+ explicit &quot;Edit&quot; mode.
93
+ </div>
94
+ </div>
95
+ );
96
+ }
97
+
98
+ const styles = {
99
+ wrap: { display: "flex", flexDirection: "column", gap: 12 },
100
+ topRow: {
101
+ display: "flex",
102
+ justifyContent: "space-between",
103
+ gap: 12,
104
+ alignItems: "flex-start",
105
+ flexWrap: "wrap",
106
+ },
107
+ actions: { display: "flex", gap: 8, flexWrap: "wrap" },
108
+ h1: { fontSize: 14, fontWeight: 800, color: "#fff" },
109
+ h2: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 4 },
110
+ btn: {
111
+ background: "rgba(255,255,255,0.10)",
112
+ border: "1px solid rgba(255,255,255,0.18)",
113
+ color: "#fff",
114
+ borderRadius: 10,
115
+ padding: "8px 10px",
116
+ cursor: "pointer",
117
+ fontSize: 13,
118
+ },
119
+ error: {
120
+ color: "#ffb3b3",
121
+ fontSize: 12,
122
+ padding: "8px 10px",
123
+ border: "1px solid rgba(255,120,120,0.25)",
124
+ borderRadius: 10,
125
+ background: "rgba(255,80,80,0.08)",
126
+ },
127
+ box: {
128
+ border: "1px solid rgba(255,255,255,0.12)",
129
+ borderRadius: 12,
130
+ overflow: "hidden",
131
+ background: "rgba(0,0,0,0.22)",
132
+ },
133
+ pre: {
134
+ margin: 0,
135
+ padding: 12,
136
+ color: "rgba(255,255,255,0.85)",
137
+ fontSize: 12,
138
+ lineHeight: 1.35,
139
+ whiteSpace: "pre-wrap",
140
+ overflow: "auto",
141
+ maxHeight: 520,
142
+ },
143
+ empty: {
144
+ padding: 12,
145
+ color: "rgba(255,255,255,0.65)",
146
+ fontSize: 13,
147
+ },
148
+ note: {
149
+ color: "rgba(255,255,255,0.55)",
150
+ fontSize: 12,
151
+ },
152
+ };
frontend/components/ProjectSettings/UseCaseTab.jsx ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useRef, useState } from "react";
2
+ import { apiUrl } from "../../utils/api.js";
3
+
4
+ export default function UseCaseTab({ owner, repo }) {
5
+ const [useCases, setUseCases] = useState([]);
6
+ const [selectedId, setSelectedId] = useState("");
7
+ const [useCase, setUseCase] = useState(null);
8
+ const [busy, setBusy] = useState(false);
9
+ const [error, setError] = useState("");
10
+ const [draftTitle, setDraftTitle] = useState("New Use Case");
11
+ const [message, setMessage] = useState("");
12
+ const messagesEndRef = useRef(null);
13
+
14
+ const canUse = useMemo(() => Boolean(owner && repo), [owner, repo]);
15
+ const spec = useCase?.spec || {};
16
+
17
+ function scrollToBottom() {
18
+ requestAnimationFrame(() => {
19
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
20
+ });
21
+ }
22
+
23
+ async function loadUseCases() {
24
+ if (!canUse) return;
25
+ setError("");
26
+ try {
27
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${repo}/use-cases`));
28
+ if (!res.ok) throw new Error(`Failed to list use cases (${res.status})`);
29
+ const data = await res.json();
30
+ const list = data.use_cases || [];
31
+ setUseCases(list);
32
+
33
+ // auto select active or first
34
+ const active = list.find((x) => x.is_active);
35
+ const nextId = active?.use_case_id || list[0]?.use_case_id || "";
36
+ if (!selectedId && nextId) setSelectedId(nextId);
37
+ } catch (e) {
38
+ setError(e?.message || "Failed to load use cases");
39
+ }
40
+ }
41
+
42
+ async function loadUseCase(id) {
43
+ if (!canUse || !id) return;
44
+ setError("");
45
+ try {
46
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${repo}/use-cases/${id}`));
47
+ if (!res.ok) throw new Error(`Failed to load use case (${res.status})`);
48
+ const data = await res.json();
49
+ setUseCase(data.use_case || null);
50
+ scrollToBottom();
51
+ } catch (e) {
52
+ setError(e?.message || "Failed to load use case");
53
+ }
54
+ }
55
+
56
+ useEffect(() => {
57
+ loadUseCases();
58
+ // eslint-disable-next-line react-hooks/exhaustive-deps
59
+ }, [owner, repo]);
60
+
61
+ useEffect(() => {
62
+ if (!selectedId) return;
63
+ loadUseCase(selectedId);
64
+ // eslint-disable-next-line react-hooks/exhaustive-deps
65
+ }, [selectedId]);
66
+
67
+ async function createUseCase() {
68
+ if (!canUse) return;
69
+ setBusy(true);
70
+ setError("");
71
+ try {
72
+ const res = await fetch(apiUrl(`/api/repos/${owner}/${repo}/use-cases`), {
73
+ method: "POST",
74
+ headers: { "Content-Type": "application/json" },
75
+ body: JSON.stringify({ title: draftTitle || "New Use Case" }),
76
+ });
77
+ if (!res.ok) {
78
+ const txt = await res.text().catch(() => "");
79
+ throw new Error(`Create failed (${res.status}) ${txt}`);
80
+ }
81
+ const data = await res.json();
82
+ const id = data?.use_case?.use_case_id;
83
+ await loadUseCases();
84
+ if (id) setSelectedId(id);
85
+ setDraftTitle("New Use Case");
86
+ } catch (e) {
87
+ setError(e?.message || "Create failed");
88
+ } finally {
89
+ setBusy(false);
90
+ }
91
+ }
92
+
93
+ async function sendMessage() {
94
+ if (!canUse || !selectedId) return;
95
+ const msg = (message || "").trim();
96
+ if (!msg) return;
97
+
98
+ setBusy(true);
99
+ setError("");
100
+
101
+ // optimistic UI: append user message immediately
102
+ setUseCase((prev) => {
103
+ if (!prev) return prev;
104
+ const next = { ...prev };
105
+ next.messages = Array.isArray(next.messages) ? [...next.messages] : [];
106
+ next.messages.push({ role: "user", content: msg, ts: new Date().toISOString() });
107
+ return next;
108
+ });
109
+ setMessage("");
110
+ scrollToBottom();
111
+
112
+ try {
113
+ const res = await fetch(
114
+ `/api/repos/${owner}/${repo}/use-cases/${selectedId}/chat`,
115
+ {
116
+ method: "POST",
117
+ headers: { "Content-Type": "application/json" },
118
+ body: JSON.stringify({ message: msg }),
119
+ }
120
+ );
121
+ if (!res.ok) {
122
+ const txt = await res.text().catch(() => "");
123
+ throw new Error(`Chat failed (${res.status}) ${txt}`);
124
+ }
125
+ const data = await res.json();
126
+ setUseCase(data.use_case || null);
127
+ await loadUseCases();
128
+ scrollToBottom();
129
+ } catch (e) {
130
+ setError(e?.message || "Chat failed");
131
+ } finally {
132
+ setBusy(false);
133
+ }
134
+ }
135
+
136
+ async function finalizeUseCase() {
137
+ if (!canUse || !selectedId) return;
138
+ setBusy(true);
139
+ setError("");
140
+ try {
141
+ const res = await fetch(
142
+ `/api/repos/${owner}/${repo}/use-cases/${selectedId}/finalize`,
143
+ { method: "POST" }
144
+ );
145
+ if (!res.ok) {
146
+ const txt = await res.text().catch(() => "");
147
+ throw new Error(`Finalize failed (${res.status}) ${txt}`);
148
+ }
149
+ const data = await res.json();
150
+ setUseCase(data.use_case || null);
151
+ await loadUseCases();
152
+ alert(
153
+ "Use Case finalized and marked active.\n\nA Markdown export was saved in the repo workspace .gitpilot/context/use_cases/."
154
+ );
155
+ } catch (e) {
156
+ setError(e?.message || "Finalize failed");
157
+ } finally {
158
+ setBusy(false);
159
+ }
160
+ }
161
+
162
+ const activeId = useCases.find((x) => x.is_active)?.use_case_id;
163
+
164
+ return (
165
+ <div style={styles.wrap}>
166
+ <div style={styles.topRow}>
167
+ <div style={styles.left}>
168
+ <div style={styles.h1}>Use Case</div>
169
+ <div style={styles.h2}>
170
+ Guided chat to clarify requirements and produce a versioned spec.
171
+ </div>
172
+ </div>
173
+
174
+ <div style={styles.right}>
175
+ <input
176
+ value={draftTitle}
177
+ onChange={(e) => setDraftTitle(e.target.value)}
178
+ placeholder="New use case title..."
179
+ style={styles.titleInput}
180
+ disabled={!canUse || busy}
181
+ />
182
+ <button
183
+ style={styles.btn}
184
+ onClick={createUseCase}
185
+ disabled={!canUse || busy}
186
+ >
187
+ New
188
+ </button>
189
+ <button
190
+ style={styles.btn}
191
+ onClick={finalizeUseCase}
192
+ disabled={!canUse || busy || !selectedId}
193
+ >
194
+ Finalize
195
+ </button>
196
+ <button
197
+ style={styles.btn}
198
+ onClick={loadUseCases}
199
+ disabled={!canUse || busy}
200
+ >
201
+ Refresh
202
+ </button>
203
+ </div>
204
+ </div>
205
+
206
+ {error ? <div style={styles.error}>{error}</div> : null}
207
+
208
+ <div style={styles.grid}>
209
+ <div style={styles.sidebar}>
210
+ <div style={styles.sidebarTitle}>Use Cases</div>
211
+ <div style={styles.sidebarList}>
212
+ {useCases.length === 0 ? (
213
+ <div style={styles.sidebarEmpty}>
214
+ No use cases yet. Create one with <b>New</b>.
215
+ </div>
216
+ ) : (
217
+ useCases.map((uc) => (
218
+ <button
219
+ key={uc.use_case_id}
220
+ style={{
221
+ ...styles.ucItem,
222
+ ...(selectedId === uc.use_case_id ? styles.ucItemActive : {}),
223
+ }}
224
+ onClick={() => setSelectedId(uc.use_case_id)}
225
+ >
226
+ <div style={styles.ucTitleRow}>
227
+ <div style={styles.ucTitle}>
228
+ {uc.title || "(untitled)"}
229
+ </div>
230
+ {uc.use_case_id === activeId ? (
231
+ <span style={styles.activePill}>ACTIVE</span>
232
+ ) : null}
233
+ </div>
234
+ <div style={styles.ucMeta}>
235
+ Updated: {uc.updated_at || uc.created_at || "-"}
236
+ </div>
237
+ </button>
238
+ ))
239
+ )}
240
+ </div>
241
+ </div>
242
+
243
+ <div style={styles.chatCol}>
244
+ <div style={styles.panelTitle}>Guided Chat</div>
245
+ <div style={styles.chatBox}>
246
+ {Array.isArray(useCase?.messages) && useCase.messages.length ? (
247
+ useCase.messages.map((m, idx) => (
248
+ <div
249
+ key={idx}
250
+ style={{
251
+ ...styles.msg,
252
+ ...(m.role === "user" ? styles.msgUser : styles.msgAsst),
253
+ }}
254
+ >
255
+ <div style={styles.msgRole}>
256
+ {m.role === "user" ? "You" : "Assistant"}
257
+ </div>
258
+ <div style={styles.msgContent}>{m.content}</div>
259
+ </div>
260
+ ))
261
+ ) : (
262
+ <div style={styles.chatEmpty}>
263
+ Select a use case and start chatting. You can paste structured
264
+ info like:
265
+ <pre style={styles.pre}>
266
+ {`Summary: ...
267
+ Problem: ...
268
+ Users: ...
269
+ Requirements:
270
+ - ...
271
+ Acceptance Criteria:
272
+ - ...`}
273
+ </pre>
274
+ </div>
275
+ )}
276
+ <div ref={messagesEndRef} />
277
+ </div>
278
+
279
+ <div style={styles.composer}>
280
+ <textarea
281
+ value={message}
282
+ onChange={(e) => setMessage(e.target.value)}
283
+ placeholder="Type your answer... (Shift+Enter for newline)"
284
+ style={styles.textarea}
285
+ disabled={!canUse || busy || !selectedId}
286
+ onKeyDown={(e) => {
287
+ if (e.key === "Enter" && !e.shiftKey) {
288
+ e.preventDefault();
289
+ sendMessage();
290
+ }
291
+ }}
292
+ />
293
+ <button
294
+ style={styles.sendBtn}
295
+ disabled={!canUse || busy || !selectedId}
296
+ onClick={sendMessage}
297
+ >
298
+ Send
299
+ </button>
300
+ </div>
301
+ </div>
302
+
303
+ <div style={styles.specCol}>
304
+ <div style={styles.panelTitle}>Spec Preview</div>
305
+ <div style={styles.specBox}>
306
+ <Section title="Title" value={spec.title || useCase?.title || ""} />
307
+ <Section title="Summary" value={spec.summary || ""} />
308
+ <Section title="Problem" value={spec.problem || ""} />
309
+ <Section title="Users / Personas" value={spec.users || ""} />
310
+ <ListSection title="Requirements" items={spec.requirements || []} />
311
+ <ListSection
312
+ title="Acceptance Criteria"
313
+ items={spec.acceptance_criteria || []}
314
+ />
315
+ <ListSection title="Constraints" items={spec.constraints || []} />
316
+ <ListSection title="Open Questions" items={spec.open_questions || []} />
317
+ <Section title="Notes" value={spec.notes || ""} />
318
+ </div>
319
+
320
+ <div style={styles.specFooter}>
321
+ <div style={styles.specHint}>
322
+ Finalize will save a Markdown spec and mark it ACTIVE for context.
323
+ </div>
324
+ <button
325
+ style={styles.primaryBtn}
326
+ disabled={!canUse || busy || !selectedId}
327
+ onClick={finalizeUseCase}
328
+ >
329
+ Finalize Spec
330
+ </button>
331
+ </div>
332
+ </div>
333
+ </div>
334
+ </div>
335
+ );
336
+ }
337
+
338
+ function Section({ title, value }) {
339
+ return (
340
+ <div style={styles.section}>
341
+ <div style={styles.sectionTitle}>{title}</div>
342
+ <div style={styles.sectionBody}>
343
+ {String(value || "").trim() ? (
344
+ <div style={styles.sectionText}>{value}</div>
345
+ ) : (
346
+ <div style={styles.sectionEmpty}>(empty)</div>
347
+ )}
348
+ </div>
349
+ </div>
350
+ );
351
+ }
352
+
353
+ function ListSection({ title, items }) {
354
+ const list = Array.isArray(items) ? items : [];
355
+ return (
356
+ <div style={styles.section}>
357
+ <div style={styles.sectionTitle}>{title}</div>
358
+ <div style={styles.sectionBody}>
359
+ {list.length ? (
360
+ <ul style={styles.ul}>
361
+ {list.map((x, i) => (
362
+ <li key={i} style={styles.li}>
363
+ {x}
364
+ </li>
365
+ ))}
366
+ </ul>
367
+ ) : (
368
+ <div style={styles.sectionEmpty}>(empty)</div>
369
+ )}
370
+ </div>
371
+ </div>
372
+ );
373
+ }
374
+
375
+ const styles = {
376
+ wrap: { display: "flex", flexDirection: "column", gap: 12 },
377
+ topRow: {
378
+ display: "flex",
379
+ justifyContent: "space-between",
380
+ gap: 12,
381
+ alignItems: "flex-start",
382
+ flexWrap: "wrap",
383
+ },
384
+ left: { minWidth: 280 },
385
+ right: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" },
386
+ h1: { fontSize: 14, fontWeight: 800, color: "#fff" },
387
+ h2: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 4 },
388
+ titleInput: {
389
+ width: 260,
390
+ maxWidth: "70vw",
391
+ padding: "8px 10px",
392
+ borderRadius: 10,
393
+ border: "1px solid rgba(255,255,255,0.18)",
394
+ background: "rgba(0,0,0,0.25)",
395
+ color: "#fff",
396
+ fontSize: 13,
397
+ outline: "none",
398
+ },
399
+ btn: {
400
+ background: "rgba(255,255,255,0.10)",
401
+ border: "1px solid rgba(255,255,255,0.18)",
402
+ color: "#fff",
403
+ borderRadius: 10,
404
+ padding: "8px 10px",
405
+ cursor: "pointer",
406
+ fontSize: 13,
407
+ },
408
+ primaryBtn: {
409
+ background: "rgba(255,255,255,0.12)",
410
+ border: "1px solid rgba(255,255,255,0.22)",
411
+ color: "#fff",
412
+ borderRadius: 10,
413
+ padding: "8px 12px",
414
+ cursor: "pointer",
415
+ fontSize: 13,
416
+ fontWeight: 700,
417
+ },
418
+ error: {
419
+ color: "#ffb3b3",
420
+ fontSize: 12,
421
+ padding: "8px 10px",
422
+ border: "1px solid rgba(255,120,120,0.25)",
423
+ borderRadius: 10,
424
+ background: "rgba(255,80,80,0.08)",
425
+ },
426
+ grid: {
427
+ display: "grid",
428
+ gridTemplateColumns: "300px 1.2fr 0.9fr",
429
+ gap: 12,
430
+ alignItems: "stretch",
431
+ },
432
+ sidebar: {
433
+ border: "1px solid rgba(255,255,255,0.12)",
434
+ borderRadius: 12,
435
+ overflow: "hidden",
436
+ background: "rgba(255,255,255,0.02)",
437
+ display: "flex",
438
+ flexDirection: "column",
439
+ minHeight: 520,
440
+ },
441
+ sidebarTitle: {
442
+ padding: 10,
443
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
444
+ fontSize: 12,
445
+ fontWeight: 800,
446
+ color: "rgba(255,255,255,0.85)",
447
+ },
448
+ sidebarList: {
449
+ padding: 8,
450
+ display: "flex",
451
+ flexDirection: "column",
452
+ gap: 8,
453
+ overflow: "auto",
454
+ },
455
+ sidebarEmpty: {
456
+ color: "rgba(255,255,255,0.65)",
457
+ fontSize: 12,
458
+ padding: 8,
459
+ },
460
+ ucItem: {
461
+ textAlign: "left",
462
+ background: "rgba(0,0,0,0.25)",
463
+ border: "1px solid rgba(255,255,255,0.12)",
464
+ color: "#fff",
465
+ borderRadius: 12,
466
+ padding: 10,
467
+ cursor: "pointer",
468
+ },
469
+ ucItemActive: {
470
+ border: "1px solid rgba(255,255,255,0.25)",
471
+ background: "rgba(255,255,255,0.06)",
472
+ },
473
+ ucTitleRow: { display: "flex", alignItems: "center", gap: 8 },
474
+ ucTitle: {
475
+ fontSize: 13,
476
+ fontWeight: 800,
477
+ overflow: "hidden",
478
+ textOverflow: "ellipsis",
479
+ whiteSpace: "nowrap",
480
+ flex: 1,
481
+ },
482
+ activePill: {
483
+ fontSize: 10,
484
+ fontWeight: 800,
485
+ padding: "2px 8px",
486
+ borderRadius: 999,
487
+ border: "1px solid rgba(120,255,180,0.30)",
488
+ background: "rgba(120,255,180,0.10)",
489
+ color: "rgba(200,255,220,0.95)",
490
+ },
491
+ ucMeta: {
492
+ marginTop: 6,
493
+ fontSize: 11,
494
+ color: "rgba(255,255,255,0.60)",
495
+ },
496
+ chatCol: {
497
+ border: "1px solid rgba(255,255,255,0.12)",
498
+ borderRadius: 12,
499
+ overflow: "hidden",
500
+ display: "flex",
501
+ flexDirection: "column",
502
+ background: "rgba(255,255,255,0.02)",
503
+ minHeight: 520,
504
+ },
505
+ specCol: {
506
+ border: "1px solid rgba(255,255,255,0.12)",
507
+ borderRadius: 12,
508
+ overflow: "hidden",
509
+ display: "flex",
510
+ flexDirection: "column",
511
+ background: "rgba(255,255,255,0.02)",
512
+ minHeight: 520,
513
+ },
514
+ panelTitle: {
515
+ padding: 10,
516
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
517
+ fontSize: 12,
518
+ fontWeight: 800,
519
+ color: "rgba(255,255,255,0.85)",
520
+ },
521
+ chatBox: {
522
+ flex: 1,
523
+ overflow: "auto",
524
+ padding: 10,
525
+ display: "flex",
526
+ flexDirection: "column",
527
+ gap: 10,
528
+ },
529
+ chatEmpty: {
530
+ color: "rgba(255,255,255,0.65)",
531
+ fontSize: 12,
532
+ padding: 6,
533
+ },
534
+ pre: {
535
+ marginTop: 10,
536
+ padding: 10,
537
+ borderRadius: 10,
538
+ border: "1px solid rgba(255,255,255,0.12)",
539
+ background: "rgba(0,0,0,0.25)",
540
+ color: "rgba(255,255,255,0.8)",
541
+ overflow: "auto",
542
+ fontSize: 11,
543
+ },
544
+ msg: {
545
+ border: "1px solid rgba(255,255,255,0.12)",
546
+ borderRadius: 12,
547
+ padding: 10,
548
+ background: "rgba(0,0,0,0.25)",
549
+ },
550
+ msgUser: {
551
+ border: "1px solid rgba(255,255,255,0.18)",
552
+ background: "rgba(255,255,255,0.04)",
553
+ },
554
+ msgAsst: {},
555
+ msgRole: {
556
+ fontSize: 11,
557
+ fontWeight: 800,
558
+ color: "rgba(255,255,255,0.70)",
559
+ marginBottom: 6,
560
+ },
561
+ msgContent: {
562
+ whiteSpace: "pre-wrap",
563
+ fontSize: 13,
564
+ color: "rgba(255,255,255,0.90)",
565
+ lineHeight: 1.35,
566
+ },
567
+ composer: {
568
+ borderTop: "1px solid rgba(255,255,255,0.10)",
569
+ padding: 10,
570
+ display: "flex",
571
+ gap: 10,
572
+ alignItems: "flex-end",
573
+ },
574
+ textarea: {
575
+ flex: 1,
576
+ minHeight: 52,
577
+ maxHeight: 120,
578
+ resize: "vertical",
579
+ padding: 10,
580
+ borderRadius: 12,
581
+ border: "1px solid rgba(255,255,255,0.18)",
582
+ background: "rgba(0,0,0,0.25)",
583
+ color: "#fff",
584
+ fontSize: 13,
585
+ outline: "none",
586
+ },
587
+ sendBtn: {
588
+ background: "rgba(255,255,255,0.12)",
589
+ border: "1px solid rgba(255,255,255,0.22)",
590
+ color: "#fff",
591
+ borderRadius: 12,
592
+ padding: "10px 12px",
593
+ cursor: "pointer",
594
+ fontSize: 13,
595
+ fontWeight: 800,
596
+ },
597
+ specBox: {
598
+ flex: 1,
599
+ overflow: "auto",
600
+ padding: 10,
601
+ display: "flex",
602
+ flexDirection: "column",
603
+ gap: 10,
604
+ },
605
+ specFooter: {
606
+ borderTop: "1px solid rgba(255,255,255,0.10)",
607
+ padding: 10,
608
+ display: "flex",
609
+ gap: 10,
610
+ alignItems: "center",
611
+ justifyContent: "space-between",
612
+ },
613
+ specHint: { fontSize: 12, color: "rgba(255,255,255,0.60)" },
614
+ section: {
615
+ border: "1px solid rgba(255,255,255,0.10)",
616
+ borderRadius: 12,
617
+ background: "rgba(0,0,0,0.22)",
618
+ overflow: "hidden",
619
+ },
620
+ sectionTitle: {
621
+ padding: "8px 10px",
622
+ borderBottom: "1px solid rgba(255,255,255,0.08)",
623
+ fontSize: 12,
624
+ fontWeight: 800,
625
+ color: "rgba(255,255,255,0.80)",
626
+ background: "rgba(255,255,255,0.02)",
627
+ },
628
+ sectionBody: { padding: "8px 10px" },
629
+ sectionText: {
630
+ whiteSpace: "pre-wrap",
631
+ fontSize: 12,
632
+ color: "rgba(255,255,255,0.90)",
633
+ lineHeight: 1.35,
634
+ },
635
+ sectionEmpty: { fontSize: 12, color: "rgba(255,255,255,0.45)" },
636
+ ul: { margin: 0, paddingLeft: 18 },
637
+ li: { color: "rgba(255,255,255,0.90)", fontSize: 12, lineHeight: 1.35 },
638
+ };
frontend/components/ProjectSettingsModal.jsx ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useState } from "react";
2
+ import ContextTab from "./ProjectSettings/ContextTab.jsx";
3
+ import UseCaseTab from "./ProjectSettings/UseCaseTab.jsx";
4
+ import ConventionsTab from "./ProjectSettings/ConventionsTab.jsx";
5
+ import EnvironmentSelector from "./EnvironmentSelector.jsx";
6
+
7
+ export default function ProjectSettingsModal({
8
+ owner,
9
+ repo,
10
+ isOpen,
11
+ onClose,
12
+ activeEnvId,
13
+ onEnvChange,
14
+ }) {
15
+ const [activeTab, setActiveTab] = useState("context");
16
+
17
+ useEffect(() => {
18
+ if (!isOpen) return;
19
+ // reset to Context each time opened (safe default)
20
+ setActiveTab("context");
21
+ }, [isOpen]);
22
+
23
+ const title = useMemo(() => {
24
+ const repoLabel = owner && repo ? `${owner}/${repo}` : "Project";
25
+ return `Project Settings — ${repoLabel}`;
26
+ }, [owner, repo]);
27
+
28
+ if (!isOpen) return null;
29
+
30
+ return (
31
+ <div
32
+ style={styles.backdrop}
33
+ onMouseDown={(e) => {
34
+ // click outside closes
35
+ if (e.target === e.currentTarget) onClose?.();
36
+ }}
37
+ >
38
+ <div style={styles.modal} onMouseDown={(e) => e.stopPropagation()}>
39
+ <div style={styles.header}>
40
+ <div style={styles.headerLeft}>
41
+ <div style={styles.title}>{title}</div>
42
+ <div style={styles.subtitle}>
43
+ Manage context, use cases, and project conventions (additive only).
44
+ </div>
45
+ </div>
46
+ <button style={styles.closeBtn} onClick={onClose}>
47
+ ✕
48
+ </button>
49
+ </div>
50
+
51
+ <div style={styles.tabsRow}>
52
+ <TabButton
53
+ label="Context"
54
+ isActive={activeTab === "context"}
55
+ onClick={() => setActiveTab("context")}
56
+ />
57
+ <TabButton
58
+ label="Use Case"
59
+ isActive={activeTab === "usecase"}
60
+ onClick={() => setActiveTab("usecase")}
61
+ />
62
+ <TabButton
63
+ label="Conventions"
64
+ isActive={activeTab === "conventions"}
65
+ onClick={() => setActiveTab("conventions")}
66
+ />
67
+ <TabButton
68
+ label="Environment"
69
+ isActive={activeTab === "environment"}
70
+ onClick={() => setActiveTab("environment")}
71
+ />
72
+ </div>
73
+
74
+ <div style={styles.body}>
75
+ {activeTab === "context" && <ContextTab owner={owner} repo={repo} />}
76
+ {activeTab === "usecase" && <UseCaseTab owner={owner} repo={repo} />}
77
+ {activeTab === "conventions" && (
78
+ <ConventionsTab owner={owner} repo={repo} />
79
+ )}
80
+ {activeTab === "environment" && (
81
+ <div style={{ maxWidth: 480 }}>
82
+ <div style={{ marginBottom: 12, fontSize: 13, color: "rgba(255,255,255,0.65)" }}>
83
+ Select and configure the execution environment for agent operations.
84
+ </div>
85
+ <EnvironmentSelector
86
+ activeEnvId={activeEnvId}
87
+ onEnvChange={onEnvChange}
88
+ />
89
+ </div>
90
+ )}
91
+ </div>
92
+
93
+ <div style={styles.footer}>
94
+ <div style={styles.footerHint}>
95
+ Tip: Upload meeting notes/transcripts in Context, then finalize a Use
96
+ Case spec.
97
+ </div>
98
+ <button style={styles.primaryBtn} onClick={onClose}>
99
+ Done
100
+ </button>
101
+ </div>
102
+ </div>
103
+ </div>
104
+ );
105
+ }
106
+
107
+ function TabButton({ label, isActive, onClick }) {
108
+ return (
109
+ <button
110
+ onClick={onClick}
111
+ style={{
112
+ ...styles.tabBtn,
113
+ ...(isActive ? styles.tabBtnActive : {}),
114
+ }}
115
+ >
116
+ {label}
117
+ </button>
118
+ );
119
+ }
120
+
121
+ const styles = {
122
+ backdrop: {
123
+ position: "fixed",
124
+ inset: 0,
125
+ background: "rgba(0,0,0,0.45)",
126
+ display: "flex",
127
+ justifyContent: "center",
128
+ alignItems: "center",
129
+ zIndex: 9999,
130
+ padding: 16,
131
+ },
132
+ modal: {
133
+ width: "min(1100px, 96vw)",
134
+ height: "min(760px, 90vh)",
135
+ background: "#111",
136
+ border: "1px solid rgba(255,255,255,0.12)",
137
+ borderRadius: 12,
138
+ overflow: "hidden",
139
+ display: "flex",
140
+ flexDirection: "column",
141
+ boxShadow: "0 12px 40px rgba(0,0,0,0.35)",
142
+ },
143
+ header: {
144
+ padding: "14px 14px 10px",
145
+ display: "flex",
146
+ gap: 12,
147
+ alignItems: "flex-start",
148
+ justifyContent: "space-between",
149
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
150
+ background: "linear-gradient(180deg, rgba(255,255,255,0.04), transparent)",
151
+ },
152
+ headerLeft: {
153
+ display: "flex",
154
+ flexDirection: "column",
155
+ gap: 4,
156
+ minWidth: 0,
157
+ },
158
+ title: {
159
+ fontSize: 16,
160
+ fontWeight: 700,
161
+ color: "#fff",
162
+ lineHeight: 1.2,
163
+ whiteSpace: "nowrap",
164
+ overflow: "hidden",
165
+ textOverflow: "ellipsis",
166
+ maxWidth: "88vw",
167
+ },
168
+ subtitle: {
169
+ fontSize: 12,
170
+ color: "rgba(255,255,255,0.65)",
171
+ },
172
+ closeBtn: {
173
+ background: "transparent",
174
+ border: "1px solid rgba(255,255,255,0.18)",
175
+ color: "rgba(255,255,255,0.85)",
176
+ borderRadius: 10,
177
+ padding: "6px 10px",
178
+ cursor: "pointer",
179
+ },
180
+ tabsRow: {
181
+ display: "flex",
182
+ gap: 8,
183
+ padding: 10,
184
+ borderBottom: "1px solid rgba(255,255,255,0.10)",
185
+ background: "rgba(255,255,255,0.02)",
186
+ },
187
+ tabBtn: {
188
+ background: "transparent",
189
+ border: "1px solid rgba(255,255,255,0.14)",
190
+ color: "rgba(255,255,255,0.75)",
191
+ borderRadius: 999,
192
+ padding: "8px 12px",
193
+ cursor: "pointer",
194
+ fontSize: 13,
195
+ },
196
+ tabBtnActive: {
197
+ border: "1px solid rgba(255,255,255,0.28)",
198
+ color: "#fff",
199
+ background: "rgba(255,255,255,0.06)",
200
+ },
201
+ body: {
202
+ flex: 1,
203
+ overflow: "auto",
204
+ padding: 12,
205
+ },
206
+ footer: {
207
+ padding: 12,
208
+ borderTop: "1px solid rgba(255,255,255,0.10)",
209
+ display: "flex",
210
+ alignItems: "center",
211
+ justifyContent: "space-between",
212
+ gap: 12,
213
+ background: "rgba(255,255,255,0.02)",
214
+ },
215
+ footerHint: {
216
+ color: "rgba(255,255,255,0.6)",
217
+ fontSize: 12,
218
+ overflow: "hidden",
219
+ textOverflow: "ellipsis",
220
+ whiteSpace: "nowrap",
221
+ },
222
+ primaryBtn: {
223
+ background: "rgba(255,255,255,0.10)",
224
+ border: "1px solid rgba(255,255,255,0.20)",
225
+ color: "#fff",
226
+ borderRadius: 10,
227
+ padding: "8px 12px",
228
+ cursor: "pointer",
229
+ },
230
+ };