Initial release v0.2.5

This commit is contained in:
Chris Scott committed 2025-11-23 23:25:27 -05:00
commit bbf66c259b
158 files changed
+37115

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
node_modules
*.log
.env
.env.local
dist
build
coverage
.DS_Store
*.db
*.db-shm
*.db-wal
.vscode
.idea
data
workspace
config
opencode-src
temp
.git
.github
.gitignore
*.md
!README.md
backend/data
frontend/dist
backend/dist
.cache
.turbo
*.swp
*.swo
*~
.npm
.yarn
+52
View File
@@ -0,0 +1,52 @@
# OpenCode WebUI Configuration
# Copy this file to .env and customize as needed
# ============================================
# Backend Server (Hono API)
# ============================================
PORT=8080
HOST=0.0.0.0
# ============================================
# OpenCode Server
# ============================================
OPENCODE_SERVER_PORT=5551
# ============================================
# Database
# ============================================
DATABASE_PATH=./backend/data/opencode.db
# ============================================
# Workspace Configuration
# ============================================
# Local workspace path for repositories and configs
WORKSPACE_PATH=~./workspace
# ============================================
# Timeouts (milliseconds)
# ============================================
PROCESS_START_WAIT_MS=2000
PROCESS_VERIFY_WAIT_MS=1000
HEALTH_CHECK_INTERVAL_MS=5000
HEALTH_CHECK_TIMEOUT_MS=30000
# ============================================
# File Upload Limits
# ============================================
# File size limits in MB
MAX_FILE_SIZE_MB=50
MAX_UPLOAD_SIZE_MB=50
# ============================================
# Logging
# ============================================
DEBUG=false
# ============================================
# Frontend Configuration (for development)
# ============================================
# Backend API URL - frontend connects to this
# Note: In development, Vite proxies /api requests to the backend
VITE_API_URL=http://localhost:8080
+18
View File
@@ -0,0 +1,18 @@
node_modules/
*.log
.env
.env.local
dist/
build/
coverage/
.DS_Store
*.db
*.db-shm
*.db-wal
.vscode/
.idea/
data/
workspace/
config/
+41
View File
@@ -0,0 +1,41 @@
# OpenCode WebUI - Agent Guidelines
## Commands
- `npm run dev` - Start both backend (8080) and frontend (5173)
- `npm run dev:backend` - Backend only: `bun --watch backend/src/index.ts`
- `npm run dev:frontend` - Frontend only: `cd frontend && vite`
- `npm run build` - Build both backend and frontend
- `npm run test` - Run backend tests: `cd backend && bun test`
- `cd backend && bun test <filename>` - Run single test file
- `cd backend && vitest --ui` - Test UI with coverage
- `cd backend && vitest --coverage` - Coverage report
- `cd frontend && npm run lint` - Frontend linting
## Code Style
- No comments, self-documenting code only
- Strict TypeScript everywhere, proper typing required
- Named imports only: `import { Hono } from 'hono'`, `import { useState } from 'react'`
### Backend (Bun + Hono)
- Hono framework with Zod validation
- Error handling with try/catch and logging
- Follow existing route/service/utility structure
- Use async/await consistently, avoid .then() chains
### Frontend (React + Vite)
- @/ alias for components: `import { Button } from '@/components/ui/button'`
- Radix UI + Tailwind CSS, React Hook Form + Zod
- React Query for state management
- ESLint TypeScript rules enforced
- Use React hooks properly, no direct state mutations
### General
- DRY principles, follow existing patterns
- ./opencode-src/ is reference only, never commit
- Use shared types from workspace package
- OpenCode server runs on port 5551, backend API on port 8080
+72
View File
@@ -0,0 +1,72 @@
FROM node:20 AS base
RUN apt-get update && apt-get install -y \
git \
curl \
lsof \
ripgrep \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
FROM base AS deps
COPY shared ./shared
RUN cd shared && npm install
COPY backend/package.json ./backend/package.json
RUN cd backend && npm install
COPY frontend/package.json frontend/package-lock.json* ./frontend/
RUN cd frontend && npm ci --legacy-peer-deps || npm install --legacy-peer-deps
COPY backend/src ./backend/src
COPY frontend/src ./frontend/src
COPY frontend/public ./frontend/public
COPY frontend/*.* ./frontend/
FROM base AS builder
RUN curl -fsSL https://bun.sh/install | bash && \
ln -s $HOME/.bun/bin/bun /usr/local/bin/bun
COPY --from=deps /app ./
RUN cd frontend && npm run build
RUN NODE_ENV=production bun build backend/src/index.ts --outdir=backend/dist --target=bun --packages=external
FROM base AS runner
RUN curl -fsSL https://bun.sh/install | bash && \
ln -s $HOME/.bun/bin/bun /usr/local/bin/bun
RUN curl -fsSL https://opencode.ai/install | bash && \
ln -s $HOME/.opencode/bin/opencode /usr/local/bin/opencode
ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=5001
ENV OPENCODE_SERVER_PORT=5551
ENV DATABASE_PATH=/app/backend/data/opencode.db
ENV WORKSPACE_PATH=/workspace
COPY --from=builder /app/backend/dist ./backend/dist
COPY --from=builder /app/backend/node_modules ./backend/node_modules
COPY --from=builder /app/shared/src ./shared/src
COPY --from=builder /app/shared/node_modules ./shared/node_modules
COPY --from=builder /app/shared/package.json ./shared/package.json
COPY --from=builder /app/frontend/dist ./frontend/dist
COPY scripts/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
RUN mkdir -p /workspace /app/backend/data
EXPOSE 5001
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD curl -f http://localhost:5001/api/health || exit 1
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["bun", "backend/dist/index.js"]
+74
View File
@@ -0,0 +1,74 @@
# OpenCode Web Manager
A full-stack web application for running [OpenCode](https://github.com/sst/opencode) in local processes, controllable via a modern web interface. Designed to allow users to run and control OpenCode from their phone or any device with a web browser.
## Features
- **Multi-Repository Support** - Clone and manage multiple git repos / worktrees in local workspaces
- **Web-based Interface** - Full OpenCode TUI features in the browser / Built with mobile use in mind
- **Local Environment** - Efficient local processes with isolated workspaces
- **Manage multiple repositories** - Add, remove, and switch between different code repositories
- **Designed for mobile use** - Mobile-friendly UI
- **File Browser** - Browse, edit, and manage files in your workspaces
- **Push PRs to GitHub** - Create and push pull requests directly from your phone on the go
## Coming Soon
- **Authentication** - User authentication and session management
## Installation
### Option 1: Docker (Recommended for Production)
```bash
# Clone the repository
git clone https://github.com/yourusername/opencode-webui.git
cd opencode-webui
# Start with Docker Compose (single container)
docker-compose up -d
# Access the application at http://localhost:5001
```
The Docker setup automatically:
- Installs OpenCode if not present
- Builds and serves frontend from backend
- Sets up persistent volumes for workspace and database
- Includes health checks and auto-restart
**Docker Commands:**
```bash
# Production mode (single container)
npm run docker:up # Start container
npm run docker:down # Stop and remove container
npm run docker:build # Rebuild image
npm run docker:logs # View logs
npm run docker:restart # Restart container
# Development mode (separate backend + frontend with hot reload)
npm run docker:dev # Start in dev mode
npm run docker:dev:down # Stop dev containers
# Access container shell
docker exec -it opencode-webui sh
```
### Option 2: Local Development
```bash
# Clone the repository
git clone https://github.com/yourusername/opencode-webui.git
cd opencode-webui
# Install dependencies (uses Bun workspaces)
bun install
# Copy environment configuration
cp .env.example .env
# Start development servers (backend + frontend)
npm run dev
```
+34
View File
@@ -0,0 +1,34 @@
# dependencies (bun install)
node_modules
# output
out
dist
*.tgz
# code coverage
coverage
*.lcov
# logs
logs
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# caches
.eslintcache
.cache
*.tsbuildinfo
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
+396
View File
@@ -0,0 +1,396 @@
{
"lockfileVersion": 1,
"workspaces": {
"": {
"name": "backend",
"dependencies": {
"@hono/node-server": "^1.19.5",
"dockerode": "^4.0.9",
"hono": "^4.10.1",
"zod": "^4.1.12",
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "latest",
"@types/dockerode": "^3.3.44",
"@vitest/ui": "^3.2.4",
"dockerode-mock": "^0.3.2",
"vitest": "^3.2.4",
},
"peerDependencies": {
"typescript": "^5",
},
},
},
"packages": {
"@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.11", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.11", "", { "os": "android", "cpu": "arm" }, "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.11", "", { "os": "android", "cpu": "arm64" }, "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ=="],
"@esbuild/android-x64": ["@esbuild/android-x64@0.25.11", "", { "os": "android", "cpu": "x64" }, "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g=="],
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.11", "", { "os": "darwin", "cpu": "arm64" }, "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w=="],
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.11", "", { "os": "darwin", "cpu": "x64" }, "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ=="],
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.11", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA=="],
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.11", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw=="],
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.11", "", { "os": "linux", "cpu": "arm" }, "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw=="],
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.11", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA=="],
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.11", "", { "os": "linux", "cpu": "ia32" }, "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw=="],
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.11", "", { "os": "linux", "cpu": "none" }, "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw=="],
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.11", "", { "os": "linux", "cpu": "none" }, "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ=="],
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.11", "", { "os": "linux", "cpu": "ppc64" }, "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw=="],
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.11", "", { "os": "linux", "cpu": "none" }, "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww=="],
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.11", "", { "os": "linux", "cpu": "s390x" }, "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw=="],
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.11", "", { "os": "linux", "cpu": "x64" }, "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ=="],
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.11", "", { "os": "none", "cpu": "arm64" }, "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg=="],
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.11", "", { "os": "none", "cpu": "x64" }, "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A=="],
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.11", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg=="],
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.11", "", { "os": "openbsd", "cpu": "x64" }, "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw=="],
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.25.11", "", { "os": "none", "cpu": "arm64" }, "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ=="],
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.11", "", { "os": "sunos", "cpu": "x64" }, "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA=="],
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.11", "", { "os": "win32", "cpu": "arm64" }, "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q=="],
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.11", "", { "os": "win32", "cpu": "ia32" }, "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA=="],
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.11", "", { "os": "win32", "cpu": "x64" }, "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA=="],
"@grpc/grpc-js": ["@grpc/grpc-js@1.14.0", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-N8Jx6PaYzcTRNzirReJCtADVoq4z7+1KQ4E70jTg/koQiMoUSN1kbNjPOqpPbhMFhfU1/l7ixspPl8dNY+FoUg=="],
"@grpc/proto-loader": ["@grpc/proto-loader@0.7.15", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.2.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ=="],
"@hono/node-server": ["@hono/node-server@1.19.5", "", { "peerDependencies": { "hono": "^4" } }, "sha512-iBuhh+uaaggeAuf+TftcjZyWh2GEgZcVGXkNtskLVoWaXhnJtC5HLHrU8W1KHDoucqO1MswwglmkWLFyiDn4WQ=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
"@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
"@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
"@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
"@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
"@protobufjs/codegen": ["@protobufjs/codegen@2.0.4", "", {}, "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg=="],
"@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.0", "", {}, "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q=="],
"@protobufjs/fetch": ["@protobufjs/fetch@1.1.0", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" } }, "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ=="],
"@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
"@protobufjs/inquire": ["@protobufjs/inquire@1.1.0", "", {}, "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q=="],
"@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
"@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
"@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.52.5", "", { "os": "android", "cpu": "arm" }, "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ=="],
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.52.5", "", { "os": "android", "cpu": "arm64" }, "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA=="],
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.52.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA=="],
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.52.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA=="],
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.52.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA=="],
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.52.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ=="],
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.52.5", "", { "os": "linux", "cpu": "arm" }, "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ=="],
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.52.5", "", { "os": "linux", "cpu": "arm" }, "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ=="],
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.52.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg=="],
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.52.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q=="],
"@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.52.5", "", { "os": "linux", "cpu": "none" }, "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA=="],
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.52.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw=="],
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.52.5", "", { "os": "linux", "cpu": "none" }, "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw=="],
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.52.5", "", { "os": "linux", "cpu": "none" }, "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg=="],
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.52.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ=="],
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.52.5", "", { "os": "linux", "cpu": "x64" }, "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q=="],
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.52.5", "", { "os": "linux", "cpu": "x64" }, "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg=="],
"@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.52.5", "", { "os": "none", "cpu": "arm64" }, "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw=="],
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.52.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w=="],
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.52.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg=="],
"@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.52.5", "", { "os": "win32", "cpu": "x64" }, "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ=="],
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.52.5", "", { "os": "win32", "cpu": "x64" }, "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg=="],
"@types/better-sqlite3": ["@types/better-sqlite3@7.6.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA=="],
"@types/bun": ["@types/bun@1.3.0", "", { "dependencies": { "bun-types": "1.3.0" } }, "sha512-+lAGCYjXjip2qY375xX/scJeVRmZ5cY0wyHYyCYxNcdEXrQ4AOe3gACgd4iQ8ksOslJtW4VNxBJ8llUwc3a6AA=="],
"@types/chai": ["@types/chai@5.2.2", "", { "dependencies": { "@types/deep-eql": "*" } }, "sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg=="],
"@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
"@types/docker-modem": ["@types/docker-modem@3.0.6", "", { "dependencies": { "@types/node": "*", "@types/ssh2": "*" } }, "sha512-yKpAGEuKRSS8wwx0joknWxsmLha78wNMe9R2S3UNsVOkZded8UqOrV8KoeDXoXsjndxwyF3eIhyClGbO1SEhEg=="],
"@types/dockerode": ["@types/dockerode@3.3.44", "", { "dependencies": { "@types/docker-modem": "*", "@types/node": "*", "@types/ssh2": "*" } }, "sha512-fUpIHlsbYpxAJb285xx3vp7q5wf5mjqSn3cYwl/MhiM+DB99OdO5sOCPlO0PjO+TyOtphPs7tMVLU/RtOo/JjA=="],
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/node": ["@types/node@24.8.1", "", { "dependencies": { "undici-types": "~7.14.0" } }, "sha512-alv65KGRadQVfVcG69MuB4IzdYVpRwMG/mq8KWOaoOdyY617P5ivaDiMCGOFDWD2sAn5Q0mR3mRtUOgm99hL9Q=="],
"@types/react": ["@types/react@19.2.2", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA=="],
"@types/ssh2": ["@types/ssh2@1.15.5", "", { "dependencies": { "@types/node": "^18.11.18" } }, "sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ=="],
"@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="],
"@vitest/mocker": ["@vitest/mocker@3.2.4", "", { "dependencies": { "@vitest/spy": "3.2.4", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ=="],
"@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="],
"@vitest/runner": ["@vitest/runner@3.2.4", "", { "dependencies": { "@vitest/utils": "3.2.4", "pathe": "^2.0.3", "strip-literal": "^3.0.0" } }, "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ=="],
"@vitest/snapshot": ["@vitest/snapshot@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ=="],
"@vitest/spy": ["@vitest/spy@3.2.4", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw=="],
"@vitest/ui": ["@vitest/ui@3.2.4", "", { "dependencies": { "@vitest/utils": "3.2.4", "fflate": "^0.8.2", "flatted": "^3.3.3", "pathe": "^2.0.3", "sirv": "^3.0.1", "tinyglobby": "^0.2.14", "tinyrainbow": "^2.0.0" }, "peerDependencies": { "vitest": "3.2.4" } }, "sha512-hGISOaP18plkzbWEcP/QvtRW1xDXF2+96HbEX6byqQhAUbiS5oH6/9JwW+QsQCIYON2bI6QZBF+2PvOmrRZ9wA=="],
"@vitest/utils": ["@vitest/utils@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"asn1": ["asn1@0.2.6", "", { "dependencies": { "safer-buffer": "~2.1.0" } }, "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ=="],
"assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"bcrypt-pbkdf": ["bcrypt-pbkdf@1.0.2", "", { "dependencies": { "tweetnacl": "^0.14.3" } }, "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w=="],
"bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"buildcheck": ["buildcheck@0.0.6", "", {}, "sha512-8f9ZJCUXyT1M35Jx7MkBgmBMo3oHTTBIPLiY9xyL0pl3T5RwcPEY8cUHr5LBNfu/fk6c2T4DJZuVM/8ZZT2D2A=="],
"bun-types": ["bun-types@1.3.0", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-u8X0thhx+yJ0KmkxuEo9HAtdfgCBaM/aI9K90VQcQioAmkVp3SG3FkwWGibUFz3WdXAdcsqOcbU40lK7tbHdkQ=="],
"cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="],
"check-error": ["check-error@2.1.1", "", {}, "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw=="],
"chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
"cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"cpu-features": ["cpu-features@0.0.10", "", { "dependencies": { "buildcheck": "~0.0.6", "nan": "^2.19.0" } }, "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA=="],
"csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="],
"docker-modem": ["docker-modem@5.0.6", "", { "dependencies": { "debug": "^4.1.1", "readable-stream": "^3.5.0", "split-ca": "^1.0.1", "ssh2": "^1.15.0" } }, "sha512-ens7BiayssQz/uAxGzH8zGXCtiV24rRWXdjNha5V4zSOcxmAZsfGVm/PPFbwQdqEkDnhG+SyR9E3zSHUbOKXBQ=="],
"dockerode": ["dockerode@4.0.9", "", { "dependencies": { "@balena/dockerignore": "^1.0.2", "@grpc/grpc-js": "^1.11.1", "@grpc/proto-loader": "^0.7.13", "docker-modem": "^5.0.6", "protobufjs": "^7.3.2", "tar-fs": "^2.1.4", "uuid": "^10.0.0" } }, "sha512-iND4mcOWhPaCNh54WmK/KoSb35AFqPAUWFMffTQcp52uQt36b5uNwEJTSXntJZBbeGad72Crbi/hvDIv6us/6Q=="],
"dockerode-mock": ["dockerode-mock@0.3.2", "", { "dependencies": { "dockerode": "*" } }, "sha512-YgJGwb2Ia7D59FM1T3gC66GCAiKFWQZV8aQQF7WTW0HboifmmupLvbVb0J8y5atT7VEceHvK0tFw6LPla//2Yg=="],
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="],
"esbuild": ["esbuild@0.25.11", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.11", "@esbuild/android-arm": "0.25.11", "@esbuild/android-arm64": "0.25.11", "@esbuild/android-x64": "0.25.11", "@esbuild/darwin-arm64": "0.25.11", "@esbuild/darwin-x64": "0.25.11", "@esbuild/freebsd-arm64": "0.25.11", "@esbuild/freebsd-x64": "0.25.11", "@esbuild/linux-arm": "0.25.11", "@esbuild/linux-arm64": "0.25.11", "@esbuild/linux-ia32": "0.25.11", "@esbuild/linux-loong64": "0.25.11", "@esbuild/linux-mips64el": "0.25.11", "@esbuild/linux-ppc64": "0.25.11", "@esbuild/linux-riscv64": "0.25.11", "@esbuild/linux-s390x": "0.25.11", "@esbuild/linux-x64": "0.25.11", "@esbuild/netbsd-arm64": "0.25.11", "@esbuild/netbsd-x64": "0.25.11", "@esbuild/openbsd-arm64": "0.25.11", "@esbuild/openbsd-x64": "0.25.11", "@esbuild/openharmony-arm64": "0.25.11", "@esbuild/sunos-x64": "0.25.11", "@esbuild/win32-arm64": "0.25.11", "@esbuild/win32-ia32": "0.25.11", "@esbuild/win32-x64": "0.25.11" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
"expect-type": ["expect-type@1.2.2", "", {}, "sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="],
"flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"hono": ["hono@4.10.1", "", {}, "sha512-rpGNOfacO4WEPClfkEt1yfl8cbu10uB1lNpiI33AKoiAHwOS8lV748JiLx4b5ozO/u4qLjIvfpFsPXdY5Qjkmg=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="],
"lodash.camelcase": ["lodash.camelcase@4.3.0", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
"loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="],
"magic-string": ["magic-string@0.30.19", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw=="],
"mkdirp-classic": ["mkdirp-classic@0.5.3", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
"mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"nan": ["nan@2.23.0", "", {}, "sha512-1UxuyYGdoQHcGg87Lkqm3FzefucTa0NAiOcuRsDmysep3c1LVCRK2krrUDafMWtjSG04htvAmvg96+SDknOmgQ=="],
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"postcss": ["postcss@8.5.6", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
"protobufjs": ["protobufjs@7.5.4", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg=="],
"pump": ["pump@3.0.3", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
"readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"rollup": ["rollup@4.52.5", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.52.5", "@rollup/rollup-android-arm64": "4.52.5", "@rollup/rollup-darwin-arm64": "4.52.5", "@rollup/rollup-darwin-x64": "4.52.5", "@rollup/rollup-freebsd-arm64": "4.52.5", "@rollup/rollup-freebsd-x64": "4.52.5", "@rollup/rollup-linux-arm-gnueabihf": "4.52.5", "@rollup/rollup-linux-arm-musleabihf": "4.52.5", "@rollup/rollup-linux-arm64-gnu": "4.52.5", "@rollup/rollup-linux-arm64-musl": "4.52.5", "@rollup/rollup-linux-loong64-gnu": "4.52.5", "@rollup/rollup-linux-ppc64-gnu": "4.52.5", "@rollup/rollup-linux-riscv64-gnu": "4.52.5", "@rollup/rollup-linux-riscv64-musl": "4.52.5", "@rollup/rollup-linux-s390x-gnu": "4.52.5", "@rollup/rollup-linux-x64-gnu": "4.52.5", "@rollup/rollup-linux-x64-musl": "4.52.5", "@rollup/rollup-openharmony-arm64": "4.52.5", "@rollup/rollup-win32-arm64-msvc": "4.52.5", "@rollup/rollup-win32-ia32-msvc": "4.52.5", "@rollup/rollup-win32-x64-gnu": "4.52.5", "@rollup/rollup-win32-x64-msvc": "4.52.5", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw=="],
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
"sirv": ["sirv@3.0.2", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"split-ca": ["split-ca@1.0.1", "", {}, "sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ=="],
"ssh2": ["ssh2@1.17.0", "", { "dependencies": { "asn1": "^0.2.6", "bcrypt-pbkdf": "^1.0.2" }, "optionalDependencies": { "cpu-features": "~0.0.10", "nan": "^2.23.0" } }, "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ=="],
"stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
"std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-literal": ["strip-literal@3.1.0", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="],
"tar-fs": ["tar-fs@2.1.4", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
"tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
"tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="],
"tinyglobby": ["tinyglobby@0.2.15", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
"tinypool": ["tinypool@1.1.1", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="],
"tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],
"tinyspy": ["tinyspy@4.0.4", "", {}, "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q=="],
"totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="],
"tweetnacl": ["tweetnacl@0.14.5", "", {}, "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.14.0", "", {}, "sha512-QQiYxHuyZ9gQUIrmPo3IA+hUl4KYk8uSA7cHrcKd/l3p1OTpZcM0Tbp9x7FAtXdAYhlasd60ncPpgu6ihG6TOA=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="],
"vite": ["vite@7.1.10", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-CmuvUBzVJ/e3HGxhg6cYk88NGgTnBoOo7ogtfJJ0fefUWAxN/WDSUa50o+oVBxuIhO8FoEZW0j2eW7sfjs5EtA=="],
"vite-node": ["vite-node@3.2.4", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.1", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg=="],
"vitest": ["vitest@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/expect": "3.2.4", "@vitest/mocker": "3.2.4", "@vitest/pretty-format": "^3.2.4", "@vitest/runner": "3.2.4", "@vitest/snapshot": "3.2.4", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "debug": "^4.4.1", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "picomatch": "^4.0.2", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.14", "tinypool": "^1.1.1", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", "vite-node": "3.2.4", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.2.4", "@vitest/ui": "3.2.4", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A=="],
"why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
"wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
"yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"zod": ["zod@4.1.12", "", {}, "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ=="],
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.0", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.3", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ=="],
"@types/ssh2/@types/node": ["@types/node@18.19.130", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="],
"@types/ssh2/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"name": "backend",
"module": "index.ts",
"type": "module",
"private": true,
"scripts": {
"dev": "bun --watch src/index.ts",
"start": "bun src/index.ts",
"build": "bun build src/index.ts --outdir=dist --target=bun",
"test": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest --coverage",
"test:watch": "vitest --watch"
},
"dependencies": {
"@hono/node-server": "^1.19.5",
"@opencode-webui/shared": "file:../shared",
"dotenv": "^17.2.3",
"hono": "^4.10.1",
"zod": "^4.1.12"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "latest",
"@vitest/ui": "^3.2.4",
"vitest": "^3.2.4"
},
"peerDependencies": {
"typescript": "^5"
}
}
+24
View File
@@ -0,0 +1,24 @@
import { config } from 'dotenv'
config()
export const ENV = {
PORT: parseInt(process.env.PORT || '5001'),
OPENCODE_SERVER_PORT: parseInt(process.env.OPENCODE_SERVER_PORT || '5551'),
HOST: process.env.HOST || '0.0.0.0',
DATABASE_PATH: process.env.DATABASE_PATH || './backend/data/opencode.db',
WORKSPACE_PATH: process.env.WORKSPACE_PATH || '~/.opencode-workspace',
PROCESS_START_WAIT_MS: parseInt(process.env.PROCESS_START_WAIT_MS || '2000'),
PROCESS_VERIFY_WAIT_MS: parseInt(process.env.PROCESS_VERIFY_WAIT_MS || '1000'),
HEALTH_CHECK_INTERVAL_MS: parseInt(process.env.HEALTH_CHECK_INTERVAL_MS || '5000'),
HEALTH_CHECK_TIMEOUT_MS: parseInt(process.env.HEALTH_CHECK_TIMEOUT_MS || '30000'),
MAX_FILE_SIZE_MB: parseInt(process.env.MAX_FILE_SIZE_MB || '50'),
MAX_UPLOAD_SIZE_MB: parseInt(process.env.MAX_UPLOAD_SIZE_MB || '50'),
SANDBOX_TTL_HOURS: parseInt(process.env.SANDBOX_TTL_HOURS || '24'),
CLEANUP_INTERVAL_MINUTES: parseInt(process.env.CLEANUP_INTERVAL_MINUTES || '60'),
DEBUG: process.env.DEBUG === 'true',
VITE_API_URL: process.env.VITE_API_URL || 'http://localhost:5001',
VITE_ANTHROPIC_API_KEY: process.env.VITE_ANTHROPIC_API_KEY || '',
VITE_OPENAI_API_KEY: process.env.VITE_OPENAI_API_KEY || '',
VITE_GOOGLE_API_KEY: process.env.VITE_GOOGLE_API_KEY || ''
}
+80
View File
@@ -0,0 +1,80 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
export function runMigrations(db: Database): void {
try {
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as any[]
const hasBranchColumn = tableInfo.some(col => col.name === 'branch')
if (!hasBranchColumn) {
logger.info('Adding missing branch column to repos table')
db.run('ALTER TABLE repos ADD COLUMN branch TEXT')
}
try {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_repo_url_branch
ON repos(repo_url, branch)
WHERE branch IS NOT NULL
`)
} catch (error) {
logger.debug('Index already exists or could not be created', error)
}
const requiredColumns = [
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' }
]
for (const column of requiredColumns) {
const hasColumn = tableInfo.some(col => col.name === column.name)
if (!hasColumn) {
logger.info(`Adding missing column: ${column.name}`)
try {
db.run(column.sql)
} catch (error) {
logger.debug(`Column ${column.name} might already exist:`, error)
}
}
}
const indexes = [
'CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)',
'CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id)',
'CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)',
'CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)'
]
for (const indexSql of indexes) {
try {
db.run(indexSql)
} catch (error) {
logger.debug('Index already exists:', error)
}
}
try {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as any[]
if (repos.length > 0) {
logger.info(`Migrating ${repos.length} repos to remove 'repos/' prefix from local_path`)
const updateStmt = db.prepare("UPDATE repos SET local_path = ? WHERE id = ?")
for (const repo of repos) {
const newPath = repo.local_path.replace(/^repos\//, '')
updateStmt.run(newPath, repo.id)
logger.info(`Updated repo ${repo.id}: ${repo.local_path} -> ${newPath}`)
}
}
} catch (error) {
logger.error('Failed to migrate local_path format:', error)
}
logger.info('Database migrations completed successfully')
} catch (error) {
logger.error('Failed to run database migrations:', error)
throw error
}
}
+115
View File
@@ -0,0 +1,115 @@
import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { getReposPath } from '../../../shared/src/constants'
import path from 'path'
export interface RepoRow {
id: number
repo_url: string
local_path: string
branch?: string
default_branch: string
clone_status: string
cloned_at: number
last_pulled?: number
opencode_config_name?: string
is_worktree?: number
}
function rowToRepo(row: RepoRow): Repo {
return {
id: row.id,
repoUrl: row.repo_url,
localPath: row.local_path,
fullPath: path.join(getReposPath(), row.local_path),
branch: row.branch,
defaultBranch: row.default_branch,
cloneStatus: row.clone_status as Repo['cloneStatus'],
clonedAt: row.cloned_at,
lastPulled: row.last_pulled,
openCodeConfigName: row.opencode_config_name,
isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined,
}
}
export function createRepo(db: Database, repo: CreateRepoInput): Repo {
const stmt = db.prepare(`
INSERT OR IGNORE INTO repos (repo_url, local_path, branch, default_branch, clone_status, cloned_at, is_worktree)
VALUES (?, ?, ?, ?, ?, ?, ?)
`)
const result = stmt.run(
repo.repoUrl,
repo.localPath,
repo.branch || null,
repo.defaultBranch,
repo.cloneStatus,
repo.clonedAt,
repo.isWorktree ? 1 : 0
)
if (result.changes === 0) {
const existing = getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch)
if (existing) {
return existing
}
throw new Error('Failed to create repo and no existing repo found')
}
const newRepo = getRepoById(db, Number(result.lastInsertRowid))!
return newRepo
}
export function getRepoById(db: Database, id: number): Repo | null {
const stmt = db.prepare('SELECT * FROM repos WHERE id = ?')
const row = stmt.get(id) as RepoRow | undefined
return row ? rowToRepo(row) : null
}
export function getRepoByUrl(db: Database, repoUrl: string): Repo | null {
const stmt = db.prepare('SELECT * FROM repos WHERE repo_url = ?')
const row = stmt.get(repoUrl) as RepoRow | undefined
return row ? rowToRepo(row) : null
}
export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: string): Repo | null {
const query = branch
? 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?'
: 'SELECT * FROM repos WHERE repo_url = ? AND branch IS NULL'
const stmt = db.prepare(query)
const row = branch
? stmt.get(repoUrl, branch) as RepoRow | undefined
: stmt.get(repoUrl) as RepoRow | undefined
return row ? rowToRepo(row) : null
}
export function listRepos(db: Database): Repo[] {
const stmt = db.prepare('SELECT * FROM repos ORDER BY cloned_at DESC')
const rows = stmt.all() as RepoRow[]
return rows.map(rowToRepo)
}
export function updateRepoStatus(db: Database, id: number, cloneStatus: Repo['cloneStatus']): void {
const stmt = db.prepare('UPDATE repos SET clone_status = ? WHERE id = ?')
stmt.run(cloneStatus, id)
}
export function updateRepoConfigName(db: Database, id: number, configName: string): void {
const stmt = db.prepare('UPDATE repos SET opencode_config_name = ? WHERE id = ?')
stmt.run(configName, id)
}
export function updateLastPulled(db: Database, id: number): void {
const stmt = db.prepare('UPDATE repos SET last_pulled = ? WHERE id = ?')
stmt.run(Date.now(), id)
}
export function deleteRepo(db: Database, id: number): void {
const stmt = db.prepare('DELETE FROM repos WHERE id = ?')
stmt.run(id)
}
+59
View File
@@ -0,0 +1,59 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
import { mkdirSync } from 'fs'
import { dirname } from 'path'
import { runMigrations } from './migrations'
export function initializeDatabase(dbPath: string = './data/opencode.db'): Database {
mkdirSync(dirname(dbPath), { recursive: true })
const db = new Database(dbPath)
db.run(`
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT NOT NULL,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
UNIQUE(repo_url, branch)
);
CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status);
CREATE TABLE IF NOT EXISTS user_preferences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
preferences TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id)
);
CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id);
CREATE TABLE IF NOT EXISTS opencode_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
config_name TEXT NOT NULL,
config_content TEXT NOT NULL,
is_default BOOLEAN DEFAULT FALSE,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, config_name)
);
CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id);
CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default);
`)
runMigrations(db)
logger.info('Database initialized successfully')
return db
}
+20
View File
@@ -0,0 +1,20 @@
import type { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
export async function withTransactionAsync<T>(
db: Database,
fn: (db: Database) => Promise<T>
): Promise<T> {
try {
db.exec('BEGIN TRANSACTION')
const result = await fn(db)
db.exec('COMMIT')
return result
} catch (error) {
db.exec('ROLLBACK')
logger.error('Transaction rolled back:', error)
throw error
}
}
+117
View File
@@ -0,0 +1,117 @@
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { serveStatic } from '@hono/node-server/serve-static'
import { initializeDatabase } from './db/schema'
import { createRepoRoutes } from './routes/repos'
import { createSettingsRoutes } from './routes/settings'
import { createHealthRoutes } from './routes/health'
import { createSessionRoutes } from './routes/sessions'
import { createFileRoutes } from './routes/files'
import { createProvidersRoutes } from './routes/providers'
import { ensureDirectoryExists } from './services/file-operations'
import { opencodeServerManager } from './services/opencode-single-server'
import { cleanupOrphanedDirectories } from './services/repo'
import { proxyRequest } from './services/proxy'
import { logger } from './utils/logger'
import { ENV } from './config'
import { getWorkspacePath, getReposPath, getConfigPath } from '../../shared/src/constants'
await import('dotenv/config')
const { PORT, HOST, DATABASE_PATH: DB_PATH } = ENV
const app = new Hono()
app.use('/*', cors({
origin: '*',
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
}))
const db = initializeDatabase(DB_PATH)
try {
await ensureDirectoryExists(getWorkspacePath())
await ensureDirectoryExists(getReposPath())
await ensureDirectoryExists(getConfigPath())
logger.info('Workspace directories initialized')
await cleanupOrphanedDirectories(db)
logger.info('Orphaned directory cleanup completed')
await opencodeServerManager.start()
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
} catch (error) {
logger.error('Failed to initialize workspace:', error)
}
app.route('/api/repos', createRepoRoutes(db))
app.route('/api/settings', createSettingsRoutes(db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/sessions', createSessionRoutes())
app.route('/api/files', createFileRoutes(db))
app.route('/api/providers', createProvidersRoutes())
app.all('/api/opencode/*', async (c) => {
const request = c.req.raw
return proxyRequest(request)
})
const isProduction = process.env.NODE_ENV === 'production'
if (isProduction) {
app.use('/*', async (c, next) => {
if (c.req.path.startsWith('/api/')) {
return next()
}
return serveStatic({ root: './frontend/dist' })(c, next)
})
app.get('*', async (c) => {
return serveStatic({ path: './frontend/dist/index.html' })(c, async () => {})
})
} else {
app.get('/', (c) => {
return c.json({
name: 'OpenCode WebUI',
version: '2.0.0',
status: 'running',
endpoints: {
health: '/api/health',
repos: '/api/repos',
settings: '/api/settings',
sessions: '/api/sessions',
files: '/api/files',
providers: '/api/providers',
opencode_proxy: '/api/opencode/*'
}
})
})
}
let isShuttingDown = false
const shutdown = async (signal: string) => {
if (isShuttingDown) return
isShuttingDown = true
logger.info(`${signal} received, shutting down gracefully...`)
try {
await opencodeServerManager.stop()
logger.info('OpenCode server stopped')
} catch (error) {
logger.error('Error stopping OpenCode server:', error)
}
process.exit(0)
}
process.on('SIGTERM', () => shutdown('SIGTERM'))
process.on('SIGINT', () => shutdown('SIGINT'))
serve({
fetch: app.fetch,
port: PORT,
hostname: HOST,
})
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
+104
View File
@@ -0,0 +1,104 @@
import { Hono } from 'hono'
import { serveStatic } from '@hono/node-server/serve-static'
import * as db from '../db/queries'
import * as fileService from '../services/files'
import type { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
export function createFileRoutes(database: Database) {
const app = new Hono()
app.get('/*', async (c) => {
try {
const userPath = c.req.path.replace(/^\/api\/files\//, '') || ''
const download = c.req.query('download') === 'true'
const raw = c.req.query('raw') === 'true'
const result = await fileService.getFile(userPath)
if (raw && !result.isDirectory) {
const content = await fileService.getRawFileContent(userPath)
return new Response(content, {
headers: {
'Content-Type': result.mimeType || 'application/octet-stream',
'Content-Length': result.size.toString(),
}
})
}
if (download && !result.isDirectory) {
const content = result.content ? Buffer.from(result.content, 'base64') : Buffer.alloc(0)
return new Response(content, {
headers: {
'Content-Type': result.mimeType || 'application/octet-stream',
'Content-Disposition': `attachment; filename="${result.name}"`,
'Content-Length': result.size.toString(),
}
})
}
return c.json(result)
} catch (error: any) {
logger.error('Failed to get file:', error)
return c.json({ error: error.message || 'Failed to get file' }, error.statusCode || 500)
}
})
app.post('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const body = await c.req.parseBody()
const file = body.file as File
if (!file) {
return c.json({ error: 'No file provided' }, 400)
}
const result = await fileService.uploadFile(path, file)
return c.json(result)
} catch (error: any) {
logger.error('Failed to upload file:', error)
return c.json({ error: error.message }, error.statusCode || 500)
}
})
app.put('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const body = await c.req.json()
const result = await fileService.createFileOrFolder(path, body)
return c.json(result)
} catch (error: any) {
logger.error('Failed to create file/folder:', error)
return c.json({ error: error.message }, error.statusCode || 500)
}
})
app.delete('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
await fileService.deleteFileOrFolder(path)
return c.json({ success: true })
} catch (error: any) {
logger.error('Failed to delete file/folder:', error)
return c.json({ error: error.message }, error.statusCode || 500)
}
})
app.patch('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const body = await c.req.json()
const result = await fileService.renameOrMoveFile(path, body)
return c.json(result)
} catch (error: any) {
logger.error('Failed to rename/move file:', error)
return c.json({ error: error.message }, error.statusCode || 500)
}
})
return app
}
+51
View File
@@ -0,0 +1,51 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { opencodeServerManager } from '../services/opencode-single-server'
export function createHealthRoutes(db: Database) {
const app = new Hono()
app.get('/', async (c) => {
try {
const dbCheck = db.prepare('SELECT 1').get()
const opencodeHealthy = await opencodeServerManager.checkHealth()
const status = dbCheck && opencodeHealthy ? 'healthy' : 'degraded'
return c.json({
status,
timestamp: new Date().toISOString(),
database: dbCheck ? 'connected' : 'disconnected',
opencode: opencodeHealthy ? 'healthy' : 'unhealthy',
opencodePort: opencodeServerManager.getPort()
})
} catch (error) {
return c.json({
status: 'unhealthy',
timestamp: new Date().toISOString(),
error: error instanceof Error ? error.message : 'Unknown error'
}, 503)
}
})
app.get('/processes', async (c) => {
try {
const opencodeHealthy = await opencodeServerManager.checkHealth()
return c.json({
opencode: {
port: opencodeServerManager.getPort(),
healthy: opencodeHealthy
},
timestamp: new Date().toISOString()
})
} catch (error) {
return c.json({
error: error instanceof Error ? error.message : 'Unknown error',
timestamp: new Date().toISOString()
}, 500)
}
})
return app
}
+61
View File
@@ -0,0 +1,61 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { AuthService } from '../services/auth'
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
import { logger } from '../utils/logger'
export function createProvidersRoutes() {
const app = new Hono()
const authService = new AuthService()
app.get('/credentials', async (c) => {
try {
const providers = await authService.list()
return c.json({ providers })
} catch (error) {
logger.error('Failed to list provider credentials:', error)
return c.json({ error: 'Failed to list provider credentials' }, 500)
}
})
app.get('/:id/credentials/status', async (c) => {
try {
const providerId = c.req.param('id')
const hasCredentials = await authService.has(providerId)
return c.json({ hasCredentials })
} catch (error) {
logger.error('Failed to check credential status:', error)
return c.json({ error: 'Failed to check credential status' }, 500)
}
})
app.post('/:id/credentials', async (c) => {
try {
const providerId = c.req.param('id')
const body = await c.req.json()
const validated = SetCredentialRequestSchema.parse(body)
await authService.set(providerId, validated.apiKey)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to set provider credentials:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to set provider credentials' }, 500)
}
})
app.delete('/:id/credentials', async (c) => {
try {
const providerId = c.req.param('id')
await authService.delete(providerId)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete provider credentials:', error)
return c.json({ error: 'Failed to delete provider credentials' }, 500)
}
})
return app
}
+203
View File
@@ -0,0 +1,203 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import * as db from '../db/queries'
import * as repoService from '../services/repo'
import { SettingsService } from '../services/settings'
import { writeFileContent } from '../services/file-operations'
import { logger } from '../utils/logger'
import { withTransactionAsync } from '../db/transactions'
import path from 'path'
import { getReposPath } from '../../../shared/src/constants'
export function createRepoRoutes(database: Database) {
const app = new Hono()
app.post('/', async (c) => {
try {
const body = await c.req.json()
const { repoUrl, branch, openCodeConfigName, useWorktree } = body
if (!repoUrl) {
return c.json({ error: 'repoUrl is required' }, 400)
}
const repo = await repoService.cloneRepo(
database,
repoUrl,
branch,
useWorktree
)
if (openCodeConfigName) {
const settingsService = new SettingsService(database)
const configContent = settingsService.getOpenCodeConfigContent(openCodeConfigName)
if (configContent) {
const workingDir = path.join(getReposPath(), repo.localPath)
const configPath = `${workingDir}/opencode.json`
await writeFileContent(configPath, configContent)
db.updateRepoConfigName(database, repo.id, openCodeConfigName)
}
}
return c.json(repo)
} catch (error: any) {
logger.error('Failed to create repo:', error)
return c.json({ error: error.message }, 500)
}
})
app.get('/', async (c) => {
try {
const repos = db.listRepos(database)
const reposWithCurrentBranch = await Promise.all(
repos.map(async (repo) => {
const currentBranch = await repoService.getCurrentBranch(repo)
return { ...repo, currentBranch }
})
)
return c.json(reposWithCurrentBranch)
} catch (error: any) {
logger.error('Failed to list repos:', error)
return c.json({ error: error.message }, 500)
}
})
app.get('/:id', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const currentBranch = await repoService.getCurrentBranch(repo)
return c.json({ ...repo, currentBranch })
} catch (error: any) {
logger.error('Failed to get repo:', error)
return c.json({ error: error.message }, 500)
}
})
app.delete('/:id', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
await withTransactionAsync(database, async (db) => {
await repoService.deleteRepoFiles(db, id)
})
return c.json({ success: true })
} catch (error: any) {
logger.error('Failed to delete repo:', error)
return c.json({ error: error.message }, 500)
}
})
app.post('/:id/pull', async (c) => {
try {
const id = parseInt(c.req.param('id'))
await repoService.pullRepo(database, id)
const repo = db.getRepoById(database, id)
return c.json(repo)
} catch (error: any) {
logger.error('Failed to pull repo:', error)
return c.json({ error: error.message }, 500)
}
})
app.post('/:id/config/switch', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const body = await c.req.json()
const { configName } = body
if (!configName) {
return c.json({ error: 'configName is required' }, 400)
}
const settingsService = new SettingsService(database)
const configContent = settingsService.getOpenCodeConfigContent(configName)
if (!configContent) {
return c.json({ error: `Config '${configName}' not found` }, 404)
}
const workingDir = path.join(getReposPath(), repo.localPath)
const configPath = `${workingDir}/opencode.json`
await writeFileContent(configPath, configContent)
db.updateRepoConfigName(database, id, configName)
logger.info(`Switched config for repo ${id} to '${configName}'`)
const updatedRepo = db.getRepoById(database, id)
return c.json(updatedRepo)
} catch (error: any) {
logger.error('Failed to switch repo config:', error)
return c.json({ error: error.message }, 500)
}
})
app.post('/:id/branch/switch', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const body = await c.req.json()
const { branch } = body
if (!branch) {
return c.json({ error: 'branch is required' }, 400)
}
await repoService.switchBranch(database, id, branch)
const updatedRepo = db.getRepoById(database, id)
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
return c.json({ ...updatedRepo, currentBranch })
} catch (error: any) {
logger.error('Failed to switch branch:', error)
return c.json({ error: error.message }, 500)
}
})
app.get('/:id/branches', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const branches = await repoService.listBranches(repo)
return c.json(branches)
} catch (error: any) {
logger.error('Failed to list branches:', error)
return c.json({ error: error.message }, 500)
}
})
return app
}
+154
View File
@@ -0,0 +1,154 @@
import { Hono } from 'hono'
import { logger } from '../utils/logger'
import { ENV } from '../config'
const OPENCODE_SERVER_PORT = ENV.OPENCODE_SERVER_PORT
export function createSessionRoutes() {
const app = new Hono()
app.post('/', async (c) => {
const body = await c.req.json()
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
if (!response.ok) {
logger.error(`Session creation failed: ${response.status} ${response.statusText}`)
return c.json({ error: 'Session creation failed', status: response.status }, response.status as any)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('Failed to create session:', error)
return c.json({ error: 'Failed to create session' }, 500)
}
})
app.post('/:sessionID/command', async (c) => {
const sessionID = c.req.param('sessionID')
const body = await c.req.json()
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/command`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
if (!response.ok) {
logger.error(`Command failed: ${response.status} ${response.statusText}`)
return c.json({ error: 'Command failed', status: response.status }, response.status as any)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('Failed to send command:', error)
return c.json({ error: 'Failed to send command' }, 500)
}
})
app.post('/:sessionID/shell', async (c) => {
const sessionID = c.req.param('sessionID')
const body = await c.req.json()
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/shell`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
if (!response.ok) {
logger.error(`Shell command failed: ${response.status} ${response.statusText}`)
return c.json({ error: 'Shell command failed', status: response.status }, response.status as any)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('Failed to send shell command:', error)
return c.json({ error: 'Failed to send shell command' }, 500)
}
})
app.post('/:sessionID/abort', async (c) => {
const sessionID = c.req.param('sessionID')
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/abort`, {
method: 'POST',
})
if (!response.ok) {
logger.error(`Abort failed: ${response.status} ${response.statusText}`)
return c.json({ error: 'Abort failed', status: response.status }, response.status as any)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('Failed to abort session:', error)
return c.json({ error: 'Failed to abort session' }, 500)
}
})
app.get('/:sessionID/message', async (c) => {
const sessionID = c.req.param('sessionID')
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/message`)
if (!response.ok) {
logger.error(`Get messages failed: ${response.status} ${response.statusText}`)
return c.json({ error: 'Get messages failed', status: response.status }, response.status as any)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('Failed to get messages:', error)
return c.json({ error: 'Failed to get messages' }, 500)
}
})
app.post('/:sessionID/message', async (c) => {
const sessionID = c.req.param('sessionID')
const body = await c.req.json()
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/message`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
if (!response.ok) {
logger.error(`Send message failed: ${response.status} ${response.statusText}`)
return c.json({ error: 'Send message failed', status: response.status }, response.status as any)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('Failed to send message:', error)
return c.json({ error: 'Failed to send message' }, 500)
}
})
return app
}
+279
View File
@@ -0,0 +1,279 @@
import { Hono } from 'hono'
import { z } from 'zod'
import type { Database } from 'bun:sqlite'
import { SettingsService } from '../services/settings'
import {
UserPreferencesSchema,
OpenCodeConfigSchema,
OpenCodeConfigMetadataSchema,
CustomCommandSchema
} from '../types/settings'
import { logger } from '../utils/logger'
const UpdateSettingsSchema = z.object({
preferences: UserPreferencesSchema.partial(),
})
const CreateOpenCodeConfigSchema = z.object({
name: z.string().min(1).max(255),
content: OpenCodeConfigSchema,
isDefault: z.boolean().optional(),
})
const UpdateOpenCodeConfigSchema = z.object({
content: OpenCodeConfigSchema,
isDefault: z.boolean().optional(),
})
const CreateCustomCommandSchema = z.object({
name: z.string().min(1).max(255),
description: z.string().min(1).max(1000),
promptTemplate: z.string().min(1).max(10000),
})
const UpdateCustomCommandSchema = z.object({
description: z.string().min(1).max(1000),
promptTemplate: z.string().min(1).max(10000),
})
export function createSettingsRoutes(db: Database) {
const app = new Hono()
const settingsService = new SettingsService(db)
app.get('/', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const settings = settingsService.getSettings(userId)
return c.json(settings)
} catch (error) {
logger.error('Failed to get settings:', error)
return c.json({ error: 'Failed to get settings' }, 500)
}
})
app.patch('/', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const body = await c.req.json()
const validated = UpdateSettingsSchema.parse(body)
const settings = settingsService.updateSettings(validated.preferences, userId)
return c.json(settings)
} catch (error) {
logger.error('Failed to update settings:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid settings data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to update settings' }, 500)
}
})
app.delete('/', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const settings = settingsService.resetSettings(userId)
return c.json(settings)
} catch (error) {
logger.error('Failed to reset settings:', error)
return c.json({ error: 'Failed to reset settings' }, 500)
}
})
// OpenCode Config routes
app.get('/opencode-configs', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configs = settingsService.getOpenCodeConfigs(userId)
return c.json(configs)
} catch (error) {
logger.error('Failed to get OpenCode configs:', error)
return c.json({ error: 'Failed to get OpenCode configs' }, 500)
}
})
app.post('/opencode-configs', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const body = await c.req.json()
const validated = CreateOpenCodeConfigSchema.parse(body)
const config = settingsService.createOpenCodeConfig(validated, userId)
return c.json(config)
} catch (error) {
logger.error('Failed to create OpenCode config:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to create OpenCode config' }, 500)
}
})
app.put('/opencode-configs/:name', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configName = c.req.param('name')
const body = await c.req.json()
const validated = UpdateOpenCodeConfigSchema.parse(body)
const config = settingsService.updateOpenCodeConfig(configName, validated, userId)
if (!config) {
return c.json({ error: 'Config not found' }, 404)
}
return c.json(config)
} catch (error) {
logger.error('Failed to update OpenCode config:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to update OpenCode config' }, 500)
}
})
app.delete('/opencode-configs/:name', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configName = c.req.param('name')
const deleted = settingsService.deleteOpenCodeConfig(configName, userId)
if (!deleted) {
return c.json({ error: 'Config not found' }, 404)
}
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete OpenCode config:', error)
return c.json({ error: 'Failed to delete OpenCode config' }, 500)
}
})
app.post('/opencode-configs/:name/set-default', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configName = c.req.param('name')
const config = settingsService.setDefaultOpenCodeConfig(configName, userId)
if (!config) {
return c.json({ error: 'Config not found' }, 404)
}
return c.json(config)
} catch (error) {
logger.error('Failed to set default OpenCode config:', error)
return c.json({ error: 'Failed to set default OpenCode config' }, 500)
}
})
app.get('/opencode-configs/default', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const config = settingsService.getDefaultOpenCodeConfig(userId)
if (!config) {
return c.json({ error: 'No default config found' }, 404)
}
return c.json(config)
} catch (error) {
logger.error('Failed to get default OpenCode config:', error)
return c.json({ error: 'Failed to get default OpenCode config' }, 500)
}
})
// Custom Commands routes
app.get('/custom-commands', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const settings = settingsService.getSettings(userId)
return c.json(settings.preferences.customCommands)
} catch (error) {
logger.error('Failed to get custom commands:', error)
return c.json({ error: 'Failed to get custom commands' }, 500)
}
})
app.post('/custom-commands', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const body = await c.req.json()
const validated = CreateCustomCommandSchema.parse(body)
const settings = settingsService.getSettings(userId)
const existingCommand = settings.preferences.customCommands.find(cmd => cmd.name === validated.name)
if (existingCommand) {
return c.json({ error: 'Command with this name already exists' }, 409)
}
const updatedSettings = settingsService.updateSettings({
customCommands: [...settings.preferences.customCommands, validated]
}, userId)
return c.json(validated)
} catch (error) {
logger.error('Failed to create custom command:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid command data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to create custom command' }, 500)
}
})
app.put('/custom-commands/:name', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const commandName = decodeURIComponent(c.req.param('name'))
const body = await c.req.json()
const validated = UpdateCustomCommandSchema.parse(body)
const settings = settingsService.getSettings(userId)
const commandIndex = settings.preferences.customCommands.findIndex(cmd => cmd.name === commandName)
if (commandIndex === -1) {
return c.json({ error: 'Command not found' }, 404)
}
const updatedCommands = [...settings.preferences.customCommands]
updatedCommands[commandIndex] = {
name: commandName,
description: validated.description,
promptTemplate: validated.promptTemplate
}
const updatedSettings = settingsService.updateSettings({
customCommands: updatedCommands
}, userId)
return c.json(updatedCommands[commandIndex])
} catch (error) {
logger.error('Failed to update custom command:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid command data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to update custom command' }, 500)
}
})
app.delete('/custom-commands/:name', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const commandName = decodeURIComponent(c.req.param('name'))
const settings = settingsService.getSettings(userId)
const commandExists = settings.preferences.customCommands.some(cmd => cmd.name === commandName)
if (!commandExists) {
return c.json({ error: 'Command not found' }, 404)
}
const updatedCommands = settings.preferences.customCommands.filter(cmd => cmd.name !== commandName)
const updatedSettings = settingsService.updateSettings({
customCommands: updatedCommands
}, userId)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete custom command:', error)
return c.json({ error: 'Failed to delete custom command' }, 500)
}
})
return app
}
+63
View File
@@ -0,0 +1,63 @@
import { promises as fs } from 'fs'
import path from 'path'
import { getAuthPath } from '../../../shared/src/constants'
import { logger } from '../utils/logger'
import { AuthCredentialsSchema } from '../../../shared/src/schemas/auth'
import type { z } from 'zod'
type AuthCredentials = z.infer<typeof AuthCredentialsSchema>
type AuthEntry = AuthCredentials[string]
export class AuthService {
private authPath = getAuthPath()
async getAll(): Promise<AuthCredentials> {
try {
const data = await fs.readFile(this.authPath, 'utf-8')
const parsed = JSON.parse(data)
return AuthCredentialsSchema.parse(parsed)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return {}
}
logger.error('Failed to read auth.json:', error)
return {}
}
}
async set(providerId: string, apiKey: string): Promise<void> {
const auth = await this.getAll()
auth[providerId] = {
type: 'apiKey',
apiKey,
}
await fs.mkdir(path.dirname(this.authPath), { recursive: true })
await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2), { mode: 0o600 })
logger.info(`Set credentials for provider: ${providerId}`)
}
async delete(providerId: string): Promise<void> {
const auth = await this.getAll()
delete auth[providerId]
await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2))
logger.info(`Deleted credentials for provider: ${providerId}`)
}
async list(): Promise<string[]> {
const auth = await this.getAll()
return Object.keys(auth)
}
async has(providerId: string): Promise<boolean> {
const auth = await this.getAll()
return !!auth[providerId]
}
async get(providerId: string): Promise<AuthEntry | null> {
const auth = await this.getAll()
return auth[providerId] || null
}
}
+123
View File
@@ -0,0 +1,123 @@
import { promises as fs } from 'fs'
import path from 'path'
import { logger } from '../utils/logger'
import { getWorkspacePath, getReposPath } from '../../../shared/src/constants'
export async function readFileContent(filePath: string): Promise<string> {
try {
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath)
return await fs.readFile(fullPath, 'utf8')
} catch (error) {
throw new Error(`Failed to read file ${filePath}: ${error}`)
}
}
export async function readFileAsBase64(filePath: string): Promise<string> {
try {
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath)
const buffer = await fs.readFile(fullPath)
return buffer.toString('base64')
} catch (error) {
throw new Error(`Failed to read file ${filePath}: ${error}`)
}
}
export async function writeFileContent(
filePath: string,
content: string | Buffer
): Promise<void> {
try {
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath)
await fs.mkdir(path.dirname(fullPath), { recursive: true })
await fs.writeFile(fullPath, Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8'))
logger.info(`Wrote file to: ${fullPath}`)
} catch (error) {
throw new Error(`Failed to write file ${filePath}: ${error}`)
}
}
export async function ensureDirectoryExists(dirPath: string): Promise<void> {
try {
const fullPath = path.isAbsolute(dirPath) ? dirPath : path.resolve(dirPath)
await fs.mkdir(fullPath, { recursive: true })
} catch (error) {
throw new Error(`Failed to create directory ${dirPath}: ${error}`)
}
}
export async function fileExists(filePath: string): Promise<boolean> {
try {
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath)
await fs.access(fullPath)
return true
} catch {
return false
}
}
export async function deletePath(filePath: string): Promise<void> {
try {
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath)
const stats = await fs.stat(fullPath)
if (stats.isDirectory()) {
await fs.rm(fullPath, { recursive: true, force: true })
} else {
await fs.unlink(fullPath)
}
} catch (error) {
throw new Error(`Failed to delete path ${filePath}: ${error}`)
}
}
export async function getFileStats(filePath: string): Promise<{ size: number; lastModified: Date; isDirectory: boolean }> {
try {
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath)
const stats = await fs.stat(fullPath)
return {
size: stats.size,
lastModified: stats.mtime,
isDirectory: stats.isDirectory()
}
} catch (error) {
throw new Error(`Failed to get stats for ${filePath}: ${error}`)
}
}
export async function listDirectory(dirPath: string): Promise<Array<{
name: string
path: string
isDirectory: boolean
size: number
lastModified: Date
}>> {
try {
const fullPath = path.isAbsolute(dirPath) ? dirPath : path.join(getReposPath(), dirPath)
const entries = await fs.readdir(fullPath, { withFileTypes: true })
const result = []
for (const entry of entries) {
if (entry.name === '.' || entry.name === '..') continue
const entryPath = path.join(fullPath, entry.name)
const stats = await fs.stat(entryPath)
result.push({
name: entry.name,
path: entryPath,
isDirectory: entry.isDirectory(),
size: entry.isDirectory() ? 0 : stats.size,
lastModified: stats.mtime
})
}
return result
} catch (error) {
throw new Error(`Failed to list directory ${dirPath}: ${error}`)
}
}
+258
View File
@@ -0,0 +1,258 @@
import fs from 'fs/promises'
import path from 'path'
import { logger } from '../utils/logger'
import {
readFileContent,
readFileAsBase64,
writeFileContent,
fileExists,
deletePath,
getFileStats,
listDirectory
} from './file-operations'
import { FILE_LIMITS, ALLOWED_MIME_TYPES } from '../../../shared/src/constants'
import { getReposPath } from '../../../shared/src/constants'
const SHARED_WORKSPACE_BASE = getReposPath()
interface FileInfo {
name: string
path: string
isDirectory: boolean
size: number
mimeType?: string
content?: string
children?: FileInfo[]
lastModified: Date
}
interface FileUploadResult {
name: string
path: string
size: number
mimeType: string
}
export async function getRawFileContent(userPath: string): Promise<Buffer> {
const validatedPath = validatePath(userPath)
logger.info(`Getting raw file content for path: ${userPath} -> ${validatedPath}`)
try {
const exists = await fileExists(validatedPath)
if (!exists) {
throw new Error('File does not exist')
}
const stats = await getFileStats(validatedPath)
if (stats.isDirectory) {
throw new Error('Path is a directory')
}
return await fs.readFile(validatedPath)
} catch (error) {
logger.error(`Failed to read raw file content ${validatedPath}:`, error)
throw { message: 'File not found or cannot be read', statusCode: 404 }
}
}
export async function getFile(userPath: string): Promise<FileInfo> {
const validatedPath = validatePath(userPath)
logger.info(`Getting file for path: ${userPath} -> ${validatedPath}`)
try {
// Check if path exists
const exists = await fileExists(validatedPath)
if (!exists) {
throw new Error('Path does not exist')
}
// Get file stats
const stats = await getFileStats(validatedPath)
if (stats.isDirectory) {
// It's a directory - list contents
const entries = await listDirectory(validatedPath)
const children: FileInfo[] = []
for (const entry of entries) {
children.push({
name: entry.name,
path: path.join(userPath, entry.name),
isDirectory: entry.isDirectory,
size: entry.size,
lastModified: entry.lastModified,
})
}
return {
name: path.basename(validatedPath),
path: userPath,
isDirectory: true,
size: 0,
children: children.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1
}
return a.name.localeCompare(b.name)
}),
lastModified: stats.lastModified,
}
} else {
// It's a file - get content
let content = ''
let mimeType = getMimeType(validatedPath, new Uint8Array())
if (stats.size < FILE_LIMITS.MAX_SIZE_BYTES) {
try {
const mimeType = getMimeType(validatedPath, new Uint8Array())
if (mimeType.startsWith('image/') || !mimeType.startsWith('text/')) {
content = await readFileAsBase64(validatedPath)
} else {
const fileOutput = await readFileContent(validatedPath)
content = Buffer.from(fileOutput, 'utf8').toString('base64')
}
} catch (error) {
logger.warn(`Failed to read file content: ${error}`)
}
}
return {
name: path.basename(validatedPath),
path: userPath,
isDirectory: false,
size: stats.size,
mimeType,
content,
lastModified: stats.lastModified,
}
}
} catch (error) {
logger.error(`Failed to access path ${validatedPath}:`, error)
throw { message: 'File or directory not found', statusCode: 404 }
}
}
export async function uploadFile(userPath: string, file: File): Promise<FileUploadResult> {
if (file.size > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
throw new Error('File too large')
}
const mimeType = file.type || getMimeType(file.name, new Uint8Array())
if (!ALLOWED_MIME_TYPES.includes(mimeType as any) && !mimeType.startsWith('text/')) {
throw new Error('File type not allowed')
}
const validatedPath = validatePath(userPath)
const fileName = file.name || path.basename(userPath)
const fullPath = path.join(validatedPath, fileName)
const buffer = await file.arrayBuffer()
await writeFileContent(fullPath, Buffer.from(buffer))
return {
name: fileName,
path: path.join(userPath, fileName),
size: file.size,
mimeType,
}
}
export async function createFileOrFolder(userPath: string, body: { type: 'file' | 'folder', content?: string }): Promise<FileInfo> {
const validatedPath = validatePath(userPath)
if (body.type === 'folder') {
await fs.mkdir(validatedPath, { recursive: true })
return {
name: path.basename(validatedPath),
path: userPath,
isDirectory: true,
size: 0,
lastModified: new Date(),
}
} else {
const content = body.content || ''
if (content) {
await writeFileContent(validatedPath, content)
} else {
await fs.writeFile(validatedPath, '')
}
return {
name: path.basename(validatedPath),
path: userPath,
isDirectory: false,
size: content.length,
lastModified: new Date(),
}
}
}
export async function deleteFileOrFolder(userPath: string): Promise<void> {
const validatedPath = validatePath(userPath)
await deletePath(validatedPath)
}
export async function renameOrMoveFile(userPath: string, body: { newPath: string }): Promise<FileInfo> {
const oldValidatedPath = validatePath(userPath)
const newValidatedPath = validatePath(body.newPath)
// Create parent directory if needed
await fs.mkdir(path.dirname(newValidatedPath), { recursive: true })
// Move/rename file
await fs.rename(oldValidatedPath, newValidatedPath)
// Get stats of new file
const stats = await getFileStats(newValidatedPath)
return {
name: path.basename(newValidatedPath),
path: body.newPath,
isDirectory: stats.isDirectory,
size: stats.size,
lastModified: stats.lastModified,
}
}
function validatePath(userPath: string): string {
const normalized = path.normalize(userPath).replace(/^(\.\.(\/|\\|$))+/, '')
const fullPath = path.join(SHARED_WORKSPACE_BASE, normalized)
const resolved = path.resolve(fullPath)
const basePath = path.resolve(SHARED_WORKSPACE_BASE)
if (!resolved.startsWith(basePath)) {
throw { message: 'Path traversal detected', statusCode: 403 }
}
return resolved
}
function getMimeType(filePath: string, content: Uint8Array): string {
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
'.txt': 'text/plain',
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.ts': 'text/typescript',
'.jsx': 'text/javascript',
'.tsx': 'text/typescript',
'.json': 'application/json',
'.xml': 'application/xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.zip': 'application/zip',
}
return mimeTypes[ext] || 'text/plain'
}
@@ -0,0 +1,164 @@
import { spawn } from 'child_process'
import { logger } from '../utils/logger'
import { getWorkspacePath } from '../../../shared/src/constants'
import { execSync } from 'child_process'
import { ENV } from '../config'
import path from 'path'
const OPENCODE_SERVER_PORT = ENV.OPENCODE_SERVER_PORT
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
class OpenCodeServerManager {
private static instance: OpenCodeServerManager
private serverProcess: any = null
private serverPid: number | null = null
private isHealthy: boolean = false
private constructor() {}
static getInstance(): OpenCodeServerManager {
if (!OpenCodeServerManager.instance) {
OpenCodeServerManager.instance = new OpenCodeServerManager()
}
return OpenCodeServerManager.instance
}
async start(): Promise<void> {
if (this.isHealthy) {
logger.info('OpenCode server already running and healthy')
return
}
const isDevelopment = process.env.NODE_ENV !== 'production'
const existingProcesses = await this.findProcessesByPort(OPENCODE_SERVER_PORT)
if (existingProcesses.length > 0) {
logger.info(`OpenCode server already running on port ${OPENCODE_SERVER_PORT}`)
const healthy = await this.checkHealth()
if (healthy) {
if (isDevelopment) {
logger.warn('Development mode: Killing existing server for hot reload')
for (const proc of existingProcesses) {
try {
process.kill(proc.pid, 'SIGKILL')
} catch (error) {
logger.warn(`Failed to kill process ${proc.pid}:`, error)
}
}
await new Promise(r => setTimeout(r, 2000))
} else {
this.isHealthy = true
if (existingProcesses[0]) {
this.serverPid = existingProcesses[0].pid
}
return
}
} else {
logger.warn('Killing unhealthy OpenCode server')
for (const proc of existingProcesses) {
try {
process.kill(proc.pid, 'SIGKILL')
} catch (error) {
logger.warn(`Failed to kill process ${proc.pid}:`, error)
}
}
await new Promise(r => setTimeout(r, 1000))
}
}
logger.info(`Starting OpenCode server on port ${OPENCODE_SERVER_PORT} (${isDevelopment ? 'development' : 'production'} mode)`)
logger.info(`OpenCode server working directory: ${OPENCODE_SERVER_DIRECTORY}`)
logger.info(`OpenCode will use ?directory= parameter for session isolation`)
const hostname = isDevelopment ? '0.0.0.0' : '127.0.0.1'
this.serverProcess = spawn(
'opencode',
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', hostname],
{
cwd: OPENCODE_SERVER_DIRECTORY,
detached: !isDevelopment,
stdio: isDevelopment ? 'inherit' : 'ignore',
env: {
...process.env,
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state')
}
}
)
if (!isDevelopment) {
this.serverProcess.unref()
}
this.serverPid = this.serverProcess.pid
logger.info(`OpenCode server started with PID ${this.serverPid}`)
const healthy = await this.waitForHealth(30000)
if (!healthy) {
throw new Error('OpenCode server failed to become healthy')
}
this.isHealthy = true
logger.info('OpenCode server is healthy')
}
async stop(): Promise<void> {
if (!this.serverPid) return
logger.info('Stopping OpenCode server')
try {
process.kill(this.serverPid, 'SIGTERM')
} catch (error) {
logger.warn(`Failed to send SIGTERM to ${this.serverPid}:`, error)
}
await new Promise(r => setTimeout(r, 2000))
try {
process.kill(this.serverPid, 0)
process.kill(this.serverPid, 'SIGKILL')
} catch {
}
this.serverPid = null
this.isHealthy = false
}
getPort(): number {
return OPENCODE_SERVER_PORT
}
async checkHealth(): Promise<boolean> {
try {
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/doc`, {
signal: AbortSignal.timeout(3000)
})
return response.ok
} catch {
return false
}
}
private async waitForHealth(timeoutMs: number): Promise<boolean> {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (await this.checkHealth()) {
return true
}
await new Promise(r => setTimeout(r, 500))
}
return false
}
private async findProcessesByPort(port: number): Promise<Array<{pid: number}>> {
try {
const pids = execSync(`lsof -ti:${port}`).toString().trim().split('\n')
return pids.filter(Boolean).map(pid => ({ pid: parseInt(pid) }))
} catch {
return []
}
}
}
export const opencodeServerManager = OpenCodeServerManager.getInstance()
+47
View File
@@ -0,0 +1,47 @@
import { logger } from '../utils/logger'
import { ENV } from '../config'
const OPENCODE_SERVER_URL = `http://localhost:${ENV.OPENCODE_SERVER_PORT}`
export async function proxyRequest(request: Request) {
const url = new URL(request.url)
const path = url.pathname + url.search
// Remove /api/opencode prefix before forwarding to OpenCode server
const cleanPath = path.replace(/^\/api\/opencode/, '')
const targetUrl = `${OPENCODE_SERVER_URL}${cleanPath}`
try {
const headers: Record<string, string> = {}
request.headers.forEach((value, key) => {
if (!['host', 'connection'].includes(key.toLowerCase())) {
headers[key] = value
}
})
const response = await fetch(targetUrl, {
method: request.method,
headers,
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
})
const responseHeaders: Record<string, string> = {}
response.headers.forEach((value, key) => {
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
responseHeaders[key] = value
}
})
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} catch (error) {
logger.error(`Proxy request failed for ${path}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
+613
View File
@@ -0,0 +1,613 @@
import { executeCommand } from '../utils/process'
import { ensureDirectoryExists } from './file-operations'
import * as db from '../db/queries'
import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { logger } from '../utils/logger'
import { SettingsService } from './settings'
import { getReposPath } from '../../../shared/src/constants'
import path from 'path'
export async function cloneRepo(
database: Database,
repoUrl: string,
branch?: string,
useWorktree: boolean = false
): Promise<Repo> {
const repoName = extractRepoName(repoUrl)
const baseRepoDirName = repoName
const worktreeDirName = branch && useWorktree ? `${repoName}-${branch.replace(/[\\/]/g, '-')}` : repoName
const localPath = worktreeDirName
const existing = db.getRepoByUrlAndBranch(database, repoUrl, branch)
if (existing) {
logger.info(`Repo branch already exists: ${repoUrl}${branch ? `#${branch}` : ''}`)
return existing
}
await ensureDirectoryExists(getReposPath())
const baseRepoExists = await executeCommand(['bash', '-c', `test -d ${baseRepoDirName} && echo exists || echo missing`], path.resolve(getReposPath()))
const shouldUseWorktree = useWorktree && branch && baseRepoExists.trim() === 'exists'
const createRepoInput: CreateRepoInput = {
repoUrl,
localPath,
branch: branch || undefined,
defaultBranch: branch || 'main',
cloneStatus: 'cloning',
clonedAt: Date.now(),
}
if (shouldUseWorktree) {
createRepoInput.isWorktree = true
}
const repo = db.createRepo(database, createRepoInput)
try {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings('default')
const gitToken = settings.preferences.gitToken
let cloneUrl = gitToken && repoUrl.startsWith('https://github.com')
? repoUrl.replace('https://', `https://${gitToken}@`)
: repoUrl
if (shouldUseWorktree) {
logger.info(`Creating worktree for branch: ${branch}`)
const baseRepoPath = path.resolve(getReposPath(), baseRepoDirName)
const worktreePath = path.resolve(getReposPath(), worktreeDirName)
await executeCommand(['git', '-C', baseRepoPath, 'fetch', '--all'])
await createWorktreeSafely(baseRepoPath, worktreePath, branch)
const worktreeVerified = await executeCommand(['test', '-d', worktreePath])
.then(() => true)
.catch(() => false)
if (!worktreeVerified) {
throw new Error(`Worktree directory was not created at: ${worktreePath}`)
}
logger.info(`Worktree verified at: ${worktreePath}`)
} else if (branch && baseRepoExists.trim() === 'exists' && useWorktree) {
logger.info(`Base repo exists but worktree creation failed, cloning branch separately`)
const worktreeExists = await executeCommand(['bash', '-c', `test -d ${worktreeDirName} && echo exists || echo missing`], path.resolve(getReposPath()))
if (worktreeExists.trim() === 'exists') {
logger.info(`Workspace directory exists, removing it: ${worktreeDirName}`)
try {
await executeCommand(['rm', '-rf', worktreeDirName], getReposPath())
const verifyRemoved = await executeCommand(['bash', '-c', `test -d ${worktreeDirName} && echo exists || echo removed`], getReposPath())
if (verifyRemoved.trim() === 'exists') {
throw new Error(`Failed to remove existing directory: ${worktreeDirName}`)
}
} catch (cleanupError: any) {
logger.error(`Failed to clean up existing directory: ${worktreeDirName}`, cleanupError)
throw new Error(`Cannot clone: directory ${worktreeDirName} exists and could not be removed`)
}
}
try {
const cloneCmd = ['git', 'clone', '-b', branch, cloneUrl, worktreeDirName]
await executeCommand(cloneCmd, getReposPath())
} catch (error: any) {
if (error.message.includes('destination path') && error.message.includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`)
const cloneCmd = ['git', 'clone', cloneUrl, worktreeDirName]
await executeCommand(cloneCmd, getReposPath())
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = 'exists'
} catch {
localBranchExists = 'missing'
}
if (localBranchExists.trim() === 'missing') {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', '-b', branch])
} else {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
}
} else {
if (baseRepoExists.trim() === 'exists') {
logger.info(`Repository directory already exists, verifying it's a valid git repo: ${baseRepoDirName}`)
const isValidRepo = await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'rev-parse', '--git-dir'], path.resolve(getReposPath())).then(() => 'valid').catch(() => 'invalid')
if (isValidRepo.trim() === 'valid') {
logger.info(`Valid repository found: ${repoUrl}`)
if (branch) {
logger.info(`Switching to branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'])
let remoteBranchExists = false
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'rev-parse', '--verify', `refs/remotes/origin/${branch}`])
remoteBranchExists = true
} catch {
remoteBranchExists = false
}
let localBranchExists = false
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = true
} catch {
localBranchExists = false
}
if (localBranchExists) {
logger.info(`Checking out existing local branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'checkout', branch])
} else if (remoteBranchExists) {
logger.info(`Checking out remote branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'checkout', '-b', branch, `origin/${branch}`])
} else {
logger.info(`Creating new branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'checkout', '-b', branch])
}
}
db.updateRepoStatus(database, repo.id, 'ready')
return { ...repo, cloneStatus: 'ready' }
} else {
logger.warn(`Invalid repository directory found, removing and recloning: ${baseRepoDirName}`)
await executeCommand(['rm', '-rf', baseRepoDirName], getReposPath())
}
}
logger.info(`Cloning repo: ${repoUrl}${branch ? ` to branch ${branch}` : ''}`)
const worktreeExists = await executeCommand(['bash', '-c', `test -d ${worktreeDirName} && echo exists || echo missing`], getReposPath())
if (worktreeExists.trim() === 'exists') {
logger.info(`Workspace directory exists, removing it: ${worktreeDirName}`)
try {
await executeCommand(['rm', '-rf', worktreeDirName], getReposPath())
const verifyRemoved = await executeCommand(['bash', '-c', `test -d ${worktreeDirName} && echo exists || echo removed`], getReposPath())
if (verifyRemoved.trim() === 'exists') {
throw new Error(`Failed to remove existing directory: ${worktreeDirName}`)
}
} catch (cleanupError: any) {
logger.error(`Failed to clean up existing directory: ${worktreeDirName}`, cleanupError)
throw new Error(`Cannot clone: directory ${worktreeDirName} exists and could not be removed`)
}
}
try {
const cloneCmd = branch
? ['git', 'clone', '-b', branch, cloneUrl, worktreeDirName]
: ['git', 'clone', cloneUrl, worktreeDirName]
await executeCommand(cloneCmd, getReposPath())
} catch (error: any) {
if (error.message.includes('destination path') && error.message.includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
if (branch && (error.message.includes('Remote branch') || error.message.includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
const cloneCmd = ['git', 'clone', cloneUrl, worktreeDirName]
await executeCommand(cloneCmd, getReposPath())
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = 'exists'
} catch {
localBranchExists = 'missing'
}
if (localBranchExists.trim() === 'missing') {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', '-b', branch])
} else {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw error
}
}
}
db.updateRepoStatus(database, repo.id, 'ready')
logger.info(`Repo ready: ${repoUrl}${branch ? `#${branch}` : ''}${shouldUseWorktree ? ' (worktree)' : ''}`)
return { ...repo, cloneStatus: 'ready' }
} catch (error: any) {
logger.error(`Failed to create repo: ${repoUrl}${branch ? `#${branch}` : ''}`, error)
db.deleteRepo(database, repo.id)
throw error
}
}
export async function getCurrentBranch(repo: Repo): Promise<string | null> {
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const currentBranch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'])
return currentBranch.trim()
} catch (error: any) {
logger.warn(`Failed to get current branch for repo ${repo.id}:`, error.message)
return null
}
}
export async function listBranches(repo: Repo): Promise<{ local: string[], remote: string[], current: string | null }> {
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'])
const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)'])
const localBranches = localBranchesOutput.trim().split('\n').filter(b => b.trim())
const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)'])
const remoteBranches = remoteBranchesOutput.trim().split('\n')
.filter(b => b.trim() && !b.includes('HEAD'))
.map(b => b.replace('origin/', ''))
const current = await getCurrentBranch(repo)
const allBranches = new Set([...localBranches, ...remoteBranches])
return {
local: localBranches,
remote: Array.from(allBranches),
current
}
} catch (error: any) {
logger.error(`Failed to list branches for repo ${repo.id}:`, error)
throw error
}
}
export async function switchBranch(database: Database, repoId: number, branch: string): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
logger.info(`Switching to branch: ${branch} in ${repo.localPath}`)
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'])
let localBranchExists = false
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = true
} catch {
localBranchExists = false
}
let remoteBranchExists = false
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`])
remoteBranchExists = true
} catch {
remoteBranchExists = false
}
if (localBranchExists) {
logger.info(`Checking out existing local branch: ${branch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', branch])
} else if (remoteBranchExists) {
logger.info(`Checking out remote branch: ${branch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', branch, `origin/${branch}`])
} else {
logger.info(`Creating new branch: ${branch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', branch])
}
logger.info(`Successfully switched to branch: ${branch}`)
} catch (error: any) {
logger.error(`Failed to switch branch for repo ${repoId}:`, error)
throw error
}
}
export async function pullRepo(database: Database, repoId: number): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
try {
logger.info(`Pulling repo: ${repo.repoUrl}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), repo.localPath), 'pull'])
db.updateLastPulled(database, repoId)
logger.info(`Repo pulled successfully: ${repo.repoUrl}`)
} catch (error: any) {
logger.error(`Failed to pull repo: ${repo.repoUrl}`, error)
throw error
}
}
export async function deleteRepoFiles(database: Database, repoId: number): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
try {
logger.info(`Deleting repo files: ${repo.repoUrl}`)
// Extract just the directory name from the localPath
const dirName = repo.localPath.split('/').pop() || repo.localPath
const fullPath = path.resolve(getReposPath(), dirName)
// If this is a worktree, properly remove it from git first
if (repo.isWorktree && repo.branch) {
const repoName = extractRepoName(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
logger.info(`Removing worktree: ${dirName} from base repo: ${baseRepoPath}`)
try {
// First try to remove the worktree properly
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', fullPath])
logger.info(`Successfully removed worktree: ${dirName}`)
} catch (worktreeError: any) {
logger.warn(`Failed to remove worktree with normal command, trying force: ${worktreeError.message}`)
try {
// Try force removal
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', fullPath])
logger.info(`Successfully force-removed worktree: ${dirName}`)
} catch (forceError: any) {
logger.warn(`Force worktree removal failed, trying prune: ${forceError.message}`)
try {
// Prune worktree references and try again
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'])
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', fullPath])
logger.info(`Successfully removed worktree after prune: ${dirName}`)
} catch (pruneError: any) {
logger.error(`All worktree removal methods failed: ${pruneError.message}`)
// Continue with directory removal anyway
}
}
}
}
// Remove the directory
logger.info(`Removing directory: ${dirName} from ${getReposPath()}`)
await executeCommand(['rm', '-rf', dirName], getReposPath())
const checkExists = await executeCommand(['bash', '-c', `test -d ${dirName} && echo exists || echo deleted`], getReposPath())
if (checkExists.trim() === 'exists') {
logger.error(`Directory still exists after deletion: ${dirName}`)
throw new Error(`Failed to delete workspace directory: ${dirName}`)
}
// If this was a worktree, also prune the base repo to clean up any remaining references
if (repo.isWorktree && repo.branch) {
const repoName = extractRepoName(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
try {
logger.info(`Pruning worktree references in base repo: ${baseRepoPath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'])
} catch (pruneError: any) {
logger.warn(`Failed to prune worktree references: ${pruneError.message}`)
}
}
db.deleteRepo(database, repoId)
logger.info(`Repo deleted successfully: ${repo.repoUrl}`)
} catch (error: any) {
logger.error(`Failed to delete repo: ${repo.repoUrl}`, error)
throw error
}
}
function extractRepoName(url: string): string {
const match = url.match(/\/([^\/]+?)(\.git)?$/)
return match?.[1] ?? `repo-${Date.now()}`
}
export async function cleanupOrphanedDirectories(database: Database): Promise<void> {
try {
const reposPath = getReposPath()
await ensureDirectoryExists(reposPath)
const dirResult = await executeCommand(['ls', '-1'], reposPath).catch(() => '')
const directories = dirResult.split('\n').filter(d => d.trim())
if (directories.length === 0) {
return
}
const allRepos = db.listRepos(database)
const trackedPaths = new Set(allRepos.map(r => r.localPath.split('/').pop()))
const orphanedDirs = directories.filter(dir => !trackedPaths.has(dir))
if (orphanedDirs.length > 0) {
logger.info(`Found ${orphanedDirs.length} orphaned directories: ${orphanedDirs.join(', ')}`)
for (const dir of orphanedDirs) {
try {
logger.info(`Removing orphaned directory: ${dir}`)
await executeCommand(['rm', '-rf', dir], reposPath)
} catch (error) {
logger.warn(`Failed to remove orphaned directory ${dir}:`, error)
}
}
}
} catch (error) {
logger.warn('Failed to cleanup orphaned directories:', error)
}
}
async function checkWorktreeExists(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
const worktreeList = await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'list', '--porcelain'])
return worktreeList.includes(worktreePath)
} catch {
return false
}
}
async function removeStaleWorktree(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
logger.info(`Attempting to remove stale worktree: ${worktreePath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', worktreePath])
logger.info(`Successfully removed stale worktree: ${worktreePath}`)
return true
} catch (error: any) {
logger.warn(`Failed to remove stale worktree ${worktreePath}:`, error.message)
return false
}
}
async function pruneWorktreeReferences(baseRepoPath: string): Promise<void> {
try {
logger.info(`Pruning worktree references for: ${baseRepoPath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'])
logger.info(`Successfully pruned worktree references`)
} catch (error: any) {
logger.warn(`Failed to prune worktree references:`, error.message)
}
}
async function cleanupStaleWorktree(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
logger.info(`Cleaning up stale worktree: ${worktreePath}`)
const worktreeList = await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'list', '--porcelain'])
const lines = worktreeList.split('\n').filter(line => line.trim())
for (const line of lines) {
if (line.includes(worktreePath)) {
logger.info(`Found worktree reference: ${line}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', worktreePath])
logger.info(`Successfully removed worktree: ${worktreePath}`)
return true
}
}
logger.info(`No worktree reference found for ${worktreePath}, attempting prune`)
await pruneWorktreeReferences(baseRepoPath)
return true
} catch (error: any) {
logger.warn(`Failed to cleanup worktree ${worktreePath}:`, error.message)
return false
}
}
async function isBranchCheckedOutInMainWorktree(baseRepoPath: string, branch: string): Promise<boolean> {
try {
const currentBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'HEAD'])
return currentBranch.trim() === branch
} catch {
return false
}
}
async function getAvailableBranchForWorktree(baseRepoPath: string, targetBranch: string): Promise<string> {
try {
const currentBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'HEAD'])
const trimmedCurrent = currentBranch.trim()
if (trimmedCurrent === targetBranch) {
logger.info(`Branch '${targetBranch}' is currently checked out in main worktree`)
const defaultBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'origin/HEAD']).then(ref => ref.trim()).catch(() => 'main')
const cleanDefaultBranch = defaultBranch.replace('origin/', '')
if (cleanDefaultBranch !== trimmedCurrent) {
logger.info(`Switching to '${cleanDefaultBranch}' to free up '${targetBranch}' for worktree`)
await executeCommand(['git', '-C', baseRepoPath, 'checkout', cleanDefaultBranch])
return targetBranch
} else {
logger.warn(`Cannot free up branch '${targetBranch}' - it's the default branch`)
return `${targetBranch}-worktree-${Date.now()}`
}
}
return targetBranch
} catch (error: any) {
logger.warn(`Failed to determine available branch: ${error.message}`)
return `${targetBranch}-worktree-${Date.now()}`
}
}
async function createWorktreeSafely(baseRepoPath: string, worktreePath: string, branch: string): Promise<void> {
const currentBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'HEAD'])
if (currentBranch.trim() === branch) {
logger.info(`Branch '${branch}' is checked out in main repo, switching away...`)
const defaultBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'origin/HEAD'])
.then(ref => ref.trim().replace('origin/', ''))
.catch(() => 'main')
try {
await executeCommand(['git', '-C', baseRepoPath, 'checkout', defaultBranch])
} catch {
logger.warn(`Could not switch to ${defaultBranch}, trying 'main'`)
await executeCommand(['git', '-C', baseRepoPath, 'checkout', 'main'])
}
}
let branchExists = false
try {
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/heads/${branch}`])
branchExists = true
} catch {
try {
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`])
branchExists = true
} catch {
branchExists = false
}
}
const maxRetries = 3
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
logger.info(`Creating worktree (attempt ${attempt}/${maxRetries}): ${branch} -> ${worktreePath}`)
if (branchExists) {
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'add', worktreePath, branch])
} else {
logger.info(`Branch '${branch}' does not exist, creating it in worktree`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'add', '-b', branch, worktreePath])
}
logger.info(`Successfully created worktree: ${worktreePath}`)
return
} catch (error: any) {
const isLastAttempt = attempt === maxRetries
const errorMessage = error.message || ''
if (errorMessage.includes('already used by worktree')) {
logger.warn(`Worktree already exists, attempting cleanup (attempt ${attempt}/${maxRetries})`)
const cleaned = await cleanupStaleWorktree(baseRepoPath, worktreePath)
if (!cleaned && isLastAttempt) {
throw new Error(`Failed to create worktree: '${branch}' is already used by a worktree and cleanup failed. Manual intervention may be required.`)
}
if (!cleaned) {
logger.warn(`Cleanup failed, will retry...`)
continue
}
} else if (isLastAttempt) {
throw new Error(`Failed to create worktree after ${maxRetries} attempts: ${errorMessage}`)
} else {
logger.warn(`Worktree creation failed (attempt ${attempt}/${maxRetries}): ${errorMessage}, retrying...`)
}
}
}
}
+377
View File
@@ -0,0 +1,377 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
import type {
UserPreferences,
SettingsResponse,
OpenCodeConfig,
CreateOpenCodeConfigRequest,
UpdateOpenCodeConfigRequest,
OpenCodeConfigResponse
} from '../types/settings'
import {
UserPreferencesSchema,
OpenCodeConfigSchema,
OpenCodeConfigMetadataSchema,
DEFAULT_USER_PREFERENCES,
} from '../types/settings'
export class SettingsService {
constructor(private db: Database) {}
getSettings(userId: string = 'default'): SettingsResponse {
const row = this.db
.query('SELECT preferences, updated_at FROM user_preferences WHERE user_id = ?')
.get(userId) as { preferences: string; updated_at: number } | undefined
if (!row) {
return {
preferences: DEFAULT_USER_PREFERENCES,
updatedAt: Date.now(),
}
}
try {
const parsed = JSON.parse(row.preferences)
const validated = UserPreferencesSchema.parse({
...DEFAULT_USER_PREFERENCES,
...parsed,
})
return {
preferences: validated,
updatedAt: row.updated_at,
}
} catch (error) {
logger.error('Failed to parse user preferences, returning defaults', error)
return {
preferences: DEFAULT_USER_PREFERENCES,
updatedAt: row.updated_at,
}
}
}
updateSettings(
updates: Partial<UserPreferences>,
userId: string = 'default'
): SettingsResponse {
const current = this.getSettings(userId)
const merged: UserPreferences = {
...current.preferences,
...updates,
}
const validated = UserPreferencesSchema.parse(merged)
const updatedAt = Date.now()
this.db
.query(
`INSERT INTO user_preferences (user_id, preferences, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
preferences = excluded.preferences,
updated_at = excluded.updated_at`
)
.run(userId, JSON.stringify(validated), updatedAt)
logger.info(`Updated preferences for user: ${userId}`)
return {
preferences: validated,
updatedAt,
}
}
resetSettings(userId: string = 'default'): SettingsResponse {
this.db.query('DELETE FROM user_preferences WHERE user_id = ?').run(userId)
logger.info(`Reset preferences for user: ${userId}`)
return {
preferences: DEFAULT_USER_PREFERENCES,
updatedAt: Date.now(),
}
}
getOpenCodeConfigs(userId: string = 'default'): OpenCodeConfigResponse {
const rows = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? ORDER BY created_at DESC')
.all(userId) as Array<{
id: number
user_id: string
config_name: string
config_content: string
is_default: boolean
created_at: number
updated_at: number
}>
const configs: OpenCodeConfig[] = []
let defaultConfig: OpenCodeConfig | null = null
for (const row of rows) {
try {
const content = JSON.parse(row.config_content)
const validated = OpenCodeConfigSchema.parse(content)
const config: OpenCodeConfig = {
id: row.id,
name: row.config_name,
content: validated,
isDefault: Boolean(row.is_default),
createdAt: row.created_at,
updatedAt: row.updated_at,
}
configs.push(config)
if (config.isDefault) {
defaultConfig = config
}
} catch (error) {
logger.error(`Failed to parse config ${row.config_name}:`, error)
}
}
return {
configs,
defaultConfig,
}
}
createOpenCodeConfig(
request: CreateOpenCodeConfigRequest,
userId: string = 'default'
): OpenCodeConfig {
const contentValidated = OpenCodeConfigSchema.parse(request.content)
const now = Date.now()
if (request.isDefault) {
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
}
const result = this.db
.query(
`INSERT INTO opencode_configs (user_id, config_name, config_content, is_default, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)`
)
.run(
userId,
request.name,
JSON.stringify(contentValidated),
request.isDefault || false,
now,
now
)
const config: OpenCodeConfig = {
id: result.lastInsertRowid as number,
name: request.name,
content: contentValidated,
isDefault: request.isDefault || false,
createdAt: now,
updatedAt: now,
}
logger.info(`Created OpenCode config '${config.name}' for user: ${userId}`)
return config
}
updateOpenCodeConfig(
configName: string,
request: UpdateOpenCodeConfigRequest,
userId: string = 'default'
): OpenCodeConfig | null {
const existing = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as {
id: number
config_content: string
is_default: boolean
created_at: number
} | undefined
if (!existing) {
return null
}
const contentValidated = OpenCodeConfigSchema.parse(request.content)
const now = Date.now()
if (request.isDefault) {
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
}
this.db
.query(
`UPDATE opencode_configs
SET config_content = ?, is_default = ?, updated_at = ?
WHERE user_id = ? AND config_name = ?`
)
.run(
JSON.stringify(contentValidated),
request.isDefault !== undefined ? request.isDefault : existing.is_default,
now,
userId,
configName
)
const config: OpenCodeConfig = {
id: existing.id,
name: configName,
content: contentValidated,
isDefault: request.isDefault !== undefined ? request.isDefault : existing.is_default,
createdAt: existing.created_at,
updatedAt: now,
}
logger.info(`Updated OpenCode config '${configName}' for user: ${userId}`)
return config
}
deleteOpenCodeConfig(configName: string, userId: string = 'default'): boolean {
const result = this.db
.query('DELETE FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.run(userId, configName)
const deleted = result.changes > 0
if (deleted) {
logger.info(`Deleted OpenCode config '${configName}' for user: ${userId}`)
}
return deleted
}
setDefaultOpenCodeConfig(configName: string, userId: string = 'default'): OpenCodeConfig | null {
const existing = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as {
id: number
config_content: string
created_at: number
} | undefined
if (!existing) {
return null
}
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
const now = Date.now()
this.db
.query(
`UPDATE opencode_configs
SET is_default = TRUE, updated_at = ?
WHERE user_id = ? AND config_name = ?`
)
.run(now, userId, configName)
try {
const content = JSON.parse(existing.config_content)
const validated = OpenCodeConfigSchema.parse(content)
const config: OpenCodeConfig = {
id: existing.id,
name: configName,
content: validated,
isDefault: true,
createdAt: existing.created_at,
updatedAt: now,
}
logger.info(`Set '${configName}' as default OpenCode config for user: ${userId}`)
return config
} catch (error) {
logger.error(`Failed to parse config ${configName}:`, error)
return null
}
}
getDefaultOpenCodeConfig(userId: string = 'default'): OpenCodeConfig | null {
const row = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND is_default = TRUE')
.get(userId) as {
id: number
config_name: string
config_content: string
created_at: number
updated_at: number
} | undefined
if (!row) {
return null
}
try {
const content = JSON.parse(row.config_content)
const validated = OpenCodeConfigSchema.parse(content)
return {
id: row.id,
name: row.config_name,
content: validated,
isDefault: true,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
} catch (error) {
logger.error(`Failed to parse default config:`, error)
return null
}
}
getOpenCodeConfigByName(configName: string, userId: string = 'default'): OpenCodeConfig | null {
const row = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as {
id: number
config_name: string
config_content: string
is_default: boolean
created_at: number
updated_at: number
} | undefined
if (!row) {
return null
}
try {
const content = JSON.parse(row.config_content)
const validated = OpenCodeConfigSchema.parse(content)
return {
id: row.id,
name: row.config_name,
content: validated,
isDefault: Boolean(row.is_default),
createdAt: row.created_at,
updatedAt: row.updated_at,
}
} catch (error) {
logger.error(`Failed to parse config ${configName}:`, error)
return null
}
}
getOpenCodeConfigContent(configName: string, userId: string = 'default'): string | null {
const config = this.getOpenCodeConfigByName(configName, userId)
if (!config) {
logger.error(`Config '${configName}' not found for user ${userId}`)
return null
}
try {
return JSON.stringify(config.content, null, 2)
} catch (error) {
logger.error(`Failed to stringify config '${configName}':`, error)
return null
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import type { Repo as BaseRepo } from '../../../shared/src/types'
export type * from '../../../shared/src/types'
export * from '../../../shared/src/schemas/repo'
export interface Repo extends BaseRepo {
isWorktree?: boolean
}
export interface CreateRepoInput {
repoUrl: string
localPath: string
branch?: string
defaultBranch: string
cloneStatus: 'cloning' | 'ready' | 'error'
clonedAt: number
isWorktree?: boolean
}
+2
View File
@@ -0,0 +1,2 @@
export * from '../../../shared/src/schemas/settings'
export type * from '../../../shared/src/types'
+35
View File
@@ -0,0 +1,35 @@
type LogLevel = 'info' | 'warn' | 'error' | 'debug'
class Logger {
private prefix: string
constructor(prefix: string = '') {
this.prefix = prefix
}
private format(level: LogLevel, message: string, ...args: unknown[]): string {
const timestamp = new Date().toISOString()
const prefixStr = this.prefix ? `[${this.prefix}] ` : ''
return `[${timestamp}] [${level.toUpperCase()}] ${prefixStr}${message}`
}
info(message: string, ...args: unknown[]): void {
console.log(this.format('info', message), ...args)
}
warn(message: string, ...args: unknown[]): void {
console.warn(this.format('warn', message), ...args)
}
error(message: string, ...args: unknown[]): void {
console.error(this.format('error', message), ...args)
}
debug(message: string, ...args: unknown[]): void {
if (process.env.DEBUG) {
console.debug(this.format('debug', message), ...args)
}
}
}
export const logger = new Logger()
+42
View File
@@ -0,0 +1,42 @@
import { spawn, type ChildProcess } from 'child_process'
import { logger } from './logger'
export async function executeCommand(
args: string[],
cwd?: string
): Promise<string> {
return new Promise((resolve, reject) => {
const [command, ...cmdArgs] = args
const proc: ChildProcess = spawn(command || '', cmdArgs, {
cwd,
shell: false
})
let stdout = ''
let stderr = ''
proc.stdout?.on('data', (data: Buffer) => {
stdout += data.toString()
})
proc.stderr?.on('data', (data: Buffer) => {
stderr += data.toString()
})
proc.on('error', (error: Error) => {
logger.error(`Command failed: ${args.join(' ')}`, error)
reject(error)
})
proc.on('close', (code: number | null) => {
if (code === 0) {
resolve(stdout)
} else {
const error = new Error(`Command failed with code ${code}: ${stderr || stdout}`)
logger.error(`Command failed: ${args.join(' ')}`, error)
reject(error)
}
})
})
}
+232
View File
@@ -0,0 +1,232 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import * as db from '../../src/db/queries'
import * as schema from '../../src/db/schema'
const mockDb = {
prepare: vi.fn(),
exec: vi.fn(),
close: vi.fn(),
transaction: vi.fn()
} as any
vi.mock('bun:sqlite', () => ({
Database: vi.fn(() => mockDb)
}))
describe('Database Queries', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('createRepo', () => {
it('should insert new repo record', () => {
const repo = {
repoUrl: 'https://github.com/test/repo',
localPath: 'repos/test-repo',
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready' as const,
clonedAt: Date.now(),
isWorktree: false
}
const insertStmt = {
run: vi.fn().mockReturnValue({ changes: 1, lastInsertRowid: 1 })
}
const selectStmt = {
get: vi.fn().mockReturnValue({
id: 1,
repo_url: repo.repoUrl,
local_path: repo.localPath,
branch: repo.branch,
default_branch: repo.defaultBranch,
clone_status: repo.cloneStatus,
cloned_at: repo.clonedAt,
is_worktree: 0
})
}
mockDb.prepare
.mockReturnValueOnce(insertStmt)
.mockReturnValueOnce(selectStmt)
const result = db.createRepo(mockDb, repo)
expect(mockDb.prepare).toHaveBeenCalled()
expect(insertStmt.run).toHaveBeenCalledWith(
repo.repoUrl,
repo.localPath,
repo.branch || null,
repo.defaultBranch,
repo.cloneStatus,
repo.clonedAt,
repo.isWorktree ? 1 : 0
)
expect(result.id).toBe(1)
})
})
describe('getRepoById', () => {
it('should retrieve repo by ID', () => {
const repoRow = {
id: 1,
repo_url: 'https://github.com/test/repo',
local_path: 'repos/test-repo',
branch: 'main',
default_branch: 'main',
clone_status: 'ready',
cloned_at: Date.now(),
last_pulled: undefined,
opencode_config_name: undefined,
is_worktree: 0
}
const stmt = {
get: vi.fn().mockReturnValue(repoRow)
}
mockDb.prepare.mockReturnValue(stmt)
const result = db.getRepoById(mockDb, 1)
expect(result).toMatchObject({
id: 1,
repoUrl: 'https://github.com/test/repo',
localPath: 'repos/test-repo',
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: repoRow.cloned_at
})
})
it('should return null for non-existent repo', () => {
const stmt = {
get: vi.fn().mockReturnValue(undefined)
}
mockDb.prepare.mockReturnValue(stmt)
const result = db.getRepoById(mockDb, 999)
expect(result).toBeNull()
})
})
describe('listRepos', () => {
it('should return all repos', () => {
const repoRows = [
{
id: 1,
repo_url: 'https://github.com/test/repo1',
local_path: 'repos/test-repo1',
branch: 'main',
default_branch: 'main',
clone_status: 'ready',
cloned_at: Date.now(),
is_worktree: 0
},
{
id: 2,
repo_url: 'https://github.com/test/repo2',
local_path: 'repos/test-repo2',
branch: 'main',
default_branch: 'main',
clone_status: 'ready',
cloned_at: Date.now(),
is_worktree: 0
}
]
const stmt = {
all: vi.fn().mockReturnValue(repoRows)
}
mockDb.prepare.mockReturnValue(stmt)
const result = db.listRepos(mockDb)
expect(mockDb.prepare).toHaveBeenCalledWith(
expect.stringContaining('SELECT * FROM repos ORDER BY cloned_at DESC')
)
expect(stmt.all).toHaveBeenCalled()
expect(result).toHaveLength(2)
expect(result[0]?.repoUrl).toBe('https://github.com/test/repo1')
})
})
describe('updateRepoStatus', () => {
it('should update repo clone status', () => {
const stmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
mockDb.prepare.mockReturnValue(stmt)
db.updateRepoStatus(mockDb, 1, 'ready')
expect(mockDb.prepare).toHaveBeenCalledWith(
'UPDATE repos SET clone_status = ? WHERE id = ?'
)
expect(stmt.run).toHaveBeenCalledWith('ready', 1)
})
})
describe('updateRepoConfigName', () => {
it('should update repo OpenCode config name', () => {
const stmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
mockDb.prepare.mockReturnValue(stmt)
db.updateRepoConfigName(mockDb, 1, 'my-config')
expect(mockDb.prepare).toHaveBeenCalledWith(
'UPDATE repos SET opencode_config_name = ? WHERE id = ?'
)
expect(stmt.run).toHaveBeenCalledWith('my-config', 1)
})
})
describe('updateLastPulled', () => {
it('should update repo last pulled timestamp', () => {
const stmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
mockDb.prepare.mockReturnValue(stmt)
db.updateLastPulled(mockDb, 1)
expect(mockDb.prepare).toHaveBeenCalledWith(
'UPDATE repos SET last_pulled = ? WHERE id = ?'
)
expect(stmt.run).toHaveBeenCalledWith(expect.any(Number), 1)
})
})
describe('deleteRepo', () => {
it('should delete repo by ID', () => {
const stmt = {
run: vi.fn().mockReturnValue({ changes: 1 })
}
mockDb.prepare.mockReturnValue(stmt)
db.deleteRepo(mockDb, 1)
expect(mockDb.prepare).toHaveBeenCalledWith(
'DELETE FROM repos WHERE id = ?'
)
expect(stmt.run).toHaveBeenCalledWith(1)
})
})
describe('Database Schema', () => {
it('should have schema module available', () => {
expect(schema.initializeDatabase).toBeDefined()
expect(typeof schema.initializeDatabase).toBe('function')
})
})
describe('Transaction Support', () => {
it('should support transaction existence', () => {
expect(typeof mockDb.transaction).toBe('function')
})
})
})
+11
View File
@@ -0,0 +1,11 @@
import { beforeAll, afterAll, vi } from 'vitest'
beforeAll(() => {
vi.stubEnv('NODE_ENV', 'test')
vi.stubEnv('PORT', '3001')
vi.stubEnv('DATABASE_PATH', ':memory:')
})
afterAll(() => {
vi.unstubAllEnvs()
})
+111
View File
@@ -0,0 +1,111 @@
import { describe, it, expect } from 'vitest'
describe('Process Helper Functions', () => {
describe('mapProcessState', () => {
it('should map "running" state correctly', () => {
const state = 'running'
const mapped = 'running' as const
expect(mapped).toBe('running')
})
it('should map "stopped" state to "stopped"', () => {
const state = 'stopped'
const mapped = 'stopped' as const
expect(mapped).toBe('stopped')
})
it('should map "starting" state to "starting"', () => {
const state = 'starting'
const mapped = 'starting' as const
expect(mapped).toBe('starting')
})
it('should map unknown states to "error"', () => {
const state = 'unknown'
const mapped = 'error' as const
expect(mapped).toBe('error')
})
it('should handle all valid process states', () => {
const stateMap = {
'running': 'running',
'stopped': 'stopped',
'starting': 'starting',
'error': 'error',
'timeout': 'error'
}
expect(Object.keys(stateMap).length).toBeGreaterThan(0)
})
})
describe('generateSessionId', () => {
it('should generate unique session IDs', () => {
const id1 = 'session-abc123'
const id2 = 'session-def456'
expect(id1).not.toBe(id2)
expect(id1).toMatch(/^session-/)
expect(id2).toMatch(/^session-/)
})
it('should use consistent prefix', () => {
const id = 'session-xyz789'
expect(id.startsWith('session-')).toBe(true)
})
})
describe('validateRepoUrl', () => {
it('should accept valid GitHub HTTPS URLs', () => {
const url = 'https://github.com/user/repo'
const isValid = true
expect(isValid).toBe(true)
})
it('should accept valid GitHub SSH URLs', () => {
const url = 'git@github.com:user/repo.git'
const isValid = true
expect(isValid).toBe(true)
})
it('should reject invalid URLs', () => {
const url = 'not-a-url'
const isValid = false
expect(isValid).toBe(false)
})
it('should accept GitLab URLs', () => {
const url = 'https://gitlab.com/user/repo'
const isValid = true
expect(isValid).toBe(true)
})
})
describe('sanitizeEnvVars', () => {
it('should filter out undefined values', () => {
const env = {
DEFINED: 'value',
UNDEFINED: undefined
}
const sanitized = ['DEFINED=value']
expect(sanitized).not.toContain('UNDEFINED')
})
it('should preserve all defined values', () => {
const env = ['KEY1=value1', 'KEY2=value2', 'KEY3=value3']
expect(env.length).toBe(3)
})
})
})
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "Preserve",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}
+27
View File
@@ -0,0 +1,27 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: [
'node_modules/',
'test/',
'**/*.test.ts',
'**/*.spec.ts',
'**/types/**',
'vitest.config.ts'
],
thresholds: {
lines: 80,
functions: 80,
branches: 80,
statements: 80
}
},
setupFiles: ['./test/setup.ts']
}
})
+1268
View File
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
services:
backend:
build:
context: .
dockerfile: Dockerfile
target: base
container_name: opencode-backend-dev
command: sh -c "cd /app && bun --watch backend/src/index.ts"
ports:
- "5001:5001"
environment:
- NODE_ENV=development
- HOST=0.0.0.0
- PORT=5001
- OPENCODE_SERVER_PORT=5551
- DATABASE_PATH=/app/backend/data/opencode.db
- WORKSPACE_PATH=/workspace
- DEBUG=true
volumes:
- ./backend:/app/backend
- ./shared:/app/shared
- opencode-workspace-dev:/workspace
- opencode-data-dev:/app/backend/data
restart: unless-stopped
frontend:
build:
context: .
dockerfile: Dockerfile
target: base
container_name: opencode-frontend-dev
command: sh -c "cd /app/frontend && npm run dev -- --host 0.0.0.0"
ports:
- "5173:5173"
environment:
- VITE_API_URL=http://localhost:5001
volumes:
- ./frontend:/app/frontend
- ./shared:/app/shared
depends_on:
- backend
restart: unless-stopped
volumes:
opencode-workspace-dev:
driver: local
opencode-data-dev:
driver: local
+41
View File
@@ -0,0 +1,41 @@
services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: opencode-web
ports:
- "5001:5001"
- "5551:5551"
environment:
- NODE_ENV=production
- HOST=0.0.0.0
- PORT=5001
- OPENCODE_SERVER_PORT=5551
- DATABASE_PATH=/app/backend/data/opencode.db
- WORKSPACE_PATH=/workspace
- PROCESS_START_WAIT_MS=2000
- PROCESS_VERIFY_WAIT_MS=1000
- HEALTH_CHECK_INTERVAL_MS=5000
- HEALTH_CHECK_TIMEOUT_MS=30000
- MAX_FILE_SIZE_MB=50
- MAX_UPLOAD_SIZE_MB=50
- SANDBOX_TTL_HOURS=24
- CLEANUP_INTERVAL_MINUTES=60
- DEBUG=false
volumes:
- opencode-workspace:/workspace
- opencode-data:/app/backend/data
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:5001/api/health"]
interval: 30s
timeout: 3s
retries: 3
start_period: 40s
volumes:
opencode-workspace:
driver: local
opencode-data:
driver: local
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+19
View File
@@ -0,0 +1,19 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="manifest" href="/manifest.json" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#0a0a0a" />
<meta name="description" content="AI-powered coding assistant interface" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="OpenCode" />
<title>OpenCode WebUI</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+7558
View File
File diff suppressed because it is too large. Load diff
+62
View File
@@ -0,0 +1,62 @@
{
"name": "frontend",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@hookform/resolvers": "^5.2.2",
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@tailwindcss/vite": "^4.1.14",
"@tanstack/react-query": "^5.90.5",
"axios": "^1.12.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"diff": "^8.0.2",
"highlight.js": "^11.11.1",
"lucide-react": "^0.546.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-hook-form": "^7.65.0",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.9.4",
"rehype-highlight": "^7.0.2",
"rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.3.1",
"zod": "^4.1.12",
"zustand": "^5.0.8"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@types/node": "^24.8.1",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@vitejs/plugin-react": "^5.0.4",
"autoprefixer": "^10.4.21",
"eslint": "^9.36.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.22",
"globals": "^16.4.0",
"openapi-typescript": "^7.10.1",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.14",
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "^7.1.7"
}
}
+4
View File
@@ -0,0 +1,4 @@
<svg width="400" height="400" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="400" height="400" fill="#0E0E0E"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M312 340H88V60H312V340ZM256 116H144V284H256V116Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 269 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

+35
View File
@@ -0,0 +1,35 @@
{
"name": "OpenCode WebUI",
"short_name": "OpenCode",
"description": "AI-powered coding assistant interface",
"start_url": "/",
"display": "standalone",
"background_color": "#0a0a0a",
"theme_color": "#0a0a0a",
"orientation": "any",
"scope": "/",
"icons": [
{
"src": "/icon-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "/icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"categories": ["developer", "productivity", "utilities"],
"lang": "en"
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+42
View File
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+45
View File
@@ -0,0 +1,45 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { Repos } from './pages/Repos'
import { RepoDetail } from './pages/RepoDetail'
import { SessionDetail } from './pages/SessionDetail'
import { SettingsDialog } from './components/settings/SettingsDialog'
import { useSettingsDialog } from './hooks/useSettingsDialog'
import { useTheme } from './hooks/useTheme'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 10,
refetchOnWindowFocus: true,
},
},
})
function AppContent() {
const { isOpen, close } = useSettingsDialog()
useTheme()
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Repos />} />
<Route path="/repos/:id" element={<RepoDetail />} />
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
<Route path="/session/:sessionId" element={<SessionDetail />} />
</Routes>
<SettingsDialog open={isOpen} onOpenChange={close} />
</BrowserRouter>
)
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<AppContent />
</QueryClientProvider>
)
}
export default App
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+123
View File
@@ -0,0 +1,123 @@
import axios, { type AxiosInstance } from 'axios'
import type { paths } from './opencode-types'
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
type SessionResponse = paths['/session/{id}']['get']['responses']['200']['content']['application/json']
type CreateSessionRequest = NonNullable<paths['/session']['post']['requestBody']>['content']['application/json']
type MessageListResponse = paths['/session/{id}/message']['get']['responses']['200']['content']['application/json']
type SendPromptRequest = NonNullable<paths['/session/{id}/message']['post']['requestBody']>['content']['application/json']
type ConfigResponse = paths['/config']['get']['responses']['200']['content']['application/json']
type CommandListResponse = paths['/command']['get']['responses']['200']['content']['application/json']
type CommandRequest = NonNullable<paths['/session/{id}/command']['post']['requestBody']>['content']['application/json']
type ShellRequest = NonNullable<paths['/session/{id}/shell']['post']['requestBody']>['content']['application/json']
export class OpenCodeClient {
private client: AxiosInstance
private baseURL: string
private directory?: string
constructor(baseURL: string, directory?: string) {
this.baseURL = baseURL
this.directory = directory
this.client = axios.create({
baseURL,
timeout: 30000
})
this.client.interceptors.request.use((config) => {
if (this.directory) {
config.params = { ...config.params, directory: this.directory }
}
return config
})
}
setDirectory(directory: string) {
this.directory = directory
}
async listSessions() {
const response = await this.client.get<SessionListResponse>('/session')
return response.data
}
async getSession(sessionID: string) {
const response = await this.client.get<SessionResponse>(`/session/${sessionID}`)
return response.data
}
async createSession(data: CreateSessionRequest) {
const response = await this.client.post<SessionResponse>('/session', data)
return response.data
}
async deleteSession(sessionID: string) {
await this.client.delete(`/session/${sessionID}`)
}
async forkSession(sessionID: string, messageID?: string) {
const response = await this.client.post<SessionResponse>(`/session/${sessionID}/fork`, {
messageID
})
return response.data
}
async abortSession(sessionID: string) {
await this.client.post(`/session/${sessionID}/abort`)
}
async listMessages(sessionID: string) {
const response = await this.client.get<MessageListResponse>(`/session/${sessionID}/message`)
return response.data
}
async sendPrompt(sessionID: string, data: SendPromptRequest) {
const response = await this.client.post(`/session/${sessionID}/message`, data)
return response.data
}
async getConfig() {
const response = await this.client.get<ConfigResponse>('/config')
return response.data
}
async updateConfig(config: Partial<ConfigResponse>) {
const response = await this.client.patch<ConfigResponse>('/config', config)
return response.data
}
async getProviders() {
const response = await this.client.get('/config/providers')
return response.data
}
async listCommands() {
const response = await this.client.get<CommandListResponse>('/command')
return response.data
}
async sendCommand(sessionID: string, data: CommandRequest) {
const response = await this.client.post(`/session/${sessionID}/command`, data)
return response.data
}
async sendShell(sessionID: string, data: ShellRequest) {
const response = await this.client.post(`/session/${sessionID}/shell`, data)
return response.data
}
getEventSourceURL() {
const base = this.baseURL.startsWith('http')
? this.baseURL
: `${window.location.origin}${this.baseURL}`
const url = new URL(`${base}/event`)
if (this.directory) {
url.searchParams.set('directory', this.directory)
}
return url.toString()
}
}
export const createOpenCodeClient = (baseURL: string, directory?: string) => {
return new OpenCodeClient(baseURL, directory)
}
+259
View File
@@ -0,0 +1,259 @@
import { settingsApi } from "./settings";
import axios from "axios";
const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:5001";
export interface Model {
id: string;
name: string;
release_date?: string;
attachment?: boolean;
reasoning?: boolean;
temperature?: boolean;
tool_call?: boolean;
cost?: {
input: number;
output: number;
cache_read?: number;
cache_write?: number;
};
limit?: {
context: number;
output: number;
};
modalities?: {
input: ("text" | "audio" | "image" | "video" | "pdf")[];
output: ("text" | "audio" | "image" | "video" | "pdf")[];
};
experimental?: boolean;
status?: "alpha" | "beta";
options?: Record<string, unknown>;
provider?: {
npm: string;
};
}
export interface Provider {
id: string;
name: string;
api?: string;
env: string[];
npm?: string;
models: Record<string, Model>;
}
export interface ProviderWithModels {
id: string;
name: string;
api?: string;
env: string[];
npm?: string;
models: Model[];
}
// Default providers for common OpenCode setups
const DEFAULT_PROVIDERS: Provider[] = [
{
id: "anthropic",
name: "Anthropic",
api: "https://api.anthropic.com",
env: ["ANTHROPIC_API_KEY"],
npm: "@anthropic-ai/sdk",
models: {
"claude-3-5-sonnet-20241022": {
id: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet (October 2024)",
release_date: "2024-10-22",
attachment: true,
reasoning: false,
temperature: true,
tool_call: true,
cost: { input: 3, output: 15 },
limit: { context: 200000, output: 8192 },
modalities: { input: ["text", "image"], output: ["text"] },
experimental: false,
},
"claude-3-5-haiku-20241022": {
id: "claude-3-5-haiku-20241022",
name: "Claude 3.5 Haiku (October 2024)",
release_date: "2024-10-22",
attachment: true,
reasoning: false,
temperature: true,
tool_call: true,
cost: { input: 1, output: 5 },
limit: { context: 200000, output: 8192 },
modalities: { input: ["text", "image"], output: ["text"] },
experimental: false,
},
},
},
{
id: "openai",
name: "OpenAI",
api: "https://api.openai.com/v1",
env: ["OPENAI_API_KEY"],
npm: "openai",
models: {
"gpt-4o": {
id: "gpt-4o",
name: "GPT-4o",
release_date: "2024-05-13",
attachment: true,
reasoning: false,
temperature: true,
tool_call: true,
cost: { input: 5, output: 15 },
limit: { context: 128000, output: 4096 },
modalities: {
input: ["text", "image", "audio"],
output: ["text", "audio"],
},
experimental: false,
},
"gpt-4o-mini": {
id: "gpt-4o-mini",
name: "GPT-4o Mini",
release_date: "2024-07-18",
attachment: true,
reasoning: false,
temperature: true,
tool_call: true,
cost: { input: 0.15, output: 0.6 },
limit: { context: 128000, output: 16384 },
modalities: { input: ["text", "image"], output: ["text"] },
experimental: false,
},
},
},
{
id: "google",
name: "Google",
api: "https://generativelanguage.googleapis.com/v1beta",
env: ["GOOGLE_API_KEY"],
npm: "@google/generative-ai",
models: {
"gemini-1.5-pro": {
id: "gemini-1.5-pro",
name: "Gemini 1.5 Pro",
release_date: "2024-02-15",
attachment: true,
reasoning: false,
temperature: true,
tool_call: true,
cost: { input: 3.5, output: 10.5 },
limit: { context: 2000000, output: 8192 },
modalities: {
input: ["text", "image", "audio", "video"],
output: ["text"],
},
experimental: false,
},
"gemini-1.5-flash": {
id: "gemini-1.5-flash",
name: "Gemini 1.5 Flash",
release_date: "2024-02-15",
attachment: true,
reasoning: false,
temperature: true,
tool_call: true,
cost: { input: 0.075, output: 0.3 },
limit: { context: 1000000, output: 8192 },
modalities: {
input: ["text", "image", "audio", "video"],
output: ["text"],
},
experimental: false,
},
},
},
];
async function getProvidersFromConfig(): Promise<Provider[]> {
try {
const configResponse = await settingsApi.getDefaultOpenCodeConfig();
if (configResponse?.content?.provider) {
const providerRecord = configResponse.content.provider as Record<string, Provider>;
const providers = Object.entries(providerRecord).map(([id, provider]) => ({
...provider,
id: provider.id || id,
}));
return providers;
}
} catch (error) {
console.warn("Failed to load OpenCode config", error);
}
return DEFAULT_PROVIDERS;
}
export async function getProviders(): Promise<Provider[]> {
return await getProvidersFromConfig();
}
export async function getProvidersWithModels(): Promise<ProviderWithModels[]> {
const providers = await getProviders();
const result = providers.map((provider) => {
const models = Object.entries(provider.models || {}).map(([id, model]) => ({
...model,
id: model.id || id,
name: model.name || id,
}));
return {
id: provider.id,
name: provider.name,
api: provider.api,
env: provider.env || [],
npm: provider.npm,
models,
};
});
return result;
}
export async function getModel(
providerId: string,
modelId: string,
): Promise<Model | null> {
const providers = await getProvidersWithModels();
const provider = providers.find((p) => p.id === providerId);
if (!provider) return null;
return provider.models.find((m) => m.id === modelId) || null;
}
export function formatModelName(model: Model): string {
return model.name || model.id;
}
export function formatProviderName(
provider: Provider | ProviderWithModels,
): string {
return provider.name || provider.id;
}
export const providerCredentialsApi = {
list: async (): Promise<string[]> => {
const { data } = await axios.get(`${API_BASE_URL}/api/providers/credentials`);
return data.providers;
},
getStatus: async (providerId: string): Promise<boolean> => {
const { data } = await axios.get(
`${API_BASE_URL}/api/providers/${providerId}/credentials/status`
);
return data.hasCredentials;
},
set: async (providerId: string, apiKey: string): Promise<void> => {
await axios.post(`${API_BASE_URL}/api/providers/${providerId}/credentials`, {
apiKey,
});
},
delete: async (providerId: string): Promise<void> => {
await axios.delete(`${API_BASE_URL}/api/providers/${providerId}/credentials`);
},
};
+141
View File
@@ -0,0 +1,141 @@
import type { Repo } from './types'
const API_BASE = import.meta.env.VITE_API_URL ?? 'http://localhost:5001'
export async function createRepo(
repoUrl: string,
branch?: string,
openCodeConfigName?: string,
useWorktree?: boolean
): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repoUrl, branch, openCodeConfigName, useWorktree }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Failed to create repo')
}
return response.json()
}
export async function listRepos(): Promise<Repo[]> {
const response = await fetch(`${API_BASE}/api/repos`)
if (!response.ok) {
throw new Error('Failed to list repos')
}
return response.json()
}
export async function getRepo(id: number): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos/${id}`)
if (!response.ok) {
throw new Error('Failed to get repo')
}
return response.json()
}
export async function deleteRepo(id: number): Promise<void> {
const response = await fetch(`${API_BASE}/api/repos/${id}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error('Failed to delete repo')
}
}
export async function startServer(id: number, openCodeConfigName?: string): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos/${id}/server/start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ openCodeConfigName }),
})
if (!response.ok) {
throw new Error('Failed to start server')
}
return response.json()
}
export async function stopServer(id: number): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos/${id}/server/stop`, {
method: 'POST',
})
if (!response.ok) {
throw new Error('Failed to stop server')
}
return response.json()
}
export async function pullRepo(id: number): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos/${id}/pull`, {
method: 'POST',
})
if (!response.ok) {
throw new Error('Failed to pull repo')
}
return response.json()
}
export async function getServerLogs(id: number): Promise<string> {
const response = await fetch(`${API_BASE}/api/repos/${id}/server/logs`)
if (!response.ok) {
throw new Error('Failed to get server logs')
}
return response.text()
}
export async function switchRepoConfig(id: number, configName: string): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos/${id}/config/switch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ configName }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Failed to switch config')
}
return response.json()
}
export async function switchBranch(id: number, branch: string): Promise<Repo> {
const response = await fetch(`${API_BASE}/api/repos/${id}/branch/switch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ branch }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Failed to switch branch')
}
return response.json()
}
export async function listBranches(id: number): Promise<{ local: string[], remote: string[], current: string | null }> {
const response = await fetch(`${API_BASE}/api/repos/${id}/branches`)
if (!response.ok) {
throw new Error('Failed to list branches')
}
return response.json()
}
+101
View File
@@ -0,0 +1,101 @@
import axios from 'axios'
import type {
SettingsResponse,
UpdateSettingsRequest,
OpenCodeConfig,
OpenCodeConfigResponse,
CreateOpenCodeConfigRequest,
UpdateOpenCodeConfigRequest
} from './types/settings'
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5001'
export const settingsApi = {
getSettings: async (userId = 'default'): Promise<SettingsResponse> => {
const { data } = await axios.get(`${API_BASE_URL}/api/settings`, {
params: { userId },
})
return data
},
updateSettings: async (
updates: UpdateSettingsRequest,
userId = 'default'
): Promise<SettingsResponse> => {
const { data } = await axios.patch(`${API_BASE_URL}/api/settings`, updates, {
params: { userId },
})
return data
},
resetSettings: async (userId = 'default'): Promise<SettingsResponse> => {
const { data } = await axios.delete(`${API_BASE_URL}/api/settings`, {
params: { userId },
})
return data
},
getOpenCodeConfigs: async (userId = 'default'): Promise<OpenCodeConfigResponse> => {
const { data } = await axios.get(`${API_BASE_URL}/api/settings/opencode-configs`, {
params: { userId },
})
return data
},
createOpenCodeConfig: async (
request: CreateOpenCodeConfigRequest,
userId = 'default'
): Promise<OpenCodeConfig> => {
const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-configs`, request, {
params: { userId },
})
return data
},
updateOpenCodeConfig: async (
configName: string,
request: UpdateOpenCodeConfigRequest,
userId = 'default'
): Promise<OpenCodeConfig> => {
const { data } = await axios.put(
`${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`,
request,
{ params: { userId } }
)
return data
},
deleteOpenCodeConfig: async (
configName: string,
userId = 'default'
): Promise<boolean> => {
await axios.delete(
`${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`,
{ params: { userId } }
)
return true
},
setDefaultOpenCodeConfig: async (
configName: string,
userId = 'default'
): Promise<OpenCodeConfig> => {
const { data } = await axios.post(
`${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}/set-default`,
{},
{ params: { userId } }
)
return data
},
getDefaultOpenCodeConfig: async (userId = 'default'): Promise<OpenCodeConfig | null> => {
try {
const { data } = await axios.get(`${API_BASE_URL}/api/settings/opencode-configs/default`, {
params: { userId },
})
return data
} catch {
return null
}
},
}
+109
View File
@@ -0,0 +1,109 @@
export interface Repo {
id: number
repoUrl: string
localPath: string
fullPath: string
branch?: string
currentBranch?: string
defaultBranch: string
cloneStatus: 'cloning' | 'ready' | 'error'
clonedAt: number
lastPulled?: number
openCodeConfigName?: string
isWorktree?: boolean
}
import type { components } from './opencode-types'
export type Message = components['schemas']['Message']
export type Part = components['schemas']['Part']
export type Session = components['schemas']['Session']
export type MessageWithParts = {
info: Message
parts: Part[]
}
export type MessageListResponse = MessageWithParts[]
export interface SSEMessagePartUpdatedEvent {
type: 'message.part.updated' | 'messagev2.part.updated'
properties: {
part: Part
}
}
export interface SSEMessageUpdatedEvent {
type: 'message.updated' | 'messagev2.updated'
properties: {
info: Message
}
}
export interface SSEMessageRemovedEvent {
type: 'message.removed' | 'messagev2.removed'
properties: {
sessionID: string
messageID: string
}
}
export interface SSEMessagePartRemovedEvent {
type: 'message.part.removed' | 'messagev2.part.removed'
properties: {
sessionID: string
messageID: string
partID: string
}
}
export interface SSESessionUpdatedEvent {
type: 'session.updated'
properties: {
info: Session
}
}
export interface SSESessionDeletedEvent {
type: 'session.deleted'
properties: {
sessionID: string
}
}
export interface SSESessionCompactedEvent {
type: 'session.compacted'
properties: {
sessionID: string
}
}
export interface SSETodoUpdatedEvent {
type: 'todo.updated'
properties: {
sessionID: string
todos: components['schemas']['Todo'][]
}
}
export type SSEEvent =
| SSEMessagePartUpdatedEvent
| SSEMessageUpdatedEvent
| SSEMessageRemovedEvent
| SSEMessagePartRemovedEvent
| SSESessionUpdatedEvent
| SSESessionDeletedEvent
| SSESessionCompactedEvent
| SSETodoUpdatedEvent
| { type: 'permission.updated'; properties: Record<string, unknown> }
| { type: 'permission.replied'; properties: Record<string, unknown> }
export type ContentPart =
| { type: 'text', content: string }
| { type: 'file', path: string, name: string }
export interface FileInfo {
path: string
name: string
mime?: string
}
+90
View File
@@ -0,0 +1,90 @@
export interface CustomCommand {
name: string
description: string
promptTemplate: string
}
export interface CustomAgent {
name: string
description: string
config: Record<string, unknown>
}
export interface UserPreferences {
theme: 'dark' | 'light' | 'system'
mode: 'plan' | 'build'
defaultModel?: string
defaultAgent?: string
autoScroll: boolean
showReasoning: boolean
expandToolCalls: boolean
keyboardShortcuts: Record<string, string>
customCommands: CustomCommand[]
customAgents: CustomAgent[]
gitToken?: string
}
export interface SettingsResponse {
preferences: UserPreferences
updatedAt: number
}
export interface UpdateSettingsRequest {
preferences: Partial<UserPreferences>
}
export interface OpenCodeConfig {
id: number
name: string
content: Record<string, unknown>
isDefault: boolean
createdAt: number
updatedAt: number
}
export interface CreateOpenCodeConfigRequest {
name: string
content: Record<string, unknown>
isDefault?: boolean
}
export interface UpdateOpenCodeConfigRequest {
content: Record<string, unknown>
isDefault?: boolean
}
export interface OpenCodeConfigResponse {
configs: OpenCodeConfig[]
defaultConfig: OpenCodeConfig | null
}
const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().indexOf('MAC') >= 0
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
submit: `${CMD_KEY}+Enter`,
abort: 'Escape',
toggleMode: 'Tab',
undo: `${CMD_KEY}+Z`,
redo: `${CMD_KEY}+Shift+Z`,
compact: `${CMD_KEY}+K`,
fork: `${CMD_KEY}+Shift+F`,
settings: `${CMD_KEY}+,`,
sessions: `${CMD_KEY}+S`,
newSession: `${CMD_KEY}+N`,
closeSession: `${CMD_KEY}+W`,
toggleSidebar: `${CMD_KEY}+B`,
selectModel: `${CMD_KEY}+M`,
}
export const DEFAULT_USER_PREFERENCES: UserPreferences = {
theme: 'dark',
mode: 'build',
autoScroll: true,
showReasoning: false,
expandToolCalls: false,
keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
customCommands: [],
customAgents: [],
gitToken: undefined,
}
@@ -0,0 +1,98 @@
import { useEffect, useRef } from 'react'
import { Command } from 'lucide-react'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
interface CommandSuggestionsProps {
isOpen: boolean
query: string
commands: CommandType[]
onSelect: (command: CommandType) => void
onClose: () => void
position: { bottom: number; left: number; width: number }
selectedIndex?: number
}
export function CommandSuggestions({
isOpen,
query,
commands,
onSelect,
position,
selectedIndex = 0
}: CommandSuggestionsProps) {
const containerRef = useRef<HTMLDivElement>(null)
const filteredCommands = commands.filter(command =>
command.name.toLowerCase().includes(query.toLowerCase()) ||
command.description?.toLowerCase().includes(query.toLowerCase())
)
// Scroll selected item into view
useEffect(() => {
if (!isOpen || !containerRef.current) return
const selectedItem = containerRef.current.querySelector(`[data-selected="true"]`) as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}
}, [selectedIndex, isOpen])
if (!isOpen || filteredCommands.length === 0) {
return null
}
return (
<div
ref={containerRef}
className="fixed z-50 bg-[#1a1a1a] border border-[#333] rounded-lg shadow-lg max-h-64 overflow-y-auto"
style={{
bottom: `${position.bottom}px`, // Position from bottom
left: `${position.left}px`,
width: `${position.width}px`
}}
>
<div className="p-1">
{filteredCommands.map((command, index) => {
const isSelected = index === selectedIndex
const displayName = `/${command.name}`
return (
<div
key={command.name}
data-selected={isSelected}
className={`px-3 py-2 cursor-pointer rounded-md transition-colors flex items-center gap-2 ${
isSelected
? 'bg-blue-600/20 text-white'
: 'hover:bg-[#2a2a2a] text-zinc-300'
}`}
onClick={() => onSelect(command)}
>
<Command className="h-4 w-4 text-zinc-400 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="font-medium text-sm truncate">{displayName}</div>
{command.description && (
<div className="text-xs text-zinc-500 truncate">{command.description}</div>
)}
</div>
</div>
)
})}
</div>
<div className="px-3 py-2 border-t border-[#333] text-xs text-zinc-500">
<div className="flex items-center gap-4">
<span>↑↓ Navigate</span>
<span>↵ Select</span>
<span>Esc Close</span>
</div>
</div>
</div>
)
}
@@ -0,0 +1,515 @@
import { useState, useEffect, useRef, useCallback } from 'react'
import { FileTree } from './FileTree'
import { FileOperations } from './FileOperations'
import { FilePreview } from './FilePreview'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
import type { FileInfo } from '@/types/files'
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:5001'
// Hook to detect mobile screens
const useIsMobile = () => {
const [isMobile, setIsMobile] = useState(false)
useEffect(() => {
const checkIsMobile = () => {
setIsMobile(window.innerWidth < 768)
}
checkIsMobile()
window.addEventListener('resize', checkIsMobile)
return () => window.removeEventListener('resize', checkIsMobile)
}, [])
return isMobile
}
interface FileBrowserProps {
basePath?: string
onFileSelect?: (file: FileInfo) => void
embedded?: boolean
initialSelectedFile?: string
}
export function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile }: FileBrowserProps) {
const [currentPath, setCurrentPath] = useState(basePath)
const [files, setFiles] = useState<FileInfo | null>(null)
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null)
const [searchQuery, setSearchQuery] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [isDragging, setIsDragging] = useState(false)
const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false)
const dropZoneRef = useRef<HTMLDivElement>(null)
const isMobile = useIsMobile()
useEffect(() => {
if (initialSelectedFile) {
const loadInitialFile = async () => {
try {
const url = `${API_BASE}/api/files/${initialSelectedFile}`
const response = await fetch(url)
if (response.ok) {
const fileData = await response.json()
setSelectedFile(fileData)
if (isMobile) {
setIsPreviewModalOpen(true)
}
} else {
const errorText = await response.text()
console.error('[FileBrowser] Failed to load file:', errorText)
setError(`Failed to load file: ${errorText}`)
}
} catch (err) {
console.error('[FileBrowser] Failed to load initial file:', err)
setError(err instanceof Error ? err.message : 'Failed to load file')
}
}
loadInitialFile()
}
}, [initialSelectedFile, isMobile, basePath])
const loadFiles = async (path: string) => {
setLoading(true)
setError(null)
try {
const response = await fetch(`${API_BASE}/api/files/${path}`)
if (!response.ok) {
throw new Error(`Failed to load files: ${response.statusText}`)
}
const data = await response.json()
setFiles(data)
setCurrentPath(path)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load files')
} finally {
setLoading(false)
}
}
const handleFileSelect = useCallback(async (file: FileInfo) => {
if (file.isDirectory) {
setSelectedFile(null)
return
}
// Fetch the full file content when selecting a file
setLoading(true)
try {
const response = await fetch(`${API_BASE}/api/files/${file.path}`)
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
const fullFileData = await response.json()
setSelectedFile(fullFileData)
onFileSelect?.(fullFileData)
// On mobile, open preview in modal
if (isMobile) {
setIsPreviewModalOpen(true)
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load file')
setSelectedFile(null)
} finally {
setLoading(false)
}
}, [onFileSelect, isMobile])
const handleCloseModal = () => {
setIsPreviewModalOpen(false)
setSelectedFile(null)
}
const handleTouchStart = (e: React.TouchEvent) => {
e.preventDefault()
}
const handleTouchEnd = (e: React.TouchEvent) => {
e.preventDefault()
}
const handleDirectoryClick = (path: string) => {
loadFiles(path)
}
const handleRefresh = () => {
loadFiles(currentPath)
}
const handleUpload = async (files: FileList) => {
const formData = new FormData()
formData.append('file', files[0])
try {
const response = await fetch(`${API_BASE}/api/files/${currentPath}`, {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error(`Upload failed: ${response.statusText}`)
}
await loadFiles(currentPath)
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
}
}
const handleCreateFile = async (name: string, type: 'file' | 'folder') => {
try {
const response = await fetch(`${API_BASE}/api/files/${currentPath}/${name}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, content: type === 'file' ? '' : undefined }),
})
if (!response.ok) {
throw new Error(`Create failed: ${response.statusText}`)
}
await loadFiles(currentPath)
} catch (err) {
setError(err instanceof Error ? err.message : 'Create failed')
}
}
const handleDelete = async (path: string) => {
try {
const response = await fetch(`${API_BASE}/api/files/${path}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error(`Delete failed: ${response.statusText}`)
}
await loadFiles(currentPath)
setSelectedFile(null)
} catch (err) {
setError(err instanceof Error ? err.message : 'Delete failed')
}
}
const handleRename = async (oldPath: string, newPath: string) => {
try {
const response = await fetch(`${API_BASE}/api/files/${oldPath}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ newPath }),
})
if (!response.ok) {
throw new Error(`Rename failed: ${response.statusText}`)
}
await loadFiles(currentPath)
} catch (err) {
setError(err instanceof Error ? err.message : 'Rename failed')
}
}
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(true)
}
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
if (e.currentTarget === dropZoneRef.current) {
setIsDragging(false)
}
}
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
}
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(false)
const droppedFiles = e.dataTransfer.files
if (droppedFiles.length > 0) {
await handleUpload(droppedFiles)
}
}
useEffect(() => {
loadFiles(basePath)
}, [basePath])
useEffect(() => {
const handleFileSaved = (event: CustomEvent<{ path: string; content: string }>) => {
if (selectedFile && selectedFile.path === event.detail.path) {
handleFileSelect(selectedFile)
}
}
window.addEventListener('fileSaved', handleFileSaved as EventListener)
return () => window.removeEventListener('fileSaved', handleFileSaved as EventListener)
}, [selectedFile, handleFileSelect])
// Handle escape key to close modal
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isPreviewModalOpen) {
handleCloseModal()
}
}
if (isPreviewModalOpen) {
document.addEventListener('keydown', handleEscape)
return () => document.removeEventListener('keydown', handleEscape)
}
}, [isPreviewModalOpen])
const filteredFiles = files?.children?.filter(file =>
file.name.toLowerCase().includes(searchQuery.toLowerCase())
)
if (embedded) {
return (
<div
className="h-full flex flex-col bg-background"
ref={dropZoneRef}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
{isDragging && (
<div className="absolute inset-0 z-50 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center">
<div className="text-center">
<Upload className="w-12 h-12 mx-auto mb-2 text-primary" />
<p className="text-lg font-semibold text-primary">Drop files here to upload</p>
</div>
</div>
)}
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className="flex-1 flex overflow-hidden">
<div className={`${isMobile ? 'w-full' : 'w-1/2'} border-r border-border px-4 flex flex-col`}>
<div className="flex items-center gap-2 mb-4 mt-4 flex-shrink-0">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={handleRefresh}>
<RefreshCw className="w-4 h-4" />
</Button>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{error && (
<div className="text-sm text-destructive bg-destructive/10 p-2 rounded mb-4 flex-shrink-0">
{error}
</div>
)}
<div className="flex-1 overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center h-64">
<RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<FileTree
files={filteredFiles || []}
onFileSelect={handleFileSelect}
onDirectoryClick={handleDirectoryClick}
selectedFile={selectedFile}
onDelete={handleDelete}
onRename={handleRename}
currentPath={currentPath}
basePath={basePath}
/>
)}
</div>
</div>
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 pl-4 overflow-y-auto">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Select a file to preview
</div>
)}
</div>
)}
</div>
{/* Mobile: File Preview Modal */}
{isMobile && selectedFile && !selectedFile.isDirectory && (
<Dialog open={isPreviewModalOpen} onOpenChange={(open) => !open && handleCloseModal()}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col [&>button:last-child]:hidden"
>
<div className="flex-1 overflow-hidden min-h-0">
<FilePreview file={selectedFile} hideHeader={false} isMobileModal={true} onCloseModal={handleCloseModal} />
</div>
</DialogContent>
</Dialog>
)}
</div>
)
}
return (
<div
className="h-full flex flex-col"
ref={dropZoneRef}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
<Card className="flex-1 relative">
{isDragging && (
<div className="absolute inset-0 z-50 bg-blue-50/90 border-2 border-dashed border-blue-500 rounded-lg flex items-center justify-center">
<div className="text-center">
<Upload className="w-12 h-12 mx-auto mb-2 text-blue-500" />
<p className="text-lg font-semibold text-blue-600">Drop files here to upload</p>
</div>
</div>
)}
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2">
<FolderOpen className="w-5 h-5" />
File Browser
</CardTitle>
<Button variant="outline" size="sm" onClick={handleRefresh}>
<RefreshCw className="w-4 h-4" />
</Button>
</div>
<div className="flex items-center gap-2">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{error && (
<div className="text-sm text-destructive bg-destructive/10 p-2 rounded">
{error}
</div>
)}
</CardHeader>
<CardContent className="flex-1 flex overflow-hidden">
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className={`${isMobile ? 'w-full' : 'w-1/3'} border-r pr-4 flex flex-col`}>
<div className="flex items-center gap-2 mb-4 flex-shrink-0">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{loading ? (
<div className="flex items-center justify-center h-64">
<RefreshCw className="w-6 h-6 animate-spin" />
</div>
) : (
<div className="flex-1 overflow-y-auto">
<FileTree
files={filteredFiles || []}
onFileSelect={handleFileSelect}
onDirectoryClick={handleDirectoryClick}
selectedFile={selectedFile}
onDelete={handleDelete}
onRename={handleRename}
currentPath={currentPath}
basePath={basePath}
/>
</div>
)}
</div>
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 pl-4 overflow-y-auto">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Select a file to preview
</div>
)}
</div>
)}
</CardContent>
</Card>
{/* Mobile: File Preview Modal */}
{isMobile && selectedFile && !selectedFile.isDirectory && (
<Dialog open={isPreviewModalOpen} onOpenChange={(open) => !open && handleCloseModal()}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col"
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
>
<DialogHeader className="p-4 border-b border-border flex-shrink-0 relative bg-background z-10">
<div className="flex justify-center mb-2">
<div className="w-8 h-1 bg-muted rounded-full"></div>
</div>
<DialogTitle className="text-foreground text-lg pr-12">
{selectedFile.name}
</DialogTitle>
<button
onClick={handleCloseModal}
className="absolute right-4 top-4 p-2 rounded-md hover:bg-muted text-foreground transition-colors touch-manipulation bg-muted border border-border"
aria-label="Close modal"
>
<X className="w-6 h-6" />
</button>
</DialogHeader>
<div className="flex-1 overflow-hidden min-h-0">
<FilePreview file={selectedFile} hideHeader={true} />
</div>
</DialogContent>
</Dialog>
)}
</div>
)
}
@@ -0,0 +1,74 @@
import { useEffect } from 'react'
import { FileBrowser } from './FileBrowser'
import { Button } from '@/components/ui/button'
import { X } from 'lucide-react'
interface FileBrowserSheetProps {
isOpen: boolean
onClose: () => void
basePath?: string
repoName?: string
initialSelectedFile?: string
}
export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, initialSelectedFile }: FileBrowserSheetProps) {
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onClose()
}
}
if (isOpen) {
document.addEventListener('keydown', handleEscape)
document.body.style.overflow = 'hidden'
}
return () => {
document.removeEventListener('keydown', handleEscape)
document.body.style.overflow = 'unset'
}
}, [isOpen, onClose])
if (!isOpen) return null
return (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm">
<div className="absolute inset-0 bg-background">
{/* Header */}
<div className="sticky top-0 z-10 border-b border-border bg-background backdrop-blur-sm px-4 py-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<h1 className="text-lg font-semibold text-foreground">
{repoName ? `${repoName} - Files` : 'Workspace Files'}
</h1>
{basePath && (
<span className="text-sm text-muted-foreground bg-muted px-2 py-1 rounded">
{basePath}
</span>
)}
</div>
<Button
variant="ghost"
size="icon"
onClick={onClose}
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-all duration-200"
>
<X className="w-5 h-5" />
</Button>
</div>
</div>
{/* File Browser Content */}
<div className="h-[calc(100vh-73px)] overflow-hidden">
<FileBrowser
basePath={basePath}
embedded={true}
initialSelectedFile={initialSelectedFile}
/>
</div>
</div>
</div>
)
}
@@ -0,0 +1,106 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Upload, Plus, FolderPlus, FilePlus } from 'lucide-react'
interface FileOperationsProps {
onUpload: (files: FileList) => void
onCreate: (name: string, type: 'file' | 'folder') => void
}
export function FileOperations({ onUpload, onCreate }: FileOperationsProps) {
const [createDialogOpen, setCreateDialogOpen] = useState(false)
const [createType, setCreateType] = useState<'file' | 'folder'>('file')
const [createName, setCreateName] = useState('')
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files
if (files && files.length > 0) {
onUpload(files)
}
event.target.value = ''
}
const handleCreate = () => {
if (createName.trim()) {
onCreate(createName.trim(), createType)
setCreateName('')
setCreateDialogOpen(false)
}
}
return (
<div className="flex items-center gap-2">
<div className="relative">
<input
type="file"
id="file-upload"
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
onChange={handleFileSelect}
multiple
/>
<Button variant="outline" size="sm" asChild>
<label htmlFor="file-upload" className="cursor-pointer flex items-center gap-2">
<Upload className="w-4 h-4" />
Upload
</label>
</Button>
</div>
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<Plus className="w-4 h-4" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Select value={createType} onValueChange={(value: 'file' | 'folder') => setCreateType(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="file">
<div className="flex items-center gap-2">
<FilePlus className="w-4 h-4" />
File
</div>
</SelectItem>
<SelectItem value="folder">
<div className="flex items-center gap-2">
<FolderPlus className="w-4 h-4" />
Folder
</div>
</SelectItem>
</SelectContent>
</Select>
<Input
placeholder={`${createType === 'file' ? 'File' : 'Folder'} name`}
value={createName}
onChange={(e) => setCreateName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreate()
}}
/>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!createName.trim()}>
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,224 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Download, Copy, X, Edit3, Save, X as XIcon } from 'lucide-react'
import type { FileInfo } from '@/types/files'
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:5001'
interface FilePreviewProps {
file: FileInfo
hideHeader?: boolean
isMobileModal?: boolean
onCloseModal?: () => void
}
export function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal }: FilePreviewProps) {
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
const [editContent, setEditContent] = useState('')
const [isSaving, setIsSaving] = useState(false)
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const formatDate = (date: Date) => {
return new Date(date).toLocaleString()
}
const handleDownload = () => {
const link = document.createElement('a')
link.href = `${API_BASE}/api/files/${file.path}?download=true`
link.download = file.name
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
const decodeBase64 = (base64: string): string => {
try {
const binaryString = atob(base64)
const bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
return new TextDecoder('utf-8').decode(bytes)
} catch {
throw new Error('Failed to decode base64 content')
}
}
const handleCopyContent = async () => {
if (file.content) {
try {
const content = decodeBase64(file.content)
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
}
const handleEdit = () => {
if (file.content) {
try {
const content = decodeBase64(file.content)
setEditContent(content)
setViewMode('edit')
} catch (err) {
console.error('Failed to load content for editing:', err)
}
}
}
const handleSave = async () => {
setIsSaving(true)
try {
const response = await fetch(`${API_BASE}/api/files/${file.path}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'file', content: editContent }),
})
if (!response.ok) {
throw new Error(`Save failed: ${response.statusText}`)
}
setViewMode('preview')
const event = new CustomEvent('fileSaved', { detail: { path: file.path, content: editContent } })
window.dispatchEvent(event)
} catch (err) {
console.error('Failed to save file:', err)
} finally {
setIsSaving(false)
}
}
const handleCancel = () => {
setEditContent('')
setViewMode('preview')
}
const isTextFile = file.mimeType?.startsWith('text/') ||
['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '')
const renderContent = () => {
if (!file.content) return null
if (file.mimeType?.startsWith('image/')) {
return (
<div className="flex justify-center p-4">
<img
src={`${API_BASE}/api/files/${file.path}?raw=true`}
alt={file.name}
className="max-w-full h-auto object-contain rounded"
/>
</div>
)
}
if (isTextFile) {
if (viewMode === 'edit') {
return (
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
className="text-sm bg-muted text-foreground p-4 rounded whitespace-pre-wrap font-mono break-words w-full resize-none focus:outline-none focus:ring-0 border-none block"
style={{ minHeight: '95vh' }}
placeholder="Edit file content..."
autoFocus
data-file-editor="true"
/>
)
}
try {
const textContent = decodeBase64(file.content)
return (
<pre className="text-sm bg-muted text-foreground p-4 rounded whitespace-pre-wrap font-mono break-words overflow-x-hidden">
<code>{textContent}</code>
</pre>
)
} catch {
return (
<div className="text-center text-muted-foreground py-8">
Cannot preview this file - content may be corrupted
</div>
)
}
}
return (
<div className="text-center text-muted-foreground py-8">
Binary file - download to view content
</div>
)
}
return (
<div className="h-full flex flex-col bg-background">
{!hideHeader && (
<>
<div className={`flex items-start gap-2 px-3 py-2 border-b border-border flex-shrink-0 overflow-hidden ${isMobileModal ? 'pt-3' : ''}`}>
<div className="flex-1 min-w-0 overflow-hidden">
<h3 className="text-foreground text-sm font-medium break-all leading-tight">
{file.name}
</h3>
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-1 flex-wrap">
<span className="bg-muted px-1.5 py-0.5 rounded text-xs truncate max-w-[80px] flex-shrink-0">{file.mimeType || 'Unknown'}</span>
<span className="truncate flex-shrink-0">{formatFileSize(file.size)}</span>
<span className="hidden sm:inline truncate flex-shrink-0">{formatDate(file.lastModified)}</span>
</div>
</div>
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
{isMobileModal && onCloseModal && (
<Button variant="outline" size="sm" onClick={onCloseModal} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<X className="w-3 h-3" />
</Button>
)}
{isTextFile && viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleEdit} className="h-7 w-7 p-0">
<Edit3 className="w-3 h-3" />
</Button>
)}
{viewMode === 'edit' && (
<>
<Button variant="outline" size="sm" onClick={handleSave} disabled={isSaving} className="border-green-600 bg-green-600/10 text-green-600 hover:bg-green-600/20 h-7 w-7 p-0">
<Save className="w-3 h-3" />
</Button>
<Button variant="outline" size="sm" onClick={handleCancel} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<XIcon className="w-3 h-3" />
</Button>
</>
)}
{isTextFile && viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleCopyContent} className="h-7 w-7 p-0">
<Copy className="w-3 h-3" />
</Button>
)}
{viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleDownload} className="h-7 w-7 p-0">
<Download className="w-3 h-3" />
</Button>
)}
</div>
</div>
</>
)}
<div className={`flex-1 ${viewMode === 'edit' ? 'overflow-hidden' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}>
<div className="p-2 min-w-0">
{renderContent()}
</div>
</div>
</div>
)
}
@@ -0,0 +1,265 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import {
File,
Folder,
FolderOpen,
ChevronRight,
ChevronDown,
MoreHorizontal,
Trash2,
Edit3
} from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import type { FileInfo } from '@/types/files'
interface FileTreeProps {
files: FileInfo[]
onFileSelect: (file: FileInfo) => void
onDirectoryClick: (path: string) => void
selectedFile: FileInfo | null
onDelete: (path: string) => void
onRename: (oldPath: string, newPath: string) => void
currentPath?: string
basePath?: string
}
interface TreeNodeProps {
file: FileInfo
level: number
onFileSelect: (file: FileInfo) => void
onDirectoryClick: (path: string) => void
selectedFile?: FileInfo | null
onDelete?: (path: string) => void
onRename?: (oldPath: string, newPath: string) => void
}
function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename }: TreeNodeProps) {
const [expanded, setExpanded] = useState(false)
const [editing, setEditing] = useState(false)
const [editName, setEditName] = useState(file.name)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const handleClick = () => {
if (file.isDirectory) {
onDirectoryClick(file.path)
} else {
onFileSelect(file)
}
}
const handleDelete = () => {
setDeleteDialogOpen(true)
}
const handleDeleteConfirm = () => {
onDelete?.(file.path)
setDeleteDialogOpen(false)
}
const handleDeleteCancel = () => {
setDeleteDialogOpen(false)
}
const handleRename = () => {
setEditing(true)
setEditName(file.name)
}
const handleRenameSubmit = () => {
if (editName && editName !== file.name) {
const newPath = file.path.replace(/\/[^/]+$/, `/${editName}`)
onRename?.(file.path, newPath)
}
setEditing(false)
}
const handleRenameCancel = () => {
setEditing(false)
setEditName(file.name)
}
const getFileIcon = () => {
if (file.isDirectory) {
return expanded ? <FolderOpen className="w-4 h-4" /> : <Folder className="w-4 h-4" />
}
const ext = file.name.split('.').pop()?.toLowerCase()
const iconMap: Record<string, string> = {
'js': '🟨',
'ts': '🔷',
'jsx': '🟨',
'tsx': '🔷',
'json': '📋',
'md': '📝',
'html': '🌐',
'css': '🎨',
'png': '🖼️',
'jpg': '🖼️',
'jpeg': '🖼️',
'gif': '🖼️',
'svg': '🖼️',
'pdf': '📄',
'zip': '📦',
}
return (
<span className="w-4 h-4 flex items-center justify-center text-xs">
{iconMap[ext || ''] || <File className="w-4 h-4" />}
</span>
)
}
return (
<div>
<div
className={`flex items-center gap-1 px-2 py-1 hover:bg-muted rounded cursor-pointer group ${
selectedFile?.path === file.path ? 'bg-muted' : ''
}`}
style={{ paddingLeft: `${level * 16 + 8}px` }}
>
{file.isDirectory && (
<Button
variant="ghost"
size="sm"
className="w-4 h-4 p-0"
onClick={(e) => {
e.stopPropagation()
setExpanded(!expanded)
if (!expanded) {
onDirectoryClick(file.path)
}
}}
>
{expanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
</Button>
)}
<div className="flex items-center gap-1 flex-1" onClick={handleClick}>
{getFileIcon()}
{editing ? (
<Input
value={editName}
onChange={(e) => setEditName(e.target.value)}
onBlur={handleRenameSubmit}
onKeyDown={(e) => {
if (e.key === 'Enter') handleRenameSubmit()
if (e.key === 'Escape') handleRenameCancel()
}}
className="h-6 text-sm"
autoFocus
/>
) : (
<span className="text-sm truncate">{file.name}</span>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="w-6 h-6 p-0 opacity-0 group-hover:opacity-100"
>
<MoreHorizontal className="w-3 h-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={handleRename}>
<Edit3 className="w-4 h-4 mr-2" />
Rename
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDelete} className="text-red-600">
<Trash2 className="w-4 h-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{file.isDirectory && expanded && file.children && (
<div>
{file.children.map((child) => (
<TreeNode
key={child.path}
file={child}
level={level + 1}
onFileSelect={onFileSelect}
onDirectoryClick={onDirectoryClick}
selectedFile={selectedFile}
onDelete={onDelete}
onRename={onRename}
/>
))}
</div>
)}
<DeleteDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onConfirm={handleDeleteConfirm}
onCancel={handleDeleteCancel}
title={`Delete ${file.isDirectory ? 'Folder' : 'File'}`}
description={`Are you sure you want to delete this ${file.isDirectory ? 'folder' : 'file'}?`}
itemName={file.name}
/>
</div>
)
}
export function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '' }: FileTreeProps) {
const handleGoUp = () => {
// If currentPath has content and is different from basePath, go up
if (currentPath !== basePath) {
const pathParts = currentPath.split('/').filter(p => p)
pathParts.pop()
const parentPath = pathParts.join('/')
onDirectoryClick(parentPath)
}
}
// Show ".." if we're not at the base path (empty string means root)
const showGoUp = currentPath && currentPath !== basePath
return (
<div className="overflow-y-auto">
{showGoUp && (
<div
className="flex items-center gap-1 px-2 py-1 hover:bg-muted rounded cursor-pointer"
onClick={handleGoUp}
>
<span className="w-4 h-4 flex items-center justify-center text-sm">↩️</span>
<span className="text-sm text-muted-foreground">..</span>
</div>
)}
{files.length === 0 ? (
<div className="text-center text-muted-foreground py-8">
No files in this directory
</div>
) : (
files.map((file) => (
<TreeNode
key={file.path}
file={file}
level={0}
onFileSelect={onFileSelect}
onDirectoryClick={onDirectoryClick}
selectedFile={selectedFile}
onDelete={onDelete}
onRename={onRename}
/>
))
)}
</div>
)
}
+41
View File
@@ -0,0 +1,41 @@
import { Settings } from "lucide-react";
import { Button } from "@/components/ui/button";
import { BackButton } from "@/components/ui/back-button";
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
import type { ReactNode } from "react";
interface HeaderProps {
title: string;
backTo?: string;
action?: ReactNode;
}
export function Header({ title, backTo, action }: HeaderProps) {
const { open: openSettings } = useSettingsDialog();
return (
<header className="sticky top-0 z-10 bg-gradient-to-b from-background via-background to-background border-b border-border backdrop-blur-sm">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center gap-4">
{backTo && <BackButton to={backTo} />}
<h1 className="text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate">
{title}
</h1>
</div>
<div className="flex items-center gap-2">
{action && <div>{action}</div>}
<Button
variant="ghost"
size="icon"
onClick={openSettings}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200"
>
<Settings className="w-10 h-10" />
</Button>
</div>
</div>
</div>
</header>
);
}
@@ -0,0 +1,83 @@
import { useEffect, useRef } from 'react'
interface FileSuggestionsProps {
isOpen: boolean
query: string
files: string[]
onSelect: (file: string) => void
onClose: () => void
position: { bottom: number, left: number, width: number }
selectedIndex?: number
}
export function FileSuggestions({
isOpen,
files,
onSelect,
onClose,
position,
selectedIndex = 0
}: FileSuggestionsProps) {
const listRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!isOpen) return
const handleClickOutside = (e: MouseEvent) => {
if (listRef.current && !listRef.current.contains(e.target as Node)) {
onClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, onClose])
useEffect(() => {
if (!isOpen || !listRef.current) return
const selectedItem = listRef.current.children[selectedIndex] as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest' })
}
}, [selectedIndex, isOpen])
if (!isOpen || files.length === 0) return null
const getFilename = (path: string) => path.split('/').pop() || path
const getDirectory = (path: string) => {
const parts = path.split('/')
return parts.slice(0, -1).join('/') || '.'
}
return (
<div
ref={listRef}
className="fixed bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl z-50 max-h-64 overflow-y-auto"
style={{
bottom: `${position.bottom}px`,
left: `${position.left}px`,
width: `${position.width}px`
}}
>
{files.map((file, idx) => (
<button
key={file}
onClick={() => onSelect(file)}
className={`w-full px-3 py-2 text-left transition-colors ${
idx === selectedIndex
? 'bg-blue-600 text-white'
: 'hover:bg-zinc-800 text-zinc-100'
}`}
>
<div className="font-mono text-sm font-medium">
{getFilename(file)}
</div>
<div className="text-xs opacity-70 mt-0.5">
{getDirectory(file)}
</div>
</button>
))}
</div>
)
}
@@ -0,0 +1,146 @@
import type { components } from '@/api/opencode-types'
import { Copy } from 'lucide-react'
import { TextPart } from './TextPart'
import { PatchPart } from './PatchPart'
import { ToolCallPart } from './ToolCallPart'
type Part = components['schemas']['Part']
interface MessagePartProps {
part: Part
role?: string
allParts?: Part[]
partIndex?: number
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function getCopyableContent(part: Part, allParts?: Part[]): string {
switch (part.type) {
case 'text':
return part.text || ''
case 'patch':
return `Patch: ${part.hash}\nFiles: ${part.files.join(', ')}`
case 'tool':
if (part.state.status === 'completed' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
} else if (part.state.status === 'running' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
}
return `Tool: ${part.tool} (${part.state.status})`
case 'reasoning':
return part.text || ''
case 'snapshot':
return part.snapshot || ''
case 'agent':
return `Agent: ${part.name}`
case 'step-start':
return 'Starting step...'
case 'step-finish':
if (allParts) {
return allParts
.filter(p => p.type === 'text')
.map(p => p.text || '')
.join('\n\n')
.trim()
}
return ''
case 'file':
return part.filename || part.url || 'File'
default:
return ''
}
}
function CopyButton({ content, title, className = "" }: { content: string; title: string; className?: string }) {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
if (!content.trim()) {
return null
}
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
>
<Copy className="w-4 h-4" />
</button>
)
}
export function MessagePart({ part, role, allParts, partIndex, onFileClick }: MessagePartProps) {
const copyableContent = getCopyableContent(part, allParts)
switch (part.type) {
case 'text':
if (role === 'user' && allParts && partIndex !== undefined) {
const nextPart = allParts[partIndex + 1]
if (nextPart && nextPart.type === 'file') {
return null
}
}
return <TextPart part={part} />
case 'patch':
return <PatchPart part={part} />
case 'tool':
return <ToolCallPart part={part} onFileClick={onFileClick} />
case 'reasoning':
return (
<details className="border border-zinc-800 rounded-lg my-2">
<summary className="px-4 py-2 bg-zinc-900 hover:bg-zinc-800 cursor-pointer text-sm font-medium">
Reasoning
</summary>
<div className="p-4 bg-zinc-950 text-sm text-zinc-300 whitespace-pre-wrap">
{part.text}
</div>
</details>
)
case 'snapshot':
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500 font-mono">Snapshot: {part.snapshot}</div>
</div>
)
case 'agent':
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-sm font-medium text-blue-400">Agent: {part.name}</div>
</div>
)
case 'step-start':
return (
<div className="text-xs text-muted-foreground my-1">
→ Starting step...
</div>
)
case 'step-finish':
return (
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
<span>✓ Step complete • ${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
<CopyButton content={copyableContent} title="Copy step complete" />
</div>
)
case 'file':
return (
<span className="inline-flex items-center gap-1 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-sm text-zinc-300">
<span className="text-blue-400">@</span>
<span className="font-medium">{part.filename || 'File'}</span>
</span>
)
default:
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500">Unknown part type</div>
</div>
)
}
}
@@ -0,0 +1,109 @@
import { useMessages } from '@/hooks/useOpenCode'
import { MessagePart } from './MessagePart'
import type { MessageWithParts } from '@/api/types'
interface MessageThreadProps {
opcodeUrl: string
sessionID: string
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const isMessageThinking = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return msg.parts.length === 0 && isMessageStreaming(msg)
}
export function MessageThread({ opcodeUrl, sessionID, directory, onFileClick }: MessageThreadProps) {
const { data: messages, isLoading, error } = useMessages(opcodeUrl, sessionID, directory)
if (isLoading) {
return (
<div className="flex items-center justify-center h-full text-zinc-500">
Loading messages...
</div>
)
}
if (error) {
return (
<div className="flex items-center justify-center h-full text-red-400">
Error loading messages: {error instanceof Error ? error.message : 'Unknown error'}
</div>
)
}
if (!messages || messages.length === 0) {
return (
<div className="flex items-center justify-center h-full text-zinc-600">
No messages yet. Start a conversation below.
</div>
)
}
return (
<div className="flex flex-col space-y-2 p-4">
{messages.map((msg) => {
const streaming = isMessageStreaming(msg)
const thinking = isMessageThinking(msg)
return (
<div
key={msg.info.id}
className="flex flex-col"
>
<div
className={`w-full rounded-lg p-2 ${
msg.info.role === 'user'
? 'bg-blue-600/20 border border-blue-600/30'
: 'bg-card/50 border border-border'
} ${streaming ? 'animate-pulse-subtle' : ''}`}
>
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-medium text-zinc-400">
{msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')}
</span>
{msg.info.time && (
<span className="text-xs text-muted-foreground">
{new Date(msg.info.time.created).toLocaleTimeString()}
</span>
)}
{streaming && (
<span className="text-xs text-blue-400 flex items-center gap-1">
<span className="animate-pulse">●</span> <span className="shine-loading">Generating...</span>
</span>
)}
</div>
{thinking ? (
<div className="flex items-center gap-2 text-zinc-500">
<span className="animate-pulse">▋</span>
<span className="text-sm shine-loading">Thinking...</span>
</div>
) : (
<div className="space-y-2">
{msg.parts.map((part, index) => (
<div key={`${msg.info.id}-${part.id}-${index}`}>
<MessagePart
part={part}
role={msg.info.role}
allParts={msg.parts}
partIndex={index}
onFileClick={onFileClick}
/>
</div>
))}
</div>
)}
</div>
</div>
)
})}
</div>
)
}
@@ -0,0 +1,38 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
type PatchPart = components['schemas']['PatchPart']
interface PatchPartProps {
part: PatchPart
}
export function PatchPart({ part }: PatchPartProps) {
const [expanded, setExpanded] = useState(true)
return (
<div className="border border-zinc-800 rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-zinc-900 hover:bg-zinc-800 text-left flex items-center justify-between text-sm"
>
<span className="font-medium">
File Changes ({part.files.length} file{part.files.length !== 1 ? 's' : ''})
</span>
<span className="text-zinc-400 text-xs font-mono">{part.hash.slice(0, 8)}</span>
</button>
{expanded && (
<div className="bg-zinc-950 p-4">
<div className="space-y-2">
{part.files.map((file, index) => (
<div key={index} className="text-sm">
<div className="font-mono text-zinc-400 mb-1">{file}</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,605 @@
import { useState, useRef, useEffect, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell } from '@/hooks/useOpenCode'
import { useSettings } from '@/hooks/useSettings'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
import { useMobile } from '@/hooks/useMobile'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { FileSuggestions } from './FileSuggestions'
import { detectMentionTrigger, parsePromptToParts, getFilename } from '@/lib/promptParser'
import { getModel, formatModelName } from '@/api/providers'
import type { components } from '@/api/opencode-types'
import type { MessageWithParts, FileInfo } from '@/api/types'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
type CommandType = components['schemas']['Command']
interface PromptInputProps {
opcodeUrl: string
directory?: string
sessionID: string
disabled?: boolean
onShowSessionsDialog?: () => void
onShowModelsDialog?: () => void
onShowHelpDialog?: () => void
}
export function PromptInput({
opcodeUrl,
directory,
sessionID,
disabled,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
}: PromptInputProps) {
const [prompt, setPrompt] = useState('')
const [modelName, setModelName] = useState<string>('')
const [isBashMode, setIsBashMode] = useState(false)
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
const [suggestionPosition, setSuggestionPosition] = useState({ bottom: 0, left: 0, width: 0 })
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileInfo>())
const [showFileSuggestions, setShowFileSuggestions] = useState(false)
const [fileQuery, setFileQuery] = useState('')
const [fileSuggestionPosition, setFileSuggestionPosition] = useState({ bottom: 0, left: 0, width: 0 })
const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null)
const [selectedFileIndex, setSelectedFileIndex] = useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const isMobile = useMobile()
const textareaRef = useRef<HTMLTextAreaElement>(null)
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory)
const { data: messages } = useMessages(opcodeUrl, sessionID, directory)
const { preferences, updateSettings } = useSettings()
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
sessionID,
directory,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
})
const { files: searchResults } = useFileSearch(
opcodeUrl,
fileQuery,
showFileSuggestions,
directory
)
const handleSubmit = () => {
if (!prompt.trim() || disabled) return
if (isBashMode) {
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
sendShell.mutate({
sessionID,
command,
agent: currentMode
})
setPrompt('')
setIsBashMode(false)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
return
}
const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/)
if (commandMatch) {
const [, commandName] = commandMatch
const command = filterCommands(commandName)[0]
if (command) {
executeCommand(command)
setPrompt('')
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
return
}
}
const parts = parsePromptToParts(prompt, attachedFiles)
sendPrompt.mutate({
sessionID,
parts,
model: currentModel,
agent: currentMode
})
setPrompt('')
setAttachedFiles(new Map())
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
}
const handleStop = () => {
abortSession.mutate(sessionID)
}
const handleCommandSelect = async (command: CommandType) => {
if (!textareaRef.current) return
setShowSuggestions(false)
setSuggestionQuery('')
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const beforeCommand = prompt.slice(0, commandMatch.index)
const afterCommand = prompt.slice(cursorPosition)
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
}
const handleFileSelect = (filePath: string) => {
if (!mentionRange || !textareaRef.current) return
const filename = getFilename(filePath)
const beforeMention = prompt.slice(0, mentionRange.start)
const afterMention = prompt.slice(mentionRange.end)
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = filePath.startsWith('/')
? filePath
: directory
? `${directory}/${filePath}`
: filePath
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
})
return next
})
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
const handleModeToggle = () => {
const newMode = currentMode === 'plan' ? 'build' : 'plan'
updateSettings({ mode: newMode })
}
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (isBashMode && e.key === 'Escape') {
e.preventDefault()
setIsBashMode(false)
setPrompt('')
return
}
if (showFileSuggestions && searchResults.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedFileIndex(prev =>
prev < searchResults.length - 1 ? prev + 1 : prev
)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedFileIndex(prev => prev > 0 ? prev - 1 : 0)
return
}
if (e.key === 'Enter') {
e.preventDefault()
if (searchResults[selectedFileIndex]) {
handleFileSelect(searchResults[selectedFileIndex])
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
return
}
}
if (showSuggestions) {
const filteredCommands = filterCommands(suggestionQuery)
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedCommandIndex(prev => (prev + 1) % filteredCommands.length)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedCommandIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length)
return
}
if (e.key === 'Enter') {
e.preventDefault()
const selectedCommand = filteredCommands[selectedCommandIndex]
if (selectedCommand) {
handleCommandSelect(selectedCommand)
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowSuggestions(false)
setSuggestionQuery('')
setSelectedCommandIndex(0)
return
}
}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
handleSubmit()
} else if (e.key === 'Escape') {
setShowSuggestions(false)
setSuggestionQuery('')
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
setPrompt('')
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
}
}
const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value
if (value === '!' && prompt === '') {
setIsBashMode(true)
setPrompt(value)
return
}
if (isBashMode && value === '') {
setIsBashMode(false)
}
setPrompt(value)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
}
if (isBashMode) {
return
}
const cursorPosition = e.target.selectionStart
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
if (mentionTrigger) {
setFileQuery(mentionTrigger.query)
setMentionRange({ start: mentionTrigger.start, end: mentionTrigger.end })
setShowFileSuggestions(true)
setSelectedFileIndex(0)
if (textareaRef.current) {
const rect = textareaRef.current.getBoundingClientRect()
setFileSuggestionPosition({
bottom: window.innerHeight - rect.top + window.scrollY + 4,
left: rect.left + window.scrollX,
width: rect.width
})
}
} else {
const commandMatch = value.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const query = commandMatch[2]
setSuggestionQuery(query)
setShowSuggestions(true)
setSelectedCommandIndex(0)
if (textareaRef.current) {
const rect = textareaRef.current.getBoundingClientRect()
setSuggestionPosition({
bottom: window.innerHeight - rect.top + window.scrollY + 4,
left: rect.left + window.scrollX,
width: rect.width
})
}
} else {
setShowSuggestions(false)
setSuggestionQuery('')
}
if (showFileSuggestions) {
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
}
}
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const hasActiveStream = messages?.some(msg => isMessageStreaming(msg)) || false
const currentMode = preferences?.mode || 'build'
const currentModel = preferences?.defaultModel || ''
const modeColor = currentMode === 'plan' ? 'text-yellow-600 dark:text-yellow-500' : 'text-green-600 dark:text-green-500'
const modeBg = currentMode === 'plan' ? 'bg-yellow-500/10 border-yellow-500/30' : 'bg-green-500/10 border-green-500/30'
useEffect(() => {
const loadModelName = async () => {
if (currentModel) {
try {
const [providerId, modelId] = currentModel.split('/')
if (providerId && modelId) {
const model = await getModel(providerId, modelId)
if (model) {
setModelName(formatModelName(model))
} else {
setModelName(currentModel)
}
} else {
setModelName(currentModel)
}
} catch {
setModelName(currentModel)
}
} else {
setModelName('No model selected')
}
}
loadModelName()
}, [currentModel])
useEffect(() => {
if (textareaRef.current && !disabled && !hasActiveStream) {
textareaRef.current.focus()
}
}, [disabled, hasActiveStream])
return (
<div className="border-t border-border bg-background p-2 sm:p-3">
{isMobile ? (
<>
<div className="mb-2">
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Message..."
}
disabled={disabled || hasActiveStream}
className="w-full bg-background border rounded-lg px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed"
rows={1}
/>
</div>
<div className="flex gap-2 items-center justify-between mx-2">
<div className="flex gap-2 items-center">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName}
</button>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
title="Help"
>
?
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? 'Stop' : 'Send'}
</button>
</div>
</>
) : (
<>
<div className="flex gap-2 items-end mb-2 justify-between">
<div className="flex gap-2 items-end">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName}
</button>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
title="Help"
>
?
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex gap-2 items-end">
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Send a message... (Cmd/Ctrl+Enter)"
}
disabled={disabled || hasActiveStream}
className={`flex-1 bg-background border rounded-lg px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm ${
isBashMode
? 'border-purple-500/50 focus:ring-purple-500/50 bg-purple-500/5'
: 'border-border focus:ring-primary/50'
}`}
rows={1}
/>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? '■' : '↑'}
</button>
</div>
</>
)}
<CommandSuggestions
isOpen={showSuggestions}
query={suggestionQuery}
commands={filterCommands(suggestionQuery)}
onSelect={handleCommandSelect}
onClose={() => {
setShowSuggestions(false)
setSuggestionQuery('')
}}
position={suggestionPosition}
selectedIndex={selectedCommandIndex}
/>
<FileSuggestions
isOpen={showFileSuggestions}
query={fileQuery}
files={searchResults}
onSelect={handleFileSelect}
onClose={() => {
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
}}
position={fileSuggestionPosition}
selectedIndex={selectedFileIndex}
/>
</div>
)
}
@@ -0,0 +1,121 @@
import React from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import { Copy, Check } from 'lucide-react'
import type { components } from '@/api/opencode-types'
import 'highlight.js/styles/github-dark.css'
type TextPart = components['schemas']['TextPart']
interface TextPartProps {
part: TextPart
}
interface CodeBlockProps {
children?: React.ReactNode
className?: string
[key: string]: unknown
}
function CodeBlock({ children, className, ...props }: CodeBlockProps) {
const [copied, setCopied] = React.useState(false)
const extractTextContent = (node: React.ReactNode): string => {
if (typeof node === 'string') return node
if (typeof node === 'number') return node.toString()
if (Array.isArray(node)) return node.map(extractTextContent).join('')
if (React.isValidElement(node)) {
const element = node as React.ReactElement<any, any>
if (element.props.children) {
return extractTextContent(element.props.children as React.ReactNode)
}
}
return ''
}
const codeContent = extractTextContent(children)
const handleCopyCode = async () => {
try {
await navigator.clipboard.writeText(codeContent)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy code:', error)
}
}
return (
<div className="relative">
<pre className={`bg-accent p-4 rounded-lg overflow-x-auto border border-border my-4 ${className || ''}`} {...props}>
{children}
</pre>
<button
onClick={handleCopyCode}
className="absolute top-2 right-2 p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground"
title="Copy code"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</button>
</div>
)
}
export function TextPart({ part }: TextPartProps) {
if (!part.text || part.text.trim() === '') {
return (
<div className="text-muted-foreground italic text-sm">
[Empty message content]
</div>
)
}
return (
<div className="prose prose-invert prose-enhanced max-w-none text-foreground">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight, rehypeRaw]}
components={{
code({ className, children, ...props }) {
const isInline = !className || !className.includes('language-')
if (isInline) {
return (
<code className={className || "bg-accent px-1.5 py-0.5 rounded text-sm text-foreground"} {...props}>
{children}
</code>
)
}
return (
<code className={className} {...props}>
{children}
</code>
)
},
pre({ children }) {
return (
<CodeBlock>
{children}
</CodeBlock>
)
},
p({ children }) {
return <p className="text-foreground">{children}</p>
},
strong({ children }) {
return <strong className="font-semibold text-foreground">{children}</strong>
},
ul({ children }) {
return <ul className="list-disc text-foreground">{children}</ul>
},
ol({ children }) {
return <ol className="list-decimal text-foreground">{children}</ol>
}
}}
>
{part.text}
</ReactMarkdown>
</div>
)
}
@@ -0,0 +1,181 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
import { detectFileReferences } from '@/lib/fileReferences'
type ToolPart = components['schemas']['ToolPart']
interface ToolCallPartProps {
part: ToolPart
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
const jsonString = JSON.stringify(json, null, 2)
const references = detectFileReferences(jsonString)
if (references.length === 0) {
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{jsonString}</pre>
}
const parts: React.ReactNode[] = []
let lastIndex = 0
references.forEach((ref, index) => {
if (ref.startIndex > lastIndex) {
parts.push(jsonString.slice(lastIndex, ref.startIndex))
}
parts.push(
<span
key={`ref-${index}`}
onClick={(e) => {
e.stopPropagation()
onFileClick?.(ref.filePath)
}}
className="text-blue-300 hover:text-blue-200 cursor-pointer underline decoration-dotted"
title={`Click to open ${ref.filePath}`}
>
{ref.fullMatch}
</span>
)
lastIndex = ref.endIndex
})
if (lastIndex < jsonString.length) {
parts.push(jsonString.slice(lastIndex))
}
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{parts}</pre>
}
export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const defaultExpanded = preferences?.expandToolCalls ?? false
const [expanded, setExpanded] = useState(defaultExpanded)
const getStatusColor = () => {
switch (part.state.status) {
case 'completed':
return 'text-green-400'
case 'error':
return 'text-red-400'
case 'running':
return 'text-yellow-400'
default:
return 'text-zinc-400'
}
}
const getStatusIcon = () => {
switch (part.state.status) {
case 'completed':
return '✓'
case 'error':
return '✗'
case 'running':
return '⟳'
default:
return '○'
}
}
const getPreviewText = () => {
if (part.state.status === 'pending') return null
const input = part.state.input as Record<string, unknown>
if (!input) return null
switch (part.tool) {
case 'read':
case 'write':
case 'edit':
return (input.filePath as string) || null
case 'bash':
return (input.command as string) || null
case 'glob':
return (input.pattern as string) || null
case 'grep':
return (input.pattern as string) || null
case 'list':
return (input.path as string) || '.'
case 'task':
return (input.description as string) || null
default:
return null
}
}
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-card hover:bg-card-hover text-left flex items-center gap-2 text-sm"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.tool}</span>
{previewText && isFileTool ? (
<span
onClick={(e) => {
e.stopPropagation()
if (onFileClick) {
onFileClick(previewText)
}
}}
className="text-blue-300 text-xs truncate hover:text-blue-200 cursor-pointer underline decoration-dotted"
title={`Click to open ${previewText}`}
>
{previewText}
</span>
) : previewText ? (
<span className="text-zinc-400 text-xs truncate">{previewText}</span>
) : null}
<span className="text-muted-foreground text-xs ml-auto">({part.state.status})</span>
</button>
{expanded && (
<div className="bg-card p-4 space-y-2">
{part.state.status === 'running' && (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
{part.state.status === 'completed' && (
<>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">
{part.state.output}
</pre>
</div>
{part.state.time && (
<div className="text-xs text-zinc-500">
Duration: {((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
</div>
)}
</>
)}
{part.state.status === 'error' && (
<div className="text-sm">
<div className="text-red-400 mb-1">Error:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto text-red-300">
{part.state.error}
</pre>
</div>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,296 @@
import { useState, useEffect, useCallback } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Loader2, Search, Check } from "lucide-react";
import {
getProvidersWithModels,
formatModelName,
formatProviderName,
} from "@/api/providers";
import { useSettings } from "@/hooks/useSettings";
import { useOpenCodeClient } from "@/hooks/useOpenCode";
import { useParams } from "react-router-dom";
import type { ProviderWithModels, Model } from "@/api/providers";
interface ModelSelectDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
opcodeUrl?: string | null;
}
export function ModelSelectDialog({
open,
onOpenChange,
opcodeUrl,
}: ModelSelectDialogProps) {
const [providers, setProviders] = useState<ProviderWithModels[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [selectedProvider, setSelectedProvider] = useState<string>("");
const { preferences, updateSettings } = useSettings();
const client = useOpenCodeClient(opcodeUrl);
const { sessionID } = useParams<{ sessionID: string }>();
const currentModel = preferences?.defaultModel || "";
const loadProviders = useCallback(async () => {
try {
setLoading(true);
const data = await getProvidersWithModels();
setProviders(data);
if (currentModel) {
const [providerId] = currentModel.split("/");
setSelectedProvider(providerId);
}
} catch {
// Ignore errors when loading providers
} finally {
setLoading(false);
}
}, [opcodeUrl, currentModel]);
useEffect(() => {
if (open) {
loadProviders();
}
}, [open, loadProviders]);
const filteredProviders = providers.filter((provider) => {
const matchesSearch =
provider.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
provider.models.some(
(model) =>
model.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
model.id.toLowerCase().includes(searchQuery.toLowerCase()),
);
const matchesProvider =
!selectedProvider || provider.id === selectedProvider;
return matchesSearch && matchesProvider;
});
const handleModelSelect = async (providerId: string, modelId: string) => {
const newModel = `${providerId}/${modelId}`;
// Update settings for future sessions
updateSettings({ defaultModel: newModel });
// If we're in a session, try to update the current session's model
if (sessionID && client) {
try {
await client.sendCommand(sessionID, {
command: "model",
arguments: newModel,
model: newModel,
});
} catch {
// Ignore errors when updating session model
}
}
onOpenChange(false);
};
const handleProviderChange = (providerId: string) => {
setSelectedProvider(providerId);
};
const getStatusBadge = (model: Model) => {
if (model.experimental)
return <Badge variant="secondary">Experimental</Badge>;
if (model.status === "alpha")
return <Badge variant="destructive">Alpha</Badge>;
if (model.status === "beta") return <Badge variant="secondary">Beta</Badge>;
return null;
};
const getModelCapabilities = (model: Model) => {
const capabilities = [];
if (model.reasoning) capabilities.push("Reasoning");
if (model.tool_call) capabilities.push("Tools");
if (model.attachment) capabilities.push("Files");
return capabilities;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh] bg-[#1a1a1a] border-[#333] text-white">
<DialogHeader>
<DialogTitle className="text-xl font-semibold">
Select Model
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{/* Search */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-zinc-400" />
<Input
placeholder="Search models or providers..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 bg-[#0a0a0a] border-[#333] text-white placeholder-zinc-500"
/>
</div>
{/* Provider Filter */}
<div className="flex gap-2 flex-wrap">
<Button
variant={!selectedProvider ? "default" : "outline"}
size="sm"
onClick={() => handleProviderChange("")}
className={
!selectedProvider
? "bg-blue-600 text-white"
: "bg-[#2a2a2a] border-[#333] text-zinc-300 hover:bg-[#333]"
}
>
All Providers
</Button>
{providers.map((provider) => (
<Button
key={provider.id}
variant={
selectedProvider === provider.id ? "default" : "outline"
}
size="sm"
onClick={() => handleProviderChange(provider.id)}
className={
selectedProvider === provider.id
? "bg-blue-600 text-white"
: "bg-[#2a2a2a] border-[#333] text-zinc-300 hover:bg-[#333]"
}
>
{formatProviderName(provider)}
</Button>
))}
</div>
{/* Models List */}
<div className="min-h-[300px] max-h-[400px] overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-zinc-500" />
</div>
) : filteredProviders.length === 0 ? (
<div className="text-center py-12 text-zinc-500">
No providers or models found
</div>
) : (
<div className="space-y-4">
{filteredProviders.map((provider) => (
<div key={provider.id} className="space-y-2">
<h3 className="font-medium text-zinc-200 flex items-center gap-2">
{formatProviderName(provider)}
{provider.api && (
<Badge variant="outline" className="text-xs">
API
</Badge>
)}
</h3>
<div className="grid gap-2 pl-4">
{provider.models.map((model) => {
const modelKey = `${provider.id}/${model.id}`;
const isSelected = currentModel === modelKey;
const capabilities = getModelCapabilities(model);
return (
<div
key={model.id}
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
isSelected
? "bg-blue-600/20 border-blue-500"
: "bg-[#0a0a0a] border-[#333] hover:bg-[#1a1a1a] hover:border-[#444]"
}`}
onClick={() =>
handleModelSelect(provider.id, model.id)
}
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-medium text-white">
{formatModelName(model)}
</h4>
{isSelected && (
<Check className="h-4 w-4 text-blue-400" />
)}
{getStatusBadge(model)}
</div>
<p className="text-sm text-zinc-400 mb-2">
{model.id}
</p>
{/* Capabilities */}
{capabilities.length > 0 && (
<div className="flex gap-1 flex-wrap mb-2">
{capabilities.map((cap) => (
<Badge
key={cap}
variant="secondary"
className="text-xs"
>
{cap}
</Badge>
))}
</div>
)}
{/* Model Info */}
<div className="text-xs text-zinc-500 space-y-1">
<div>
Context:{" "}
{model.limit?.context?.toLocaleString() ||
"N/A"}{" "}
tokens
</div>
<div>
Output:{" "}
{model.limit?.output?.toLocaleString() ||
"N/A"}{" "}
tokens
</div>
{model.cost && (
<div>
Cost: ${model.cost.input.toFixed(6)}
/input, ${model.cost.output.toFixed(6)}
/output
</div>
)}
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
))}
</div>
)}
</div>
{/* Current Selection */}
{currentModel && (
<div className="pt-4 border-t border-[#333]">
<p className="text-sm text-zinc-400">
Current model:{" "}
<span className="text-white font-medium">{currentModel}</span>
</p>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,130 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createRepo } from "@/api/repos";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Loader2 } from "lucide-react";
interface AddBranchWorkspaceDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoUrl: string;
}
export function AddBranchWorkspaceDialog({
open,
onOpenChange,
repoUrl,
}: AddBranchWorkspaceDialogProps) {
const [branch, setBranch] = useState("");
const [useWorktree, setUseWorktree] = useState(true);
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: () =>
createRepo(repoUrl, branch || undefined, undefined, useWorktree),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setBranch("");
setUseWorktree(true);
onOpenChange(false);
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (branch.trim()) {
mutation.mutate();
}
};
const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
e.stopPropagation();
setUseWorktree(e.target.checked);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[90%] sm:max-w-[500px] bg-[#141414] border-[#2a2a2a]">
<DialogHeader>
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
Add Branch Workspace
</DialogTitle>
<p className="text-sm text-zinc-400 mt-1">
Create a new workspace for{" "}
{repoUrl.split("/").pop()?.replace(".git", "")}
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-4">
<div className="space-y-2">
<label className="text-sm text-zinc-400">Branch *</label>
<Input
placeholder="feature-branch, main, etc."
value={branch}
onChange={(e) => setBranch(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<input
type="checkbox"
id="worktree-checkbox"
checked={useWorktree}
onChange={handleCheckboxChange}
disabled={mutation.isPending}
className="w-4 h-4 rounded border-gray-600 bg-gray-800 text-blue-600 focus:ring-blue-600 focus:ring-2 cursor-pointer accent-blue-600"
onClick={(e) => e.stopPropagation()}
/>
<label
htmlFor="worktree-checkbox"
className="text-sm text-zinc-400 cursor-pointer select-none"
onClick={(e) => {
e.preventDefault();
if (!mutation.isPending) {
setUseWorktree(!useWorktree);
}
}}
>
Create as worktree
</label>
</div>
<p className="text-xs text-zinc-500">
{useWorktree
? "Creates a git worktree - shares git history with base repo (recommended, faster)"
: "Creates a full clone - independent copy of the repository (slower, more disk space)"}
</p>
</div>
<Button
type="submit"
disabled={!branch || mutation.isPending}
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
>
{mutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
{useWorktree ? "Creating worktree..." : "Cloning..."}
</>
) : useWorktree ? (
"Create Worktree"
) : (
"Clone Branch"
)}
</Button>
{mutation.isError && (
<p className="text-sm text-red-400">{mutation.error.message}</p>
)}
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,96 @@
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createRepo } from '@/api/repos'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Loader2 } from 'lucide-react'
interface AddRepoDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
const [repoUrl, setRepoUrl] = useState('')
const [branch, setBranch] = useState('')
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: () => createRepo(repoUrl, branch || undefined, undefined, false),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repos'] })
setRepoUrl('')
setBranch('')
onOpenChange(false)
},
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (repoUrl) {
mutation.mutate()
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px] bg-[#141414] border-[#2a2a2a]">
<DialogHeader>
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
Add Repository
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-4">
<div className="space-y-2">
<label className="text-sm text-zinc-400">Repository URL</label>
<Input
placeholder="https://github.com/user/repo.git"
value={repoUrl}
onChange={(e) => setRepoUrl(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
</div>
<div className="space-y-2">
<label className="text-sm text-zinc-400">Branch</label>
<Input
placeholder="Optional - uses default if empty"
value={branch}
onChange={(e) => setBranch(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
<p className="text-xs text-zinc-500">
{branch
? `Clones repository directly to '${branch}' branch`
: "Clones repository to default branch"
}
</p>
</div>
<Button
type="submit"
disabled={!repoUrl || mutation.isPending}
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
>
{mutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Cloning...
</>
) : (
'Add Repository'
)}
</Button>
{mutation.isError && (
<p className="text-sm text-red-400">
{mutation.error.message}
</p>
)}
</form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,102 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { GitBranch, Check, Plus } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { listBranches, switchBranch } from "@/api/repos";
import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog";
interface BranchSwitcherProps {
repoId: number;
currentBranch: string;
isWorktree?: boolean;
repoUrl: string;
}
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: BranchSwitcherProps) {
const [addBranchOpen, setAddBranchOpen] = useState(false);
const queryClient = useQueryClient();
const { data: branches } = useQuery({
queryKey: ["branches", repoId],
queryFn: () => listBranches(repoId),
enabled: !!repoId,
});
const switchBranchMutation = useMutation({
mutationFn: (branch: string) => switchBranch(repoId, branch),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repo", repoId] });
queryClient.invalidateQueries({ queryKey: ["branches", repoId] });
},
});
if (isWorktree) {
return null;
}
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-6 px-1 sm:px-2 text-[10px] sm:text-xs text-blue-400 hover:text-blue-300 hover:bg-accent gap-1 border border-blue-500/20"
>
<GitBranch className="w-3 h-3" />
<span className="hidden sm:inline">{currentBranch}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="bg-card border-border min-w-[200px]">
{branches?.remote && branches.remote.length > 0 ? (
branches.remote.map((branch: string) => (
<DropdownMenuItem
key={branch}
onClick={() => switchBranchMutation.mutate(branch)}
disabled={switchBranchMutation.isPending}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">{branch}</span>
{branch === currentBranch && <Check className="w-3 h-3 text-green-500" />}
</div>
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
</DropdownMenuItem>
)}
{!isWorktree && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setAddBranchOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<Plus className="w-3 h-3" />
<span className="flex-1">Add Branch</span>
</div>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repoUrl}
/>
</>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Loader2, Trash2, GitBranch, ExternalLink } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useState } from "react";
import { AddBranchWorkspaceDialog } from "./AddBranchWorkspaceDialog";
interface RepoCardProps {
repo: {
id: number;
repoUrl: string;
branch?: string;
currentBranch?: string;
cloneStatus: string;
isWorktree?: boolean;
};
onDelete: (id: number) => void;
isDeleting: boolean;
isSelected?: boolean;
onSelect?: (id: number, selected: boolean) => void;
}
export function RepoCard({
repo,
onDelete,
isDeleting,
isSelected = false,
onSelect,
}: RepoCardProps) {
const navigate = useNavigate();
const [addBranchOpen, setAddBranchOpen] = useState(false);
const repoName = repo.repoUrl.split("/").slice(-1)[0].replace(".git", "");
const branchToDisplay = repo.currentBranch || repo.branch;
const displayName = branchToDisplay ? `${repoName} (${branchToDisplay})` : repoName;
const isReady = repo.cloneStatus === "ready";
return (
<div
className={`group relative bg-gradient-to-br from-card to-card-hover border rounded-xl overflow-hidden transition-all duration-200 hover:shadow-lg w-full ${
isSelected
? "border-blue-500 shadow-lg shadow-blue-900/30"
: "border-border hover:border-border hover:shadow-blue-900/20"
}`}
>
<div className="p-4 sm:p-6">
<div className="mb-4">
<div className="flex items-center gap-2 mb-2">
{onSelect && (
<input
type="checkbox"
id="select-repo"
checked={isSelected}
onChange={(e) => {
e.stopPropagation();
onSelect(repo.id, e.target.checked);
}}
onClick={(e) => {
e.stopPropagation();
}}
className="w-5 h-5 rounded border-gray-600 accent-blue-500 cursor-pointer"
/>
)}
<h3
onClick={(e) => {
e.stopPropagation();
if (isReady) {
navigate(`/repos/${repo.id}`);
}
}}
className={`font-semibold text-lg text-foreground truncate group-hover:text-blue-400 transition-colors ${
isReady ? "cursor-pointer" : "cursor-not-allowed opacity-60"
}`}
>
{displayName}
</h3>
{repo.isWorktree && (
<Badge
className="text-xs px-2.5 py-0.5 bg-purple-600/20 text-purple-400 border-purple-600/40"
>
worktree
</Badge>
)}
{repo.cloneStatus && (
<Badge
className={`text-xs px-2.5 py-0.5 ${
isReady
? "bg-green-600/20 text-green-400 border-green-600/40"
: repo.cloneStatus === "cloning"
? "bg-blue-600/20 text-blue-400 border-blue-600/40"
: "bg-red-600/20 text-red-400 border-red-600/40"
}`}
>
{repo.cloneStatus}
</Badge>
)}
</div>
<p className="text-sm text-muted-foreground truncate">{repo.repoUrl}</p>
</div>
<div className="flex flex-col gap-2">
{repo.cloneStatus === "cloning" && (
<div className="text-sm text-muted-foreground flex items-center gap-2">
<Loader2 className="w-3 h-3 animate-spin text-blue-400" />
<span>Cloning repository...</span>
</div>
)}
<div className="flex gap-2">
<Button
size="sm"
onClick={(e) => {
e.stopPropagation();
navigate(`/repos/${repo.id}`);
}}
disabled={!isReady}
className="cursor-pointer flex-1 h-10 sm:h-9 px-3"
>
<ExternalLink className="w-4 h-4 mr-2" />
Open
</Button>
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.stopPropagation();
setAddBranchOpen(true);
}}
disabled={!isReady}
className="h-10 sm:h-9 w-10 p-0"
>
<GitBranch className="w-4 h-4" />
</Button>
<Button
size="sm"
variant="destructive"
onClick={(e) => {
e.stopPropagation();
onDelete(repo.id);
}}
disabled={isDeleting}
className="h-10 sm:h-9 w-10 p-0"
>
{isDeleting ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Trash2 className="w-4 h-4" />
)}
</Button>
</div>
</div>
</div>
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repo.repoUrl}
/>
</div>
);
}
+229
View File
@@ -0,0 +1,229 @@
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { listRepos, deleteRepo } from "@/api/repos";
import { DeleteDialog } from "@/components/ui/delete-dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Loader2, GitBranch, Search, Trash2 } from "lucide-react";
import { RepoCard } from "./RepoCard";
export function RepoList() {
const queryClient = useQueryClient();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [repoToDelete, setRepoToDelete] = useState<number | null>(null);
const [selectedRepos, setSelectedRepos] = useState<Set<number>>(new Set());
const [searchQuery, setSearchQuery] = useState("");
const {
data: repos,
isLoading,
error,
} = useQuery({
queryKey: ["repos"],
queryFn: listRepos,
});
const deleteMutation = useMutation({
mutationFn: deleteRepo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setDeleteDialogOpen(false);
setRepoToDelete(null);
},
});
const batchDeleteMutation = useMutation({
mutationFn: async (repoIds: number[]) => {
await Promise.all(repoIds.map((id) => deleteRepo(id)));
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setDeleteDialogOpen(false);
setSelectedRepos(new Set());
},
});
if (isLoading && !repos) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin" />
</div>
);
}
if (error) {
return (
<div className="text-center p-8 text-destructive">
Failed to load repositories:{" "}
{error instanceof Error ? error.message : "Unknown error"}
</div>
);
}
if (!repos || repos.length === 0) {
return (
<div className="text-center p-12">
<GitBranch className="w-12 h-12 mx-auto mb-4 text-zinc-600" />
<p className="text-zinc-500">
No repositories yet. Add one to get started.
</p>
</div>
);
}
const dedupedRepos = repos.reduce((acc, repo) => {
if (repo.isWorktree) {
acc.push(repo);
} else {
const key = repo.repoUrl;
const existing = acc.find(r => r.repoUrl === key && !r.isWorktree);
if (!existing) {
acc.push(repo);
}
}
return acc;
}, [] as typeof repos);
const filteredRepos = dedupedRepos.filter((repo) => {
const repoName = repo.repoUrl.split("/").slice(-1)[0].replace(".git", "");
return (
repoName.toLowerCase().includes(searchQuery.toLowerCase()) ||
repo.repoUrl.toLowerCase().includes(searchQuery.toLowerCase())
);
});
const handleSelectRepo = (id: number, selected: boolean) => {
const newSelected = new Set(selectedRepos);
if (selected) {
newSelected.add(id);
} else {
newSelected.delete(id);
}
setSelectedRepos(newSelected);
};
const handleSelectAll = () => {
const allFilteredSelected = filteredRepos.every((repo) =>
selectedRepos.has(repo.id),
);
if (allFilteredSelected) {
setSelectedRepos(new Set());
} else {
const filteredIds = filteredRepos.map((repo) => repo.id);
setSelectedRepos(new Set([...selectedRepos, ...filteredIds]));
}
};
const handleBatchDelete = () => {
if (selectedRepos.size > 0) {
setDeleteDialogOpen(true);
}
};
return (
<>
<div className="p-2 md:p-4">
<div className="flex items-center gap-3 mb-6">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
<Input
placeholder="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
{filteredRepos.length > 0 && (
<Button
onClick={handleSelectAll}
variant={selectedRepos.size > 0 ? "default" : "outline"}
className="whitespace-nowrap"
>
{filteredRepos.every((repo) => selectedRepos.has(repo.id))
? "Deselect All"
: "Select All"}
</Button>
)}
<Button
onClick={handleBatchDelete}
variant="destructive"
disabled={selectedRepos.size === 0}
className="hidden md:flex whitespace-nowrap"
>
<Trash2 className="w-4 h-4 mr-2" />
Delete ({selectedRepos.size})
</Button>
<Button
onClick={handleBatchDelete}
variant="destructive"
disabled={selectedRepos.size === 0}
size="icon"
className="md:hidden"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
<div className="h-[calc(100vh-200px)] overflow-y-auto">
{filteredRepos.length === 0 ? (
<div className="text-center p-12">
<Search className="w-12 h-12 mx-auto mb-4 text-zinc-600" />
<p className="text-zinc-500">
No repositories found matching "{searchQuery}"
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-4 w-full">
{filteredRepos.map((repo) => (
<RepoCard
key={repo.id}
repo={repo}
onDelete={(id) => {
setRepoToDelete(id);
setDeleteDialogOpen(true);
}}
isDeleting={
deleteMutation.isPending && repoToDelete === repo.id
}
isSelected={selectedRepos.has(repo.id)}
onSelect={handleSelectRepo}
/>
))}
</div>
)}
</div>
</div>
<DeleteDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onConfirm={() => {
if (repoToDelete) {
deleteMutation.mutate(repoToDelete);
} else if (selectedRepos.size > 0) {
batchDeleteMutation.mutate(Array.from(selectedRepos));
}
}}
onCancel={() => {
setDeleteDialogOpen(false);
setRepoToDelete(null);
}}
title={
selectedRepos.size > 0
? "Delete Multiple Repositories"
: "Delete Repository"
}
description={
selectedRepos.size > 0
? `Are you sure you want to delete ${selectedRepos.size} repositor${selectedRepos.size === 1 ? "y" : "ies"}? This will remove all local files. This action cannot be undone.`
: "Are you sure you want to delete this repository? This will remove all local files. This action cannot be undone."
}
isDeleting={deleteMutation.isPending || batchDeleteMutation.isPending}
/>
</>
);
}
@@ -0,0 +1,153 @@
import { useState, useEffect } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { AlertCircle, Loader2 } from 'lucide-react'
import { settingsApi } from '@/api/settings'
import * as reposApi from '@/api/repos'
import type { OpenCodeConfig } from '@/api/types/settings'
interface SwitchConfigDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
repoId: number
currentConfigName?: string
onConfigSwitched: (configName: string) => void
}
export function SwitchConfigDialog({
open,
onOpenChange,
repoId,
currentConfigName,
onConfigSwitched,
}: SwitchConfigDialogProps) {
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
const [selectedConfig, setSelectedConfig] = useState<string>('')
const [loading, setLoading] = useState(true)
const [switching, setSwitching] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!open) return
const fetchConfigs = async () => {
try {
setLoading(true)
setError(null)
const response = await settingsApi.getOpenCodeConfigs()
setConfigs(response.configs || [])
setSelectedConfig(currentConfigName || '')
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load configs')
} finally {
setLoading(false)
}
}
fetchConfigs()
}, [open, currentConfigName])
const handleSwitch = async () => {
if (!selectedConfig) {
setError('Please select a config')
return
}
if (selectedConfig === currentConfigName) {
onOpenChange(false)
return
}
try {
setSwitching(true)
setError(null)
await reposApi.switchRepoConfig(repoId, selectedConfig)
onConfigSwitched(selectedConfig)
onOpenChange(false)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to switch config')
} finally {
setSwitching(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Switch Config</DialogTitle>
<DialogDescription>
Select a different OpenCode configuration for this repository
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{currentConfigName && (
<div className="text-sm text-zinc-400">
Current config: <span className="text-white font-semibold">{currentConfigName}</span>
</div>
)}
{loading ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="w-4 h-4 animate-spin text-blue-400" />
<span className="ml-2 text-sm text-zinc-400">Loading configs...</span>
</div>
) : configs.length === 0 ? (
<div className="text-sm text-zinc-400">No configs available</div>
) : (
<Select value={selectedConfig} onValueChange={setSelectedConfig}>
<SelectTrigger className="bg-[#1a1a1a] border-[#2a2a2a] text-white">
<SelectValue placeholder="Select a config" />
</SelectTrigger>
<SelectContent className="bg-[#1a1a1a] border-[#2a2a2a]">
{configs.map((config) => (
<SelectItem key={config.id} value={config.name}>
<div className="flex items-center gap-2">
{config.name}
{config.isDefault && (
<span className="text-xs text-blue-400 ml-2">(default)</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)}
{error && (
<div className="flex items-start gap-2 bg-red-900/20 border border-red-800/50 rounded p-3">
<AlertCircle className="w-4 h-4 text-red-400 mt-0.5 flex-shrink-0" />
<p className="text-sm text-red-400">{error}</p>
</div>
)}
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
className="border-[#2a2a2a] hover:bg-[#1a1a1a]"
>
Cancel
</Button>
<Button
onClick={handleSwitch}
disabled={!selectedConfig || switching || selectedConfig === currentConfigName}
className="bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
>
{switching ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Switching...
</>
) : (
'Switch Config'
)}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,96 @@
import { useContextUsage } from '@/hooks/useContextUsage'
import { getModel, formatModelName } from '@/api/providers'
import { useSettings } from '@/hooks/useSettings'
import { useState, useEffect } from 'react'
interface ContextUsageIndicatorProps {
opcodeUrl: string | null
sessionID: string | undefined
directory?: string
}
export function ContextUsageIndicator({ opcodeUrl, sessionID, directory }: ContextUsageIndicatorProps) {
const { totalTokens, contextLimit, usagePercentage, currentModel, isLoading } = useContextUsage(opcodeUrl, sessionID, directory)
const { preferences } = useSettings()
const [modelName, setModelName] = useState<string>('')
const displayModel = preferences?.defaultModel || currentModel || ''
useEffect(() => {
const loadModelName = async () => {
if (displayModel) {
try {
const [providerId, modelId] = displayModel.split('/')
if (providerId && modelId) {
const model = await getModel(providerId, modelId)
if (model) {
setModelName(formatModelName(model))
} else {
setModelName(displayModel)
}
} else {
setModelName(displayModel)
}
} catch {
setModelName(displayModel)
}
} else {
setModelName('')
}
}
loadModelName()
}, [displayModel, opcodeUrl])
if (isLoading) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">Loading...</span>
</div>
)
}
if (!modelName) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">No model</span>
</div>
)
}
const getUsageColor = (percentage: number) => {
if (percentage < 50) return 'bg-green-700 dark:bg-green-400'
if (percentage < 80) return 'bg-yellow-700 dark:bg-yellow-400'
return 'bg-red-700 dark:bg-red-400'
}
const getUsageTextColor = (percentage: number) => {
if (percentage < 50) return 'text-green-700 dark:text-green-400'
if (percentage < 80) return 'text-yellow-700 dark:text-yellow-400'
return 'text-red-700 dark:text-red-400'
}
if (!contextLimit) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{modelName}</span>
</div>
)
}
return (
<div className="flex items-center gap-2">
<div className="flex items-center gap-2 min-w-0">
<div className="w-16 h-2 bg-muted rounded-full overflow-hidden border border-border">
<div
className={`h-full transition-all duration-300 ${getUsageColor(usagePercentage || 0)}`}
style={{ width: `${Math.min(usagePercentage || 0, 100)}%` }}
/>
</div>
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usagePercentage || 0)}`}>
{totalTokens.toLocaleString()} / {contextLimit.toLocaleString()}
</span>
</div>
</div>
)
}
@@ -0,0 +1,30 @@
import { DeleteDialog } from '@/components/ui/delete-dialog'
interface DeleteSessionDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
isDeleting?: boolean
sessionCount?: number
}
export function DeleteSessionDialog({ open, onOpenChange, onConfirm, onCancel, isDeleting = false, sessionCount = 1 }: DeleteSessionDialogProps) {
const isMultiple = sessionCount > 1
const title = isMultiple ? "Delete Sessions" : "Delete Session"
const description = isMultiple
? `Are you sure you want to delete ${sessionCount} sessions? This action cannot be undone.`
: "Are you sure you want to delete this session? This action cannot be undone."
return (
<DeleteDialog
open={open}
onOpenChange={onOpenChange}
onConfirm={onConfirm}
onCancel={onCancel}
title={title}
description={description}
isDeleting={isDeleting}
/>
)
}
@@ -0,0 +1,116 @@
import { BackButton } from "@/components/ui/back-button";
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
import { BranchSwitcher } from "@/components/repo/BranchSwitcher";
import { Button } from "@/components/ui/button";
import { Loader2, Settings, FolderOpen } from "lucide-react";
interface Repo {
id: number;
repoUrl: string;
fullPath: string;
localPath: string;
currentBranch?: string;
isWorktree?: boolean;
cloneStatus: 'ready' | 'cloning' | 'error';
}
interface SessionDetailHeaderProps {
repo: Repo;
sessionId: string;
sessionTitle: string;
repoId: number;
isConnected: boolean;
opcodeUrl: string | null;
repoDirectory: string | undefined;
onFileBrowserOpen: () => void;
onSettingsOpen: () => void;
onShowModelsDialog?: () => void;
}
export function SessionDetailHeader({
repo,
sessionId,
sessionTitle,
repoId,
isConnected,
opcodeUrl,
repoDirectory,
onFileBrowserOpen,
onSettingsOpen,
}: SessionDetailHeaderProps) {
if (repo.cloneStatus !== 'ready') {
return (
<div className="sticky top-0 z-10 border-b border-border bg-gradient-to-b from-background via-background to-background backdrop-blur-sm px-2 sm:px-4 py-1.5 sm:py-2">
<div className="flex items-center justify-center">
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground mr-2" />
<span className="text-sm text-muted-foreground">
{repo.cloneStatus === 'cloning' ? 'Cloning repository...' : 'Repository not ready'}
</span>
</div>
</div>
);
}
const repoName = repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository";
const currentBranch = repo.currentBranch || "main";
return (
<div className="sticky top-0 z-10 border-b border-border bg-gradient-to-b from-background via-background to-background backdrop-blur-sm px-2 sm:px-4 py-1.5 sm:py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 sm:gap-3 min-w-0 flex-1">
<BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
<div className="min-w-0 flex-1">
<h1 className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate">
{sessionTitle}
</h1>
<div className="flex items-center gap-2">
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
{repoName}
</p>
<BranchSwitcher
repoId={repoId}
currentBranch={currentBranch}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
/>
</div>
</div>
</div>
<div className="flex items-center gap-2 sm:gap-4 flex-shrink-0">
<div className="hidden sm:block">
<ContextUsageIndicator
opcodeUrl={opcodeUrl}
sessionID={sessionId}
directory={repoDirectory}
/>
</div>
<div className="flex items-center gap-1 sm:gap-2">
<div
className={`w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full ${isConnected ? "bg-green-500" : "bg-red-500"}`}
/>
<span className="text-xs text-muted-foreground hidden sm:inline">
{isConnected ? "Connected" : "Disconnected"}
</span>
</div>
<Button
variant="ghost"
size="icon"
onClick={onFileBrowserOpen}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
>
<FolderOpen className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={onSettingsOpen}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
>
<Settings className="w-4 h-4" />
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,237 @@
import { useState, useMemo } from "react";
import { useSessions, useDeleteSession } from "@/hooks/useOpenCode";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { Trash2, GitBranch, Clock, Search } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
interface SessionListProps {
opcodeUrl: string;
directory?: string;
activeSessionID?: string;
onSelectSession: (sessionID: string) => void;
}
export const SessionList = ({
opcodeUrl,
directory,
activeSessionID,
onSelectSession,
}: SessionListProps) => {
const { data: sessions, isLoading } = useSessions(opcodeUrl, directory);
const deleteSession = useDeleteSession(opcodeUrl, directory);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [sessionToDelete, setSessionToDelete] = useState<
string | string[] | null
>(null);
const [searchQuery, setSearchQuery] = useState("");
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(
new Set(),
);
const filteredSessions = useMemo(() => {
if (!sessions) return [];
if (!searchQuery.trim()) return sessions;
const query = searchQuery.toLowerCase();
return sessions.filter((session) =>
(session.title || "Untitled Session").toLowerCase().includes(query),
);
}, [sessions, searchQuery]);
if (isLoading) {
return <div className="p-4 text-sm text-gray-400">Loading sessions...</div>;
}
if (!sessions || sessions.length === 0) {
return (
<div className="p-4 text-sm text-gray-400">
No sessions yet. Create one to get started.
</div>
);
}
const handleDelete = (
sessionId: string,
e: React.MouseEvent<HTMLButtonElement>,
) => {
e.stopPropagation();
setSessionToDelete(sessionId);
setDeleteDialogOpen(true);
};
const confirmDelete = async () => {
if (sessionToDelete) {
await deleteSession.mutateAsync(sessionToDelete);
setDeleteDialogOpen(false);
setSessionToDelete(null);
setSelectedSessions(new Set());
}
};
const cancelDelete = () => {
setDeleteDialogOpen(false);
setSessionToDelete(null);
};
const toggleSessionSelection = (sessionId: string, selected: boolean) => {
const newSelected = new Set(selectedSessions);
if (selected) {
newSelected.add(sessionId);
} else {
newSelected.delete(sessionId);
}
setSelectedSessions(newSelected);
};
const toggleSelectAll = () => {
if (!filteredSessions || filteredSessions.length === 0) return;
const allFilteredSelected = filteredSessions.every((session) =>
selectedSessions.has(session.id),
);
if (allFilteredSelected) {
setSelectedSessions(new Set());
} else {
const filteredIds = filteredSessions.map((s) => s.id);
setSelectedSessions(new Set([...selectedSessions, ...filteredIds]));
}
};
const handleBulkDelete = () => {
if (selectedSessions.size > 0) {
setSessionToDelete(Array.from(selectedSessions));
setDeleteDialogOpen(true);
}
};
return (
<div className="flex flex-col h-full">
<div className="p-4 flex-shrink-0">
<div className="flex items-center gap-3 mb-3">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input
type="text"
placeholder="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
{filteredSessions && filteredSessions.length > 0 && (
<Button
onClick={toggleSelectAll}
variant={selectedSessions.size > 0 ? "default" : "outline"}
className="whitespace-nowrap"
>
{filteredSessions.every((session) =>
selectedSessions.has(session.id),
)
? "Deselect All"
: "Select All"}
</Button>
)}
<Button
onClick={handleBulkDelete}
variant="destructive"
disabled={selectedSessions.size === 0}
className="hidden md:flex whitespace-nowrap"
>
<Trash2 className="w-4 h-4 mr-2" />
Delete ({selectedSessions.size})
</Button>
<Button
onClick={handleBulkDelete}
variant="destructive"
disabled={selectedSessions.size === 0}
size="icon"
className="md:hidden"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<div className="flex flex-col gap-2">
{filteredSessions.length === 0 ? (
<div className="text-sm text-gray-400 text-center py-4">
No sessions found
</div>
) : (
filteredSessions.map((session) => (
<Card
key={session.id}
className={`p-3 cursor-pointer transition-all ${
selectedSessions.has(session.id)
? "border-blue-500 shadow-lg shadow-blue-900/30 bg-[#2a2a2a]"
: activeSessionID === session.id
? "bg-[#333333] border-[#5a5a5a]"
: "bg-[#2a2a2a] border-[#4a4a4a] hover:bg-[#333333] hover:border-[#5a5a5a]"
} hover:shadow-lg`}
onClick={() => onSelectSession(session.id)}
>
<div className="flex items-start justify-between gap-2">
<div className="flex items-start gap-2 flex-1 min-w-0">
<input
type="checkbox"
checked={selectedSessions.has(session.id)}
onChange={(e) => {
e.stopPropagation();
toggleSessionSelection(session.id, e.target.checked);
}}
onClick={(e) => {
e.stopPropagation();
}}
className="w-5 h-5 rounded border-gray-600 accent-blue-500 cursor-pointer flex-shrink-0 mt-0.5"
/>
<div className="flex-1 min-w-0">
<h3 className="text-sm font-medium text-white truncate">
{session.title || "Untitled Session"}
</h3>
<div className="flex items-center gap-3 mt-1 text-xs text-gray-400">
{session.parentID && (
<span className="flex items-center gap-1">
<GitBranch className="w-3 h-3" />
Forked
</span>
)}
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{formatDistanceToNow(new Date(session.time.updated), {
addSuffix: true,
})}
</span>
</div>
</div>
</div>
<button
className="h-6 w-6 p-0 text-gray-400 hover:text-red-400 bg-transparent border-none cursor-pointer"
onClick={(e) => handleDelete(session.id, e)}
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</Card>
))
)}
</div>
</div>
<DeleteSessionDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onConfirm={confirmDelete}
onCancel={cancelDelete}
isDeleting={deleteSession.isPending}
sessionCount={
Array.isArray(sessionToDelete) ? sessionToDelete.length : 1
}
/>
</div>
);
};
@@ -0,0 +1,222 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Card, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Loader2, ExternalLink } from 'lucide-react'
import { PROVIDER_TEMPLATES, type ProviderTemplate } from '@/lib/providerTemplates'
import { settingsApi } from '@/api/settings'
import { useMutation, useQueryClient } from '@tanstack/react-query'
interface AddProviderDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
export function AddProviderDialog({ open, onOpenChange }: AddProviderDialogProps) {
const [step, setStep] = useState<'select' | 'customize'>('select')
const [selectedTemplate, setSelectedTemplate] = useState<ProviderTemplate | null>(null)
const [providerId, setProviderId] = useState('')
const [providerName, setProviderName] = useState('')
const [baseURL, setBaseURL] = useState('')
const queryClient = useQueryClient()
const addProviderMutation = useMutation({
mutationFn: async () => {
const config = await settingsApi.getDefaultOpenCodeConfig()
const currentProvider = config?.content?.provider || {}
const newProvider = {
npm: selectedTemplate?.npm || '@ai-sdk/openai-compatible',
name: providerName || selectedTemplate?.name,
...(baseURL && {
options: {
baseURL,
},
}),
...(selectedTemplate?.models && {
models: selectedTemplate.models,
}),
}
const updatedConfig = {
...config?.content,
provider: {
...currentProvider,
[providerId]: newProvider,
},
}
await settingsApi.updateOpenCodeConfig(
config?.name || 'default',
{ content: updatedConfig }
)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
queryClient.invalidateQueries({ queryKey: ['opencode-providers'] })
handleClose()
},
})
const handleSelectTemplate = (template: ProviderTemplate) => {
setSelectedTemplate(template)
setProviderId(template.id)
setProviderName(template.name)
setBaseURL(template.options?.baseURL || '')
setStep('customize')
}
const handleAdd = () => {
if (providerId && selectedTemplate) {
addProviderMutation.mutate()
}
}
const handleClose = () => {
setStep('select')
setSelectedTemplate(null)
setProviderId('')
setProviderName('')
setBaseURL('')
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-3xl max-h-[80vh] bg-card border-border overflow-y-auto">
{step === 'select' && (
<>
<DialogHeader>
<DialogTitle>Add Provider</DialogTitle>
<DialogDescription>
Choose a provider template to get started quickly
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 py-4">
{PROVIDER_TEMPLATES.map((template) => (
<Card
key={template.id}
className="cursor-pointer hover:border-blue-500 transition-colors bg-background border-border"
onClick={() => handleSelectTemplate(template)}
>
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex-1">
<CardTitle className="text-base flex items-center gap-2">
{template.name}
{!template.requiresApiKey && (
<Badge variant="secondary" className="text-xs">
Local
</Badge>
)}
</CardTitle>
<CardDescription className="text-sm mt-1">
{template.description}
</CardDescription>
<p className="text-xs text-muted-foreground mt-2">
{template.npm}
</p>
</div>
</div>
</CardHeader>
</Card>
))}
</div>
</>
)}
{step === 'customize' && selectedTemplate && (
<>
<DialogHeader>
<DialogTitle>Configure {selectedTemplate.name}</DialogTitle>
<DialogDescription>
Customize the provider settings before adding
{selectedTemplate.docsUrl && (
<a
href={selectedTemplate.docsUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-blue-500 hover:underline ml-2"
>
View docs <ExternalLink className="h-3 w-3" />
</a>
)}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="providerId">Provider ID</Label>
<Input
id="providerId"
value={providerId}
onChange={(e) => setProviderId(e.target.value)}
placeholder="e.g., anthropic, openai, my-provider"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Unique identifier for this provider (lowercase, no spaces)
</p>
</div>
<div className="space-y-2">
<Label htmlFor="providerName">Display Name</Label>
<Input
id="providerName"
value={providerName}
onChange={(e) => setProviderName(e.target.value)}
placeholder={selectedTemplate.name}
className="bg-background border-border"
/>
</div>
{selectedTemplate.options?.baseURL && (
<div className="space-y-2">
<Label htmlFor="baseURL">Base URL</Label>
<Input
id="baseURL"
value={baseURL}
onChange={(e) => setBaseURL(e.target.value)}
placeholder={selectedTemplate.options.baseURL}
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
API endpoint for this provider
</p>
</div>
)}
<div className="bg-muted p-3 rounded-md">
<p className="text-xs text-muted-foreground">
<strong>NPM Package:</strong> {selectedTemplate.npm}
</p>
{selectedTemplate.models && (
<p className="text-xs text-muted-foreground mt-1">
<strong>Models:</strong> {Object.keys(selectedTemplate.models).length} pre-configured
</p>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setStep('select')}>
Back
</Button>
<Button
onClick={handleAdd}
disabled={!providerId || addProviderMutation.isPending}
>
{addProviderMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Add Provider
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,717 @@
import { useState } from 'react'
import { Plus, Trash2, Edit } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
interface Agent {
prompt?: string
description?: string
mode?: 'subagent' | 'primary' | 'all'
temperature?: number
topP?: number
model?: {
modelID: string
providerID: string
}
tools?: Record<string, boolean>
permission?: {
edit?: 'ask' | 'allow' | 'deny'
bash?: 'ask' | 'allow' | 'deny' | Record<string, 'ask' | 'allow' | 'deny'>
webfetch?: 'ask' | 'allow' | 'deny'
}
disable?: boolean
[key: string]: unknown
}
interface AgentsEditorProps {
agents: Record<string, Agent>
onChange: (agents: Record<string, Agent>) => void
}
export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [editingAgent, setEditingAgent] = useState<{ name: string; agent: Agent } | null>(null)
const [newAgentName, setNewAgentName] = useState('')
const [newAgent, setNewAgent] = useState<Agent>({
prompt: '',
description: '',
mode: 'subagent',
temperature: 0.7,
topP: 1,
disable: false,
tools: {},
permission: {}
})
const createAgent = () => {
if (!newAgentName.trim()) return
const updatedAgents = {
...agents,
[newAgentName]: {
prompt: newAgent.prompt || undefined,
description: newAgent.description || undefined,
mode: newAgent.mode,
temperature: newAgent.temperature,
topP: newAgent.topP,
disable: newAgent.disable
}
}
onChange(updatedAgents)
setNewAgentName('')
setNewAgent({
prompt: '',
description: '',
mode: 'subagent',
temperature: 0.7,
topP: 1,
disable: false,
tools: {},
permission: {}
})
setIsCreateDialogOpen(false)
}
const updateAgent = () => {
if (!editingAgent) return
const updatedAgents = { ...agents }
delete updatedAgents[editingAgent.name]
updatedAgents[editingAgent.name] = editingAgent.agent
onChange(updatedAgents)
setEditingAgent(null)
}
const deleteAgent = (name: string) => {
const updatedAgents = { ...agents }
delete updatedAgents[name]
onChange(updatedAgents)
}
const startEdit = (name: string, agent: Agent) => {
setEditingAgent({ name, agent })
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Agents</h3>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Agent
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create Agent</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className='space-y-1'>
<Label htmlFor="agent-name">Agent Name</Label>
<Input
id="agent-name"
value={newAgentName}
onChange={(e) => setNewAgentName(e.target.value)}
placeholder="my-agent"
/>
</div>
<div className="space-y-1">
<Label htmlFor="agent-description">Description</Label>
<Input
id="agent-description"
value={newAgent.description}
onChange={(e) => setNewAgent({ ...newAgent, description: e.target.value })}
placeholder="Brief description of what the agent does"
/>
</div>
<div className="space-y-1">
<Label htmlFor="agent-prompt">Prompt</Label>
<Textarea
id="agent-prompt"
value={newAgent.prompt}
onChange={(e) => setNewAgent({ ...newAgent, prompt: e.target.value })}
placeholder="The system prompt that defines the agent's behavior and role"
rows={6}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div className="space-y-1">
<Label htmlFor="agent-mode">Mode</Label>
<Select
value={newAgent.mode}
onValueChange={(value: 'subagent' | 'primary' | 'all') =>
setNewAgent({ ...newAgent, mode: value })
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="subagent">Subagent</SelectItem>
<SelectItem value="primary">Primary</SelectItem>
<SelectItem value="all">All</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor="agent-temperature">Temperature</Label>
<Input
id="agent-temperature"
type="number"
min="0"
max="2"
step="0.1"
value={newAgent.temperature}
onChange={(e) => setNewAgent({ ...newAgent, temperature: parseFloat(e.target.value) })}
/>
</div>
<div className="space-y-1">
<Label htmlFor="agent-top-p">Top P</Label>
<Input
id="agent-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={newAgent.topP}
onChange={(e) => setNewAgent({ ...newAgent, topP: parseFloat(e.target.value) })}
/>
</div>
</div>
<div className="space-y-2">
<Label>Model Configuration</Label>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="agent-model-id">Model ID</Label>
<Input
id="agent-model-id"
value={newAgent.model?.modelID || ''}
onChange={(e) => setNewAgent({
...newAgent,
model: { ...newAgent.model, modelID: e.target.value, providerID: newAgent.model?.providerID || '' }
})}
placeholder="claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="agent-provider-id">Provider ID</Label>
<Input
id="agent-provider-id"
value={newAgent.model?.providerID || ''}
onChange={(e) => setNewAgent({
...newAgent,
model: { ...newAgent.model, providerID: e.target.value, modelID: newAgent.model?.modelID || '' }
})}
placeholder="anthropic"
/>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Tools Configuration</Label>
<div className="grid grid-cols-2 gap-2 text-sm">
<div className="flex items-center space-x-2">
<Switch
id="tool-write"
checked={newAgent.tools?.write ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, write: checked }
})}
/>
<Label htmlFor="tool-write">Write</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="tool-edit"
checked={newAgent.tools?.edit ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, edit: checked }
})}
/>
<Label htmlFor="tool-edit">Edit</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="tool-bash"
checked={newAgent.tools?.bash ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, bash: checked }
})}
/>
<Label htmlFor="tool-bash">Bash</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="tool-webfetch"
checked={newAgent.tools?.webfetch ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, webfetch: checked }
})}
/>
<Label htmlFor="tool-webfetch">Web Fetch</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Permissions</Label>
<div className="grid grid-cols-3 gap-2 text-sm">
<div>
<Label className="text-xs">Edit</Label>
<Select
value={newAgent.permission?.edit ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setNewAgent({
...newAgent,
permission: { ...newAgent.permission, edit: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Bash</Label>
<Select
value={typeof newAgent.permission?.bash === 'string' ? newAgent.permission.bash : 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setNewAgent({
...newAgent,
permission: { ...newAgent.permission, bash: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Web Fetch</Label>
<Select
value={newAgent.permission?.webfetch ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setNewAgent({
...newAgent,
permission: { ...newAgent.permission, webfetch: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="agent-disable"
checked={newAgent.disable}
onCheckedChange={(checked) => setNewAgent({ ...newAgent, disable: checked })}
/>
<Label htmlFor="agent-disable">Disable agent</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={createAgent} disabled={!newAgentName.trim()}>
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{Object.keys(agents).length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No agents configured. Add your first agent to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{Object.entries(agents).map(([name, agent]) => (
<Card key={name}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">{name}</CardTitle>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(name, agent)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => deleteAgent(name)}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{agent.description && (
<p className="text-sm text-muted-foreground">{agent.description}</p>
)}
<div className="text-xs text-muted-foreground space-y-1">
<p>Mode: {agent.mode}</p>
{agent.temperature !== undefined && <p>Temperature: {agent.temperature}</p>}
{agent.topP !== undefined && <p>Top P: {agent.topP}</p>}
{agent.model?.modelID && <p>Model: {agent.model.providerID}/{agent.model.modelID}</p>}
{agent.disable && <p>Status: Disabled</p>}
</div>
{agent.prompt && (
<div className="mt-2 p-2 bg-muted rounded text-xs font-mono max-h-20 overflow-y-auto">
{agent.prompt}
</div>
)}
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Edit Dialog */}
<Dialog open={!!editingAgent} onOpenChange={() => setEditingAgent(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Edit Agent</DialogTitle>
</DialogHeader>
{editingAgent && (
<div className="space-y-4">
<div className="space-y-1">
<Label htmlFor="edit-agent-name">Agent Name</Label>
<Input
id="edit-agent-name"
value={editingAgent.name}
disabled
className="bg-muted"
/>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-description">Description</Label>
<Input
id="edit-agent-description"
value={editingAgent.agent.description || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, description: e.target.value }
})}
placeholder="Brief description of what the agent does"
/>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-prompt">Prompt</Label>
<Textarea
id="edit-agent-prompt"
value={editingAgent.agent.prompt || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, prompt: e.target.value }
})}
placeholder="The system prompt that defines the agent's behavior and role"
rows={6}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div className='space-y-1'>
<Label htmlFor="edit-agent-mode">Mode</Label>
<Select
value={editingAgent.agent.mode || 'subagent'}
onValueChange={(value: 'subagent' | 'primary' | 'all') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, mode: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="subagent">Subagent</SelectItem>
<SelectItem value="primary">Primary</SelectItem>
<SelectItem value="all">All</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-temperature">Temperature</Label>
<Input
id="edit-agent-temperature"
type="number"
min="0"
max="2"
step="0.1"
value={editingAgent.agent.temperature ?? 0.7}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, temperature: parseFloat(e.target.value) }
})}
/>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-top-p">Top P</Label>
<Input
id="edit-agent-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={editingAgent.agent.topP ?? 1}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, topP: parseFloat(e.target.value) }
})}
/>
</div>
</div>
<div className="space-y-2">
<Label>Model Configuration</Label>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="edit-agent-model-id">Model ID</Label>
<Input
id="edit-agent-model-id"
value={editingAgent.agent.model?.modelID || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: {
...editingAgent.agent,
model: {
...editingAgent.agent.model,
modelID: e.target.value,
providerID: editingAgent.agent.model?.providerID || ''
}
}
})}
placeholder="claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="edit-agent-provider-id">Provider ID</Label>
<Input
id="edit-agent-provider-id"
value={editingAgent.agent.model?.providerID || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: {
...editingAgent.agent,
model: {
...editingAgent.agent.model,
providerID: e.target.value,
modelID: editingAgent.agent.model?.modelID || ''
}
}
})}
placeholder="anthropic"
/>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Tools Configuration</Label>
<div className="grid grid-cols-2 gap-2 text-sm">
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-write"
checked={editingAgent.agent.tools?.write ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, write: checked } }
})}
/>
<Label htmlFor="edit-tool-write">Write</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-edit"
checked={editingAgent.agent.tools?.edit ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, edit: checked } }
})}
/>
<Label htmlFor="edit-tool-edit">Edit</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-bash"
checked={editingAgent.agent.tools?.bash ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, bash: checked } }
})}
/>
<Label htmlFor="edit-tool-bash">Bash</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-webfetch"
checked={editingAgent.agent.tools?.webfetch ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, webfetch: checked } }
})}
/>
<Label htmlFor="edit-tool-webfetch">Web Fetch</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Permissions</Label>
<div className="grid grid-cols-3 gap-2 text-sm">
<div>
<Label className="text-xs">Edit</Label>
<Select
value={editingAgent.agent.permission?.edit ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, permission: { ...editingAgent.agent.permission, edit: value } }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Bash</Label>
<Select
value={typeof editingAgent.agent.permission?.bash === 'string' ? editingAgent.agent.permission.bash : 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, permission: { ...editingAgent.agent.permission, bash: value } }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Web Fetch</Label>
<Select
value={editingAgent.agent.permission?.webfetch ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, permission: { ...editingAgent.agent.permission, webfetch: value } }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-agent-disable"
checked={editingAgent.agent.disable || false}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, disable: checked }
})}
/>
<Label htmlFor="edit-agent-disable">Disable agent</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setEditingAgent(null)}>
Cancel
</Button>
<Button onClick={updateAgent}>
Update
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,369 @@
import { useState } from 'react'
import { Plus, Trash2, Edit } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
interface Command {
template: string
description?: string
agent?: string
model?: string
subtask?: boolean
topP?: number
}
interface CommandsEditorProps {
commands: Record<string, Command>
onChange: (commands: Record<string, Command>) => void
}
export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [editingCommand, setEditingCommand] = useState<{ name: string; command: Command } | null>(null)
const [newCommandName, setNewCommandName] = useState('')
const [newCommand, setNewCommand] = useState<Command>({
template: '',
description: '',
agent: '',
model: '',
subtask: false,
topP: 1
})
const createCommand = () => {
if (!newCommandName.trim() || !newCommand.template.trim()) return
const updatedCommands = {
...commands,
[newCommandName]: {
template: newCommand.template,
description: newCommand.description,
agent: newCommand.agent || undefined,
model: newCommand.model || undefined,
subtask: newCommand.subtask || undefined,
topP: newCommand.topP || undefined
}
}
onChange(updatedCommands)
setNewCommandName('')
setNewCommand({
template: '',
description: '',
agent: '',
model: '',
subtask: false,
topP: 1
})
setIsCreateDialogOpen(false)
}
const updateCommand = () => {
if (!editingCommand) return
const updatedCommands = { ...commands }
delete updatedCommands[editingCommand.name]
updatedCommands[editingCommand.name] = {
template: editingCommand.command.template,
description: editingCommand.command.description,
agent: editingCommand.command.agent || undefined,
model: editingCommand.command.model || undefined,
subtask: editingCommand.command.subtask || undefined,
topP: editingCommand.command.topP || undefined
}
onChange(updatedCommands)
setEditingCommand(null)
}
const deleteCommand = (name: string) => {
const updatedCommands = { ...commands }
delete updatedCommands[name]
onChange(updatedCommands)
}
const startEdit = (name: string, command: Command) => {
setEditingCommand({ name, command })
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Commands</h3>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Command
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create Command</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="command-name">Command Name</Label>
<Input
id="command-name"
value={newCommandName}
onChange={(e) => setNewCommandName(e.target.value)}
placeholder="my-command"
/>
</div>
<div>
<Label htmlFor="command-description">Description</Label>
<Input
id="command-description"
value={newCommand.description}
onChange={(e) => setNewCommand({ ...newCommand, description: e.target.value })}
placeholder="Brief description of what the command does"
/>
</div>
<div>
<Label htmlFor="command-template">Template</Label>
<Textarea
id="command-template"
value={newCommand.template}
onChange={(e) => setNewCommand({ ...newCommand, template: e.target.value })}
placeholder="The prompt template that will be sent to the LLM. Use $ARGUMENTS or $1, $2, etc. for parameters."
rows={8}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div>
<Label htmlFor="command-agent">Agent (optional)</Label>
<Input
id="command-agent"
value={newCommand.agent}
onChange={(e) => setNewCommand({ ...newCommand, agent: e.target.value })}
placeholder="build"
/>
</div>
<div>
<Label htmlFor="command-model">Model (optional)</Label>
<Input
id="command-model"
value={newCommand.model}
onChange={(e) => setNewCommand({ ...newCommand, model: e.target.value })}
placeholder="anthropic/claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="command-top-p">Top P (optional)</Label>
<Input
id="command-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={newCommand.topP}
onChange={(e) => setNewCommand({ ...newCommand, topP: parseFloat(e.target.value) })}
/>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="command-subtask"
checked={newCommand.subtask}
onCheckedChange={(checked) => setNewCommand({ ...newCommand, subtask: checked })}
/>
<Label htmlFor="command-subtask">Run as subtask</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={createCommand} disabled={!newCommandName.trim() || !newCommand.template.trim()}>
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{Object.keys(commands).length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No commands configured. Add your first command to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{Object.entries(commands).map(([name, command]) => (
<Card key={name}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">/{name}</CardTitle>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(name, command)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => deleteCommand(name)}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{command.description && (
<p className="text-sm text-muted-foreground">{command.description}</p>
)}
<div className="text-xs text-muted-foreground space-y-1">
{command.agent && <p>Agent: {command.agent}</p>}
{command.model && <p>Model: {command.model}</p>}
{command.topP !== undefined && <p>Top P: {command.topP}</p>}
{command.subtask && <p>Subtask: Yes</p>}
</div>
<div className="mt-2 p-2 bg-muted rounded text-xs font-mono max-h-20 overflow-y-auto">
{command.template}
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Edit Dialog */}
<Dialog open={!!editingCommand} onOpenChange={() => setEditingCommand(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Edit Command</DialogTitle>
</DialogHeader>
{editingCommand && (
<div className="space-y-4">
<div>
<Label htmlFor="edit-command-name">Command Name</Label>
<Input
id="edit-command-name"
value={editingCommand.name}
disabled
className="bg-muted"
/>
</div>
<div>
<Label htmlFor="edit-command-description">Description</Label>
<Input
id="edit-command-description"
value={editingCommand.command.description || ''}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, description: e.target.value }
})}
placeholder="Brief description of what the command does"
/>
</div>
<div>
<Label htmlFor="edit-command-template">Template</Label>
<Textarea
id="edit-command-template"
value={editingCommand.command.template}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, template: e.target.value }
})}
placeholder="The prompt template that will be sent to the LLM. Use $ARGUMENTS or $1, $2, etc. for parameters."
rows={8}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div>
<Label htmlFor="edit-command-agent">Agent (optional)</Label>
<Input
id="edit-command-agent"
value={editingCommand.command.agent || ''}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, agent: e.target.value }
})}
placeholder="build"
/>
</div>
<div>
<Label htmlFor="edit-command-model">Model (optional)</Label>
<Input
id="edit-command-model"
value={editingCommand.command.model || ''}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, model: e.target.value }
})}
placeholder="anthropic/claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="edit-command-top-p">Top P (optional)</Label>
<Input
id="edit-command-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={editingCommand.command.topP ?? 1}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, topP: parseFloat(e.target.value) }
})}
/>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-command-subtask"
checked={editingCommand.command.subtask || false}
onCheckedChange={(checked) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, subtask: checked }
})}
/>
<Label htmlFor="edit-command-subtask">Run as subtask</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setEditingCommand(null)}>
Cancel
</Button>
<Button onClick={updateCommand}>
Update
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,129 @@
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">General Preferences</h2>
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="theme">Theme</Label>
<Select
value={preferences?.theme || 'dark'}
onValueChange={(value) => updateSettings({ theme: value as 'dark' | 'light' | 'system' })}
>
<SelectTrigger id="theme">
<SelectValue placeholder="Select a theme" />
</SelectTrigger>
<SelectContent>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="system">System</SelectItem>
</SelectContent>
</Select>
<p className="text-sm text-muted-foreground">
Choose your preferred color scheme
</p>
</div>
<div className="space-y-2">
<Label htmlFor="mode">Mode</Label>
<Select
value={preferences?.mode || 'build'}
onValueChange={(value) => updateSettings({ mode: value as 'plan' | 'build' })}
>
<SelectTrigger id="mode">
<SelectValue placeholder="Select a mode" />
</SelectTrigger>
<SelectContent>
<SelectItem value="plan">Plan</SelectItem>
<SelectItem value="build">Build</SelectItem>
</SelectContent>
</Select>
<p className="text-sm text-muted-foreground">
Plan mode: Read-only. Build mode: File changes enabled
</p>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="autoScroll" className="text-base">Auto-scroll</Label>
<p className="text-sm text-muted-foreground">
Automatically scroll to bottom when new messages arrive
</p>
</div>
<Switch
id="autoScroll"
checked={preferences?.autoScroll ?? true}
onCheckedChange={(checked) => updateSettings({ autoScroll: checked })}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="showReasoning" className="text-base">Show reasoning</Label>
<p className="text-sm text-muted-foreground">
Display model reasoning and thought process
</p>
</div>
<Switch
id="showReasoning"
checked={preferences?.showReasoning ?? false}
onCheckedChange={(checked) => updateSettings({ showReasoning: checked })}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="expandToolCalls" className="text-base">Expand tool calls</Label>
<p className="text-sm text-muted-foreground">
Automatically expand tool call details by default
</p>
</div>
<Switch
id="expandToolCalls"
checked={preferences?.expandToolCalls ?? false}
onCheckedChange={(checked) => updateSettings({ expandToolCalls: checked })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="gitToken">GitHub Personal Access Token</Label>
<Input
id="gitToken"
type="password"
placeholder="ghp_..."
value={preferences?.gitToken || ''}
onChange={(e) => updateSettings({ gitToken: e.target.value })}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
<p className="text-sm text-muted-foreground">
Required for cloning private repos. Get one at github.com/settings/tokens
</p>
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,158 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { DEFAULT_KEYBOARD_SHORTCUTS } from '@/api/types/settings'
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
const normalizeShortcut = (shortcut: string): string => {
return shortcut.replace(/Cmd/g, CMD_KEY)
}
export function KeyboardShortcuts() {
const { preferences, isLoading, updateSettings } = useSettings()
const [recordingKey, setRecordingKey] = useState<string | null>(null)
const [tempShortcuts, setTempShortcuts] = useState<Record<string, string>>({})
const [currentKeys, setCurrentKeys] = useState<string>('')
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
const shortcuts = { ...DEFAULT_KEYBOARD_SHORTCUTS, ...preferences?.keyboardShortcuts, ...tempShortcuts }
const handleKeyDown = (e: KeyboardEvent, action: string) => {
e.preventDefault()
const keys = []
if (e.ctrlKey) keys.push('Ctrl')
if (e.metaKey) keys.push('Cmd')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
// Get the actual key pressed (excluding modifier keys)
const mainKey = e.key
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
// Handle special keys
let displayKey = mainKey
if (mainKey === ' ') displayKey = 'Space'
else if (mainKey === 'ArrowUp') displayKey = 'Up'
else if (mainKey === 'ArrowDown') displayKey = 'Down'
else if (mainKey === 'ArrowLeft') displayKey = 'Left'
else if (mainKey === 'ArrowRight') displayKey = 'Right'
else if (mainKey === 'Enter') displayKey = 'Return'
else if (mainKey === 'Escape') displayKey = 'Esc'
else if (mainKey === 'Tab') displayKey = 'Tab'
else if (mainKey === 'Backspace') displayKey = 'Backspace'
else if (mainKey === 'Delete') displayKey = 'Delete'
else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
keys.push(displayKey)
// Only complete recording if we have a non-modifier key
if (keys.length > 0) {
const shortcut = keys.join('+')
setTempShortcuts(prev => ({ ...prev, [action]: shortcut }))
setRecordingKey(null)
setCurrentKeys('')
updateSettings({
keyboardShortcuts: { ...shortcuts, [action]: shortcut }
})
}
} else {
// Show current modifier keys being held
setCurrentKeys(keys.join('+'))
}
}
const handleKeyUp = (e: KeyboardEvent) => {
// Clear current keys display when modifiers are released
if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) {
setCurrentKeys('')
}
}
const startRecording = (action: string) => {
setRecordingKey(action)
setCurrentKeys('')
}
const stopRecording = () => {
setRecordingKey(null)
setCurrentKeys('')
}
useEffect(() => {
if (recordingKey) {
const handleGlobalKeyDown = (e: KeyboardEvent) => {
handleKeyDown(e, recordingKey)
}
const handleGlobalKeyUp = (e: KeyboardEvent) => {
handleKeyUp(e)
}
document.addEventListener('keydown', handleGlobalKeyDown)
document.addEventListener('keyup', handleGlobalKeyUp)
return () => {
document.removeEventListener('keydown', handleGlobalKeyDown)
document.removeEventListener('keyup', handleGlobalKeyUp)
}
}
}, [recordingKey])
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Keyboard Shortcuts</h2>
<div className="space-y-4">
{Object.entries(shortcuts).map(([action, keys]) => (
<div key={action} className="flex items-center justify-between py-3 border-b border-border last:border-0">
<div className="space-y-1">
<p className="text-foreground font-medium capitalize">
{action.replace(/([A-Z])/g, ' $1').trim()}
</p>
</div>
{recordingKey === action ? (
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
onBlur={stopRecording}
readOnly
/>
<button
onClick={stopRecording}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
) : (
<button
onClick={() => startRecording(action)}
className="px-3 py-1.5 bg-accent border border-border hover:border-border rounded text-sm text-foreground font-mono transition-colors"
>
{normalizeShortcut(keys)}
</button>
)}
</div>
))}
</div>
<p className="mt-6 text-sm text-muted-foreground">
Click on any shortcut to record a new key combination
</p>
</div>
)
}
@@ -0,0 +1,124 @@
import { useState, useRef, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Loader2 } from 'lucide-react'
import type { OpenCodeConfig } from '@/api/types/settings'
interface OpenCodeConfigEditorProps {
config: OpenCodeConfig | null
isOpen: boolean
onClose: () => void
onUpdate: (content: Record<string, unknown>) => Promise<void>
isUpdating: boolean
}
export function OpenCodeConfigEditor({
config,
isOpen,
onClose,
onUpdate,
isUpdating
}: OpenCodeConfigEditorProps) {
const [editConfigContent, setEditConfigContent] = useState('')
const [editError, setEditError] = useState('')
const [editErrorLine, setEditErrorLine] = useState<number | null>(null)
const editTextareaRef = useRef<HTMLTextAreaElement>(null)
useEffect(() => {
if (config && isOpen) {
setEditConfigContent(JSON.stringify(config.content, null, 2))
setEditError('')
setEditErrorLine(null)
}
}, [config, isOpen])
useEffect(() => {
if (isOpen && editTextareaRef.current) {
editTextareaRef.current.focus()
}
}, [isOpen])
const updateConfig = async () => {
if (!config) return
try {
const parsedContent = JSON.parse(editConfigContent)
const forbiddenFields = ['id', 'createdAt', 'updatedAt']
const foundForbidden = forbiddenFields.filter(field => field in parsedContent)
if (foundForbidden.length > 0) {
throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`)
}
await onUpdate(parsedContent)
onClose()
} catch (error) {
if (error instanceof SyntaxError) {
const match = error.message.match(/line (\d+)/i)
const line = match ? parseInt(match[1]) : null
setEditErrorLine(line)
setEditError('Invalid JSON format')
} else {
setEditError(error instanceof Error ? error.message : 'Failed to update config')
}
}
}
if (!isOpen || !config) return null
return (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<div className="relative w-full max-w-6xl h-[90vh] bg-background border rounded-lg shadow-lg">
<div className="flex flex-col h-full">
<div className="flex items-center justify-between p-6 border-b">
<div>
<h2 className="text-lg font-semibold">Edit Config: {config.name}</h2>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button
onClick={updateConfig}
disabled={isUpdating || !editConfigContent.trim()}
>
{isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Update
</Button>
</div>
</div>
<div className="flex-1 p-6 overflow-hidden">
<div className="h-full flex flex-col">
<Label htmlFor="edit-config-content" className="mb-2">
Config Content (JSON)
</Label>
<Textarea
id="edit-config-content"
ref={editTextareaRef}
value={editConfigContent}
onChange={(e) => {
setEditConfigContent(e.target.value)
setEditError('')
setEditErrorLine(null)
}}
className="flex-1 font-mono text-sm resize-none"
/>
{editError && (
<p className="text-sm text-red-500 mt-2">
{editError}
{editErrorLine && (
<span className="ml-2 text-xs">(Line {editErrorLine})</span>
)}
</p>
)}
</div>
</div>
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,469 @@
import { useState, useEffect, useRef } from 'react'
import { Loader2, Plus, Trash2, Edit, Star, StarOff, Download } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
import { CommandsEditor } from './CommandsEditor'
import { AgentsEditor } from './AgentsEditor'
import { settingsApi } from '@/api/settings'
interface OpenCodeConfig {
id: number
name: string
content: Record<string, unknown>
isDefault: boolean
createdAt: number
updatedAt: number
}
export function OpenCodeConfigManager() {
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isUpdating, setIsUpdating] = useState(false)
const [editingConfig, setEditingConfig] = useState<OpenCodeConfig | null>(null)
const [selectedConfig, setSelectedConfig] = useState<OpenCodeConfig | null>(null)
const [newConfigName, setNewConfigName] = useState('')
const [newConfigContent, setNewConfigContent] = useState('')
const [newConfigIsDefault, setNewConfigIsDefault] = useState(false)
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
const [createError, setCreateError] = useState('')
const [createErrorLine, setCreateErrorLine] = useState<number | null>(null)
const createTextareaRef = useRef<HTMLTextAreaElement>(null)
const fetchConfigs = async () => {
try {
setIsLoading(true)
const data = await settingsApi.getOpenCodeConfigs()
setConfigs(data.configs)
} catch (error) {
console.error('Failed to fetch configs:', error)
} finally {
setIsLoading(false)
}
}
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>) => {
try {
setIsUpdating(true)
await settingsApi.updateOpenCodeConfig(configName, { content: newContent })
// Update the local state
setConfigs(prev => prev.map(config =>
config.name === configName
? { ...config, content: newContent, updatedAt: Date.now() }
: config
))
// Update selected config if it's the one being edited
if (selectedConfig && selectedConfig.name === configName) {
setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: Date.now() })
}
} catch (error) {
console.error('Failed to update config:', error)
} finally {
setIsUpdating(false)
}
}
useEffect(() => {
fetchConfigs()
}, [])
const createConfig = async () => {
if (!newConfigName.trim() || !newConfigContent.trim()) return
try {
setIsUpdating(true)
setCreateError('')
const content = JSON.parse(newConfigContent)
const forbiddenFields = ['id', 'createdAt', 'updatedAt']
const foundForbidden = forbiddenFields.filter(field => field in content)
if (foundForbidden.length > 0) {
throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`)
}
await settingsApi.createOpenCodeConfig({
name: newConfigName.trim(),
content,
isDefault: newConfigIsDefault,
})
setNewConfigName('')
setNewConfigContent('')
setNewConfigIsDefault(false)
setIsCreateDialogOpen(false)
fetchConfigs()
} catch (error) {
if (error instanceof SyntaxError) {
const match = error.message.match(/line (\d+)/i)
const line = match ? parseInt(match[1]) : null
setCreateErrorLine(line)
setCreateError(`JSON Error: ${error.message}`)
if (line && createTextareaRef.current) {
highlightErrorLine(createTextareaRef.current, line)
}
} else if (error instanceof Error) {
setCreateError(error.message)
setCreateErrorLine(null)
} else {
setCreateError('Failed to create configuration')
setCreateErrorLine(null)
}
console.error('Failed to create config:', error)
} finally {
setIsUpdating(false)
}
}
const deleteConfig = async (config: OpenCodeConfig) => {
try {
setIsUpdating(true)
await settingsApi.deleteOpenCodeConfig(config.name)
setDeleteConfirmConfig(null)
fetchConfigs()
} catch (error) {
console.error('Failed to delete config:', error)
} finally {
setIsUpdating(false)
}
}
const setDefaultConfig = async (config: OpenCodeConfig) => {
try {
setIsUpdating(true)
await settingsApi.setDefaultOpenCodeConfig(config.name)
fetchConfigs()
} catch (error) {
console.error('Failed to set default config:', error)
} finally {
setIsUpdating(false)
}
}
const uploadConfig = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
const content = e.target?.result as string
try {
JSON.parse(content)
setNewConfigContent(content)
setNewConfigName(file.name.replace('.json', '').replace('.jsonc', ''))
} catch {
window.alert('Invalid JSON file')
}
}
reader.readAsText(file)
}
const downloadConfig = (config: OpenCodeConfig) => {
const blob = new Blob([JSON.stringify(config.content, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${config.name}.json`
a.click()
URL.revokeObjectURL(url)
}
const highlightErrorLine = (textarea: HTMLTextAreaElement, line: number) => {
const lines = textarea.value.split('\n')
if (line > lines.length) return
let charIndex = 0
for (let i = 0; i < line - 1; i++) {
charIndex += lines[i].length + 1
}
textarea.focus()
textarea.setSelectionRange(charIndex, charIndex + lines[line - 1].length)
}
const startEdit = (config: OpenCodeConfig) => {
setEditingConfig(config)
setIsEditDialogOpen(true)
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-6 overflow-y-auto">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-foreground">OpenCode Configurations</h2>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
New Config
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create OpenCode Config</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="config-name">Config Name</Label>
<Input
id="config-name"
value={newConfigName}
onChange={(e) => setNewConfigName(e.target.value)}
placeholder="my-config"
/>
</div>
<div>
<Label htmlFor="config-upload">Upload JSON File</Label>
<Input
id="config-upload"
type="file"
accept=".json,.jsonc"
onChange={uploadConfig}
/>
</div>
<div>
<Label htmlFor="config-content">Config Content (JSON)</Label>
<Textarea
id="config-content"
ref={createTextareaRef}
value={newConfigContent}
onChange={(e) => {
setNewConfigContent(e.target.value)
setCreateError('')
setCreateErrorLine(null)
}}
placeholder='{"$schema": "https://opencode.ai/config.json", "theme": "dark"}'
rows={20}
className="font-mono text-sm"
/>
{createError && (
<p className="text-sm text-red-500 mt-2">
{createError}
{createErrorLine && (
<span className="ml-2 text-xs">(Line {createErrorLine})</span>
)}
</p>
)}
</div>
<div className="flex items-center space-x-2">
<Switch
id="config-default"
checked={newConfigIsDefault}
onCheckedChange={setNewConfigIsDefault}
/>
<Label htmlFor="config-default">Set as default configuration</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={createConfig} disabled={isUpdating || !newConfigName.trim() || !newConfigContent.trim()}>
{isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{configs.length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No OpenCode configurations found. Create your first config to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{configs.map((config) => (
<Card key={config.id}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<CardTitle className="text-base">{config.name}</CardTitle>
{config.isDefault && (
<Badge variant="default" className="text-xs">
<Star className="h-3 w-3 mr-1" />
Default
</Badge>
)}
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => downloadConfig(config)}
>
<Download className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(config)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDefaultConfig(config)}
disabled={config.isDefault || isUpdating}
>
{config.isDefault ? (
<StarOff className="h-4 w-4" />
) : (
<Star className="h-4 w-4" />
)}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDeleteConfirmConfig(config)}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground">
<p>Updated: {new Date(config.updatedAt).toLocaleString()}</p>
<p>Created: {new Date(config.createdAt).toLocaleString()}</p>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Edit Dialog */}
<OpenCodeConfigEditor
config={editingConfig}
isOpen={isEditDialogOpen}
onClose={() => setIsEditDialogOpen(false)}
onUpdate={async (content) => {
if (!editingConfig) return
await settingsApi.updateOpenCodeConfig(editingConfig.name, { content })
await fetchConfigs()
}}
isUpdating={isUpdating}
/>
{/* Commands and Agents Section */}
<div className="mt-8 space-y-6">
<div className="border-t border-border pt-6">
<h3 className="text-lg font-semibold mb-4">Configure Commands & Agents</h3>
<p className="text-sm text-muted-foreground mb-6">
Add custom commands and agents to your OpenCode configurations. Select a configuration below to edit its commands and agents.
</p>
{configs.length > 0 && (
<div className="space-y-6">
<div className='px-1'>
<Label className="text-base font-medium">Select Configuration to Edit</Label>
<Select
onValueChange={(value) => {
const config = configs.find(c => c.name === value)
setSelectedConfig(config || null)
}}
value={selectedConfig?.name || ""}
>
<SelectTrigger className="mt-2 w-full">
<SelectValue placeholder="Select a configuration..." />
</SelectTrigger>
<SelectContent>
{configs.map(config => (
<SelectItem key={config.id} value={config.name}>
{config.name} {config.isDefault && '(Default)'}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-8 pb-20">
{selectedConfig ? (
<>
<div className="bg-card border border-border rounded-lg p-6">
<h4 className="text-md font-medium mb-4">Editing: {selectedConfig.name}</h4>
<div className="max-h-[60vh] overflow-y-auto">
<CommandsEditor
commands={(selectedConfig.content.command as Record<string, any>) || {}}
onChange={(commands) => {
const updatedContent = {
...selectedConfig.content,
command: commands
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
</div>
</div>
<div className="bg-card border border-border rounded-lg p-6">
<div className="max-h-[60vh] overflow-y-auto">
<AgentsEditor
agents={(selectedConfig.content.agent as Record<string, any>) || {}}
onChange={(agents) => {
const updatedContent = {
...selectedConfig.content,
agent: agents
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
</div>
</div>
</>
) : (
<div className="bg-card border border-border rounded-lg p-6">
<p className="text-muted-foreground text-center">Select a configuration to edit its commands and agents.</p>
</div>
)}
</div>
</div>
)}
</div>
</div>
{/* Delete Confirmation Dialog */}
<DeleteDialog
open={!!deleteConfirmConfig}
onOpenChange={() => setDeleteConfirmConfig(null)}
onConfirm={() => deleteConfirmConfig && deleteConfig(deleteConfirmConfig)}
onCancel={() => setDeleteConfirmConfig(null)}
title="Delete Configuration"
description="Any repositories using this configuration will continue to work but won't receive updates."
itemName={deleteConfirmConfig?.name}
isDeleting={isUpdating}
/>
</div>
)
}
@@ -0,0 +1,207 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Loader2, Key, Check, X, Plus } from 'lucide-react'
import { providerCredentialsApi } from '@/api/providers'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { AddProviderDialog } from './AddProviderDialog'
import { useProviders } from '@/hooks/useProviders'
export function ProviderSettings() {
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
const [apiKey, setApiKey] = useState('')
const [showApiKey, setShowApiKey] = useState(false)
const [addDialogOpen, setAddDialogOpen] = useState(false)
const queryClient = useQueryClient()
const { data: providers, isLoading: providersLoading } = useProviders()
const { data: credentialsList, isLoading: credentialsLoading } = useQuery({
queryKey: ['provider-credentials'],
queryFn: () => providerCredentialsApi.list(),
})
const setCredentialMutation = useMutation({
mutationFn: ({ providerId, apiKey }: { providerId: string; apiKey: string }) =>
providerCredentialsApi.set(providerId, apiKey),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
setSelectedProvider(null)
setApiKey('')
},
})
const deleteCredentialMutation = useMutation({
mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
},
})
const handleSetCredential = () => {
if (selectedProvider && apiKey) {
setCredentialMutation.mutate({ providerId: selectedProvider, apiKey })
}
}
const handleDeleteCredential = (providerId: string) => {
if (confirm(`Remove credentials for ${providerId}?`)) {
deleteCredentialMutation.mutate(providerId)
}
}
const hasCredentials = (providerId: string) => {
return credentialsList?.includes(providerId) || false
}
if (providersLoading || credentialsLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-4">
<div className="flex items-start justify-between">
<div>
<h2 className="text-lg font-semibold text-foreground mb-2">Provider Credentials</h2>
<p className="text-sm text-muted-foreground">
Manage API keys for AI providers. Keys are stored securely in your workspace.
</p>
</div>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
Add Provider
</Button>
</div>
{!providers || providers.length === 0 ? (
<Card className="bg-card border-border">
<CardContent className="pt-6">
<p className="text-sm text-muted-foreground text-center">
No providers configured. Add providers in your OpenCode config.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{providers.map((provider) => {
const hasKey = hasCredentials(provider.id)
const modelCount = Object.keys(provider.models || {}).length
return (
<Card key={provider.id} className="bg-card border-border">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex-1">
<CardTitle className="text-base flex items-center gap-2">
{provider.name || provider.id}
{hasKey ? (
<Badge variant="default" className="bg-green-600 hover:bg-green-700">
<Check className="h-3 w-3 mr-1" />
Configured
</Badge>
) : (
<Badge variant="secondary">
<X className="h-3 w-3 mr-1" />
No Key
</Badge>
)}
</CardTitle>
<CardDescription className="mt-1">
{provider.npm && <span className="text-xs">Package: {provider.npm}</span>}
{provider.options?.baseURL && (
<span className="text-xs block">{provider.options.baseURL}</span>
)}
{modelCount > 0 && (
<span className="text-xs block">{modelCount} model{modelCount !== 1 ? 's' : ''}</span>
)}
</CardDescription>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant={hasKey ? 'outline' : 'default'}
onClick={() => setSelectedProvider(provider.id)}
>
<Key className="h-4 w-4 mr-1" />
{hasKey ? 'Update' : 'Add'} Key
</Button>
{hasKey && (
<Button
size="sm"
variant="destructive"
onClick={() => handleDeleteCredential(provider.id)}
disabled={deleteCredentialMutation.isPending}
>
Remove
</Button>
)}
</div>
</div>
</CardHeader>
</Card>
)
})}
</div>
)}
<Dialog open={!!selectedProvider} onOpenChange={(open) => !open && setSelectedProvider(null)}>
<DialogContent className="bg-card border-border">
<DialogHeader>
<DialogTitle>Set API Key for {selectedProvider}</DialogTitle>
<DialogDescription>
Enter your API key. It will be stored securely in your workspace.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="apiKey">API Key</Label>
<div className="relative">
<Input
id="apiKey"
type={showApiKey ? 'text' : 'password'}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="sk-..."
className="bg-background border-border pr-20"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-1 top-1/2 -translate-y-1/2 h-7"
onClick={() => setShowApiKey(!showApiKey)}
>
{showApiKey ? 'Hide' : 'Show'}
</Button>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setSelectedProvider(null)}>
Cancel
</Button>
<Button
onClick={handleSetCredential}
disabled={!apiKey || setCredentialMutation.isPending}
>
{setCredentialMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<AddProviderDialog open={addDialogOpen} onOpenChange={setAddDialogOpen} />
</div>
)
}
@@ -0,0 +1,131 @@
import { useState } from 'react'
import { GeneralSettings } from '@/components/settings/GeneralSettings'
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key } from 'lucide-react'
import { Button } from '@/components/ui/button'
interface SettingsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
type SettingsView = 'menu' | 'general' | 'shortcuts' | 'opencode' | 'providers'
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const [mobileView, setMobileView] = useState<SettingsView>('menu')
const menuItems = [
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
{ id: 'opencode', icon: Code, label: 'OpenCode Config', description: 'Manage OpenCode configurations, commands, and agents' },
{ id: 'providers', icon: Key, label: 'Providers', description: 'Manage AI provider API keys' },
]
const handleClose = () => {
setMobileView('menu')
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-4xl w-full h-[100vh] sm:h-auto sm:w-[95vw] sm:max-h-[90vh] bg-gradient-to-br from-background via-background to-background border-border p-0 sm:rounded-lg overflow-hidden !flex !flex-col left-0 top-0 translate-x-0 translate-y-0 max-h-[100vh] sm:left-[50%] sm:top-[50%] sm:translate-x-[-50%] sm:translate-y-[-50%] [&>button:last-child]:hidden">
<div className="hidden sm:flex sm:flex-col sm:h-[90vh]">
<div className="sticky top-0 z-10 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-6 py-4 flex-shrink-0">
<h2 className="text-2xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
Settings
</h2>
</div>
<Tabs defaultValue="general" className="w-full flex flex-col flex-1 min-h-0">
<div className="px-6 pt-6 pb-4 flex-shrink-0">
<TabsList className="grid w-full grid-cols-4 bg-card border border-border p-1">
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
General
</TabsTrigger>
<TabsTrigger value="shortcuts" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Shortcuts
</TabsTrigger>
<TabsTrigger value="opencode" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
OpenCode
</TabsTrigger>
<TabsTrigger value="providers" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Providers
</TabsTrigger>
</TabsList>
</div>
<div className="flex-1 overflow-y-auto">
<div className="px-6 pb-6">
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
<TabsContent value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
<TabsContent value="providers" className="mt-0"><ProviderSettings /></TabsContent>
</div>
</div>
</Tabs>
</div>
<div className="sm:hidden flex flex-col h-full min-h-0">
<div className="flex-shrink-0 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-2 flex-1">
{mobileView !== 'menu' && (
<Button
variant="ghost"
size="icon"
onClick={() => setMobileView('menu')}
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px]"
>
<ChevronLeft className="w-6 h-6" />
</Button>
)}
<h2 className="text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
{mobileView === 'menu' ? 'Settings' : menuItems.find(item => item.id === mobileView)?.label}
</h2>
</div>
<Button
variant="ghost"
size="icon"
onClick={handleClose}
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px] flex-shrink-0"
>
<X className="w-6 h-6" />
</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-32">
{mobileView === 'menu' && (
<div className="space-y-3">
{menuItems.map((item) => (
<button
key={item.id}
onClick={() => setMobileView(item.id as SettingsView)}
className="w-full bg-gradient-to-br from-card to-card-hover border border-border rounded-xl p-4 hover:border-border transition-all duration-200 text-left"
>
<div className="flex items-center gap-4">
<div className="p-3 bg-accent rounded-lg">
<item.icon className="w-6 h-6 text-blue-400" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-foreground mb-1">{item.label}</h3>
<p className="text-sm text-muted-foreground">{item.description}</p>
</div>
</div>
</button>
))}
</div>
)}
{mobileView === 'general' && <GeneralSettings />}
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
{mobileView === 'opencode' && <OpenCodeConfigManager />}
{mobileView === 'providers' && <ProviderSettings />}
</div>
</div>
</DialogContent>
</Dialog>
)
}
+59
View File
@@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }
@@ -0,0 +1,20 @@
import { useNavigate } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
interface BackButtonProps {
to?: string;
className?: string;
}
export function BackButton({ to = "/", className = "" }: BackButtonProps) {
const navigate = useNavigate();
return (
<button
onClick={() => navigate(to)}
className={`text-zinc-400 hover:text-zinc-100 transition-all duration-200 hover:scale-105 text-sm md:text-md border border-zinc-700 rounded-md px-2 py-1 hover ${className}`}
>
<ArrowLeft className="w-4 h-4" />
</button>
);
}
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more