36 Commits

Author SHA1 Message Date
viper151
ba077fdf62 Update package.json 2025-07-13 17:30:59 +02:00
simos
6170f97216 Fixes to json 2025-07-13 15:30:22 +00:00
simos
6c64ea7552 feat: Ability to add and control user level MCP Servers 2025-07-13 15:25:45 +00:00
viper151
23f5fc357b Update package.json 2025-07-13 16:00:56 +02:00
viper151
2d63b18c69 Update index.js 2025-07-13 15:22:34 +02:00
simos
9f65756e2c Removing some console logs 2025-07-13 12:46:28 +00:00
simos
db8c086f22 Merge branch 'main' of https://github.com/siteboon/claudecodeui 2025-07-13 12:46:10 +00:00
simos
111311eac5 Fixes on Dark Theme 2025-07-13 12:05:32 +00:00
viper151
6934581488 Update README.md 2025-07-13 12:33:03 +02:00
simos
c0f30afb23 Enhanced UX on GitPanel 2025-07-13 09:42:10 +00:00
simos
aa1df3c9c8 Fixes on chat interface file selection 2025-07-13 09:35:16 +00:00
simos
ed920bb73b Introducing push on server 2025-07-13 05:14:01 +00:00
simos
e72be46733 Fixes 2025-07-13 05:11:18 +00:00
simos
a5ddef58df Introducing push on git panel 2025-07-13 05:10:56 +00:00
simos
02cc0257ae UX enhancements on gitpanel and Shell to make them more mobile friendly 2025-07-13 05:06:31 +00:00
simos
24282ababe Merge branch 'main' of https://github.com/siteboon/claudecodeui 2025-07-13 04:37:15 +00:00
simos
71ac848d60 Added animations to git panel 2025-07-12 22:04:08 +00:00
simos
7329f89c96 Added pull and fetch on git panel
Made UX enhancements
2025-07-12 22:02:59 +00:00
simos
00acc57161 Formatting properly exit_plan_mose 2025-07-12 21:43:47 +00:00
viper151
9ac604de41 Update README.md 2025-07-12 22:29:02 +02:00
viper151
046f270a11 Update package.json 2025-07-12 21:34:56 +02:00
lvalics
7feeebc2ae feat: Add image upload functionality with drag & drop, clipboard paste, and file picker (#46)
- Add drag & drop support for images with visual feedback
- Implement clipboard paste for images (Ctrl+V/Cmd+V)
- Add image upload button in chat interface
- Support multiple formats: PNG, JPG, JPEG, GIF, WebP, SVG
- Max 5 images per message, 5MB per image
- Add image preview with remove functionality
- Display images in chat message bubbles

Technical implementation:
- Frontend: Add react-dropzone for drag & drop
- Frontend: Create ImageAttachment component for previews
- Backend: Add multer for file upload handling
- Backend: Create /api/projects/:projectName/upload-images endpoint
- Backend: Convert images to base64 and save to temp files
- Claude CLI: Pass image paths as arguments
- Add automatic cleanup of temporary files
- Fix JWT auth to use correct token name
- Fix UI overlap with proper padding adjustments
- Remove non-essential console.logs for production

Security:
- Validate file types and sizes
- Sanitize filenames
- User-specific temp directories
- Proper JWT authentication

Infrastructure:
- Add .tmp/ to .gitignore
- Create comprehensive CHANGELOG.md
- Update package.json with new dependencies

Co-authored-by: viper151 <simosmik@gmail.com>
2025-07-12 21:30:55 +02:00
simos
ad0bcba117 fix: Enhance project sorting in sidebar
- Fixed combined sorting for projects: starred projects first, followed by sorting by last activity date or display name.
- Added helper functions to retrieve all sessions for a project and determine the last activity date.
- Improved sorting logic to accommodate user-defined display names and recent activity.
2025-07-12 19:13:26 +00:00
lvalics
a56e06385d feat: Add project search filter to sidebar
- Added search input below header to filter projects by name
- Search works on both display name and project path
- Clear button (X) appears when search is active
- Shows "No matching projects" message when filter returns no results
- Search box only visible when projects exist
- Case-insensitive search implementation
2025-07-12 20:57:09 +02:00
viper151
5ec51dacc3 Added stared project and ux enahncements
Added stared project and ux enahncements
2025-07-12 20:41:46 +02:00
viper151
a79028a124 Merge branch 'main' into feature/project-starring 2025-07-12 20:41:08 +02:00
viper151
2435d12a0b Merge pull request #37 from lvalics/feature/file-permissions 2025-07-12 20:25:11 +02:00
viper151
54d5583bc2 Merge branch 'main' into feature/file-permissions 2025-07-12 13:35:32 +02:00
viper151
ce1e6c73b3 feat: Add project sorting by date option
feat: Add project sorting by date option
2025-07-12 13:35:04 +02:00
viper151
c6c11c236c Update ToolsSettings.jsx 2025-07-12 13:33:26 +02:00
viper151
211a3c4557 Delete file-metadata-issue.md 2025-07-12 13:28:41 +02:00
Valics Lehel
02a296739d fix: Address project sorting feedback
- Sort by user-defined displayName instead of path/folder name
- Move project sorting under Appearance section
- Replace large toggle buttons with compact dropdown
- Use clearer labels: "Alphabetical" and "Recent Activity"
- Projects now sort by custom names when available
2025-07-12 14:17:56 +03:00
Valics Lehel
1f3fe2df3d feat: Add file metadata display with view modes
- Added file size, permissions (rwx format), and modified date display
- Implemented three view modes: simple, compact, and detailed
- Added server-side file stats collection in getFileTree
- View mode preference persisted in localStorage
- Detailed view shows table-like layout with column headers
- Compact view shows inline metadata
- Simple view maintains original basic tree structure
2025-07-11 23:14:07 +03:00
Valics Lehel
122b757fa2 feat: Add project sorting by date option
- Added ability to sort projects by name or most recent session activity
- Added projectSortOrder state and localStorage persistence
- Added UI controls in ToolsSettings to switch between sort modes
- Projects with no sessions sort last when sorting by date
- Real-time updates when sort preference changes
2025-07-11 22:42:22 +03:00
simos
45b3e54d04 Added stared project and ux enahncements 2025-07-11 12:35:27 +00:00
viper151
4762a2d719 Update README.md 2025-07-11 12:47:11 +02:00
17 changed files with 3304 additions and 258 deletions

1
.gitignore vendored
View File

@@ -90,6 +90,7 @@ jspm_packages/
# Temporary folders
tmp/
temp/
.tmp/
# Vite
.vite/

View File

@@ -33,10 +33,11 @@ A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/cla
## Features
- **Responsive Design** - Works seamlessly across desktop, tablet, and mobile
- **Responsive Design** - Works seamlessly across desktop, tablet, and mobile so you can also use Claude Code from mobile
- **Interactive Chat Interface** - Built-in chat interface for seamless communication with Claude Code
- **Integrated Shell Terminal** - Direct access to Claude Code CLI through built-in shell functionality
- **File Explorer** - Interactive file tree with syntax highlighting and live editing
- **Git Explorer** - View, stage and commit your changes. You can also switch branches
- **Session Management** - Resume conversations, manage multiple sessions, and track history
@@ -44,7 +45,7 @@ A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/cla
### Prerequisites
- [Node.js](https://nodejs.org/) v16 or higher
- [Node.js](https://nodejs.org/) v20 or higher
- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) installed and configured
### Installation
@@ -72,6 +73,7 @@ cp .env.example .env
npm run dev
```
The application will start at the port you specified in your .env
5. **Open your browser:**
- Development: `http://localhost:3001`
@@ -120,17 +122,21 @@ The UI automatically discovers Claude Code projects from `~/.claude/projects/` a
- **Syntax Highlighting** - Support for multiple programming languages
- **File Operations** - Create, rename, delete files and directories
#### Git Explorer
#### Session Management
- **Session Persistence** - All conversations automatically saved
- **Session Organization** - Group sessions by project and timestamp
- **Session Actions** - Rename, delete, and export conversation history
- **Cross-device Sync** - Access sessions from any device
### Mobile Experience
### Mobile App
- **Responsive Design** - Optimized for all screen sizes
- **Touch-friendly Interface** - Swipe gestures and touch navigation
- **Mobile Navigation** - Bottom tab bar for easy thumb navigation
- **Adaptive Layout** - Collapsible sidebar and smart content prioritization
- **Add shortcut to Home Screen** - Add a shortcut to your home screen and the app will behave like a PWA
## Architecture
@@ -230,8 +236,10 @@ This project is open source and free to use, modify, and distribute under the GP
- **Watch** for updates and new releases
- **Follow** the project for announcements
### Sponsors
- [Siteboon - AI powered website builder](https://siteboon.ai)
---
<div align="center">
<strong>Made with care for the Claude Code community</strong>
</div>
<strong>Made with care for the Claude Code community.</strong>
</div>

155
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "claude-code-ui",
"version": "1.1.4",
"version": "1.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-code-ui",
"version": "1.1.4",
"version": "1.2.0",
"license": "MIT",
"dependencies": {
"@anthropic-ai/claude-code": "^1.0.24",
@@ -31,10 +31,12 @@
"jsonwebtoken": "^9.0.2",
"lucide-react": "^0.515.0",
"mime-types": "^3.0.1",
"multer": "^2.0.1",
"node-fetch": "^2.7.0",
"node-pty": "^1.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",
"react-markdown": "^10.1.0",
"react-router-dom": "^6.8.1",
"tailwind-merge": "^3.3.1",
@@ -2115,6 +2117,12 @@
"node": ">= 8"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/arg": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",
@@ -2125,6 +2133,15 @@
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
},
"node_modules/attr-accept": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
"integrity": "sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/autoprefixer": {
"version": "10.4.21",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.21.tgz",
@@ -2366,6 +2383,23 @@
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -2677,6 +2711,21 @@
"node": ">= 6"
}
},
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/concurrently": {
"version": "8.2.2",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-8.2.2.tgz",
@@ -3195,6 +3244,18 @@
"reusify": "^1.0.4"
}
},
"node_modules/file-selector": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/file-selector/-/file-selector-2.1.2.tgz",
"integrity": "sha512-QgXo+mXTe8ljeqUFaX3QVHc5osSItJ/Km+xpocx0aSqWGMSCf6qYs/VnzZgS864Pjn5iceMRFigeAV7AfTlaig==",
"license": "MIT",
"dependencies": {
"tslib": "^2.7.0"
},
"engines": {
"node": ">= 12"
}
},
"node_modules/file-uri-to-path": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
@@ -4578,6 +4639,18 @@
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"license": "MIT",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/mkdirp-classic": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
@@ -4588,6 +4661,24 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/multer": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.0.1.tgz",
"integrity": "sha512-Ug8bXeTIUlxurg8xLTEskKShvcKDZALo1THEX5E41pYCD2sCVub5/kIRIGqWNoqV6szyLyQKV6mD4QUrWE5GCQ==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.6.0",
"concat-stream": "^2.0.0",
"mkdirp": "^0.5.6",
"object-assign": "^4.1.1",
"type-is": "^1.6.18",
"xtend": "^4.0.2"
},
"engines": {
"node": ">= 10.16.0"
}
},
"node_modules/mz": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
@@ -5049,6 +5140,17 @@
"node": ">=10"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"node_modules/property-information": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
@@ -5171,6 +5273,29 @@
"react": "^18.3.1"
}
},
"node_modules/react-dropzone": {
"version": "14.3.8",
"resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-14.3.8.tgz",
"integrity": "sha512-sBgODnq+lcA4P296DY4wacOZz3JFpD99fp+hb//iBO2HHnyeZU3FwWyXJ6salNpqQdsZrgMrotuko/BdJMV8Ug==",
"license": "MIT",
"dependencies": {
"attr-accept": "^2.2.4",
"file-selector": "^2.1.0",
"prop-types": "^15.8.1"
},
"engines": {
"node": ">= 10.13"
},
"peerDependencies": {
"react": ">= 16.8 || 18.0.0"
}
},
"node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/react-markdown": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
@@ -5966,6 +6091,14 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
@@ -6407,8 +6540,7 @@
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
},
"node_modules/tunnel-agent": {
"version": "0.6.0",
@@ -6452,6 +6584,12 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/unified": {
"version": "11.0.5",
"resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
@@ -6860,6 +6998,15 @@
}
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
},
"node_modules/xterm": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/xterm/-/xterm-5.3.0.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-ui",
"version": "1.2.0",
"version": "1.5.0",
"description": "A web-based UI for Claude Code CLI",
"type": "module",
"main": "server/index.js",
@@ -44,10 +44,12 @@
"jsonwebtoken": "^9.0.2",
"lucide-react": "^0.515.0",
"mime-types": "^3.0.1",
"multer": "^2.0.1",
"node-fetch": "^2.7.0",
"node-pty": "^1.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",
"react-markdown": "^10.1.0",
"react-router-dom": "^6.8.1",
"tailwind-merge": "^3.3.1",

View File

@@ -1,10 +1,13 @@
import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';
let activeClaudeProcesses = new Map(); // Track active processes by session ID
async function spawnClaude(command, options = {}, ws) {
return new Promise(async (resolve, reject) => {
const { sessionId, projectPath, cwd, resume, toolsSettings, permissionMode } = options;
const { sessionId, projectPath, cwd, resume, toolsSettings, permissionMode, images } = options;
let capturedSessionId = sessionId; // Track session ID throughout the process
let sessionCreatedSent = false; // Track if we've already sent session-created event
@@ -14,7 +17,7 @@ async function spawnClaude(command, options = {}, ws) {
disallowedTools: [],
skipPermissions: false
};
// Build Claude CLI command - start with print/resume flags first
const args = [];
@@ -23,6 +26,56 @@ async function spawnClaude(command, options = {}, ws) {
args.push('--print', command);
}
// Use cwd (actual project directory) instead of projectPath (Claude's metadata directory)
const workingDir = cwd || process.cwd();
// Handle images by saving them to temporary files and passing paths to Claude
const tempImagePaths = [];
let tempDir = null;
if (images && images.length > 0) {
try {
// Create temp directory in the project directory so Claude can access it
tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
await fs.mkdir(tempDir, { recursive: true });
// Save each image to a temp file
for (const [index, image] of images.entries()) {
// Extract base64 data and mime type
const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
if (!matches) {
console.error('Invalid image data format');
continue;
}
const [, mimeType, base64Data] = matches;
const extension = mimeType.split('/')[1] || 'png';
const filename = `image_${index}.${extension}`;
const filepath = path.join(tempDir, filename);
// Write base64 data to file
await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
tempImagePaths.push(filepath);
}
// Include the full image paths in the prompt for Claude to reference
// Only modify the command if we actually have images and a command
if (tempImagePaths.length > 0 && command && command.trim()) {
const imageNote = `\n\n[Images provided at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
const modifiedCommand = command + imageNote;
// Update the command in args
const printIndex = args.indexOf('--print');
if (printIndex !== -1 && args[printIndex + 1] === command) {
args[printIndex + 1] = modifiedCommand;
}
}
} catch (error) {
console.error('Error processing images for Claude:', error);
}
}
// Add resume flag if resuming
if (resume && sessionId) {
args.push('--resume', sessionId);
@@ -31,6 +84,84 @@ async function spawnClaude(command, options = {}, ws) {
// Add basic flags
args.push('--output-format', 'stream-json', '--verbose');
// Add MCP config flag only if MCP servers are configured
try {
console.log('🔍 Starting MCP config check...');
// Use already imported modules (fs.promises is imported as fs, path, os)
const fsSync = await import('fs'); // Import synchronous fs methods
console.log('✅ Successfully imported fs sync methods');
// Check for MCP config in ~/.claude.json
const claudeConfigPath = path.join(os.homedir(), '.claude.json');
console.log(`🔍 Checking for MCP configs in: ${claudeConfigPath}`);
console.log(` Claude config exists: ${fsSync.existsSync(claudeConfigPath)}`);
let hasMcpServers = false;
// Check Claude config for MCP servers
if (fsSync.existsSync(claudeConfigPath)) {
try {
const claudeConfig = JSON.parse(fsSync.readFileSync(claudeConfigPath, 'utf8'));
// Check global MCP servers
if (claudeConfig.mcpServers && Object.keys(claudeConfig.mcpServers).length > 0) {
console.log(`✅ Found ${Object.keys(claudeConfig.mcpServers).length} global MCP servers`);
hasMcpServers = true;
}
// Check project-specific MCP servers
if (!hasMcpServers && claudeConfig.claudeProjects) {
const currentProjectPath = process.cwd();
const projectConfig = claudeConfig.claudeProjects[currentProjectPath];
if (projectConfig && projectConfig.mcpServers && Object.keys(projectConfig.mcpServers).length > 0) {
console.log(`✅ Found ${Object.keys(projectConfig.mcpServers).length} project MCP servers`);
hasMcpServers = true;
}
}
} catch (e) {
console.log(`❌ Failed to parse Claude config:`, e.message);
}
}
console.log(`🔍 hasMcpServers result: ${hasMcpServers}`);
if (hasMcpServers) {
// Use Claude config file if it has MCP servers
let configPath = null;
if (fsSync.existsSync(claudeConfigPath)) {
try {
const claudeConfig = JSON.parse(fsSync.readFileSync(claudeConfigPath, 'utf8'));
// Check if we have any MCP servers (global or project-specific)
const hasGlobalServers = claudeConfig.mcpServers && Object.keys(claudeConfig.mcpServers).length > 0;
const currentProjectPath = process.cwd();
const projectConfig = claudeConfig.claudeProjects && claudeConfig.claudeProjects[currentProjectPath];
const hasProjectServers = projectConfig && projectConfig.mcpServers && Object.keys(projectConfig.mcpServers).length > 0;
if (hasGlobalServers || hasProjectServers) {
configPath = claudeConfigPath;
}
} catch (e) {
// No valid config found
}
}
if (configPath) {
console.log(`📡 Adding MCP config: ${configPath}`);
args.push('--mcp-config', configPath);
} else {
console.log('⚠️ MCP servers detected but no valid config file found');
}
}
} catch (error) {
// If there's any error checking for MCP configs, don't add the flag
console.log('❌ MCP config check failed:', error.message);
console.log('📍 Error stack:', error.stack);
console.log('Note: MCP config check failed, proceeding without MCP support');
}
// Add model for new sessions
if (!resume) {
args.push('--model', 'sonnet');
@@ -87,15 +218,14 @@ async function spawnClaude(command, options = {}, ws) {
}
}
// Use cwd (actual project directory) instead of projectPath (Claude's metadata directory)
const workingDir = cwd || process.cwd();
console.log('Spawning Claude CLI:', 'claude', args.map(arg => {
const cleanArg = arg.replace(/\n/g, '\\n').replace(/\r/g, '\\r');
return cleanArg.includes(' ') ? `"${cleanArg}"` : cleanArg;
}).join(' '));
console.log('Working directory:', workingDir);
console.log('Session info - Input sessionId:', sessionId, 'Resume:', resume);
console.log('🔍 Full command args:', args);
console.log('🔍 Full command args:', JSON.stringify(args, null, 2));
console.log('🔍 Final Claude command will be: claude ' + args.join(' '));
const claudeProcess = spawn('claude', args, {
cwd: workingDir,
@@ -103,6 +233,10 @@ async function spawnClaude(command, options = {}, ws) {
env: { ...process.env } // Inherit all environment variables
});
// Attach temp file info to process for cleanup later
claudeProcess.tempImagePaths = tempImagePaths;
claudeProcess.tempDir = tempDir;
// Store process reference for potential abort
const processKey = capturedSessionId || sessionId || Date.now().toString();
activeClaudeProcesses.set(processKey, claudeProcess);
@@ -166,7 +300,7 @@ async function spawnClaude(command, options = {}, ws) {
});
// Handle process completion
claudeProcess.on('close', (code) => {
claudeProcess.on('close', async (code) => {
console.log(`Claude CLI process exited with code ${code}`);
// Clean up process reference
@@ -179,6 +313,20 @@ async function spawnClaude(command, options = {}, ws) {
isNewSession: !sessionId && !!command // Flag to indicate this was a new session
}));
// Clean up temporary image files if any
if (claudeProcess.tempImagePaths && claudeProcess.tempImagePaths.length > 0) {
for (const imagePath of claudeProcess.tempImagePaths) {
await fs.unlink(imagePath).catch(err =>
console.error(`Failed to delete temp image ${imagePath}:`, err)
);
}
if (claudeProcess.tempDir) {
await fs.rm(claudeProcess.tempDir, { recursive: true, force: true }).catch(err =>
console.error(`Failed to delete temp directory ${claudeProcess.tempDir}:`, err)
);
}
}
if (code === 0) {
resolve();
} else {

View File

@@ -40,6 +40,7 @@ import { getProjects, getSessions, getSessionMessages, renameProject, deleteSess
import { spawnClaude, abortClaudeSession } from './claude-cli.js';
import gitRoutes from './routes/git.js';
import authRoutes from './routes/auth.js';
import mcpRoutes from './routes/mcp.js';
import { initializeDatabase } from './database/db.js';
import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
@@ -130,18 +131,6 @@ async function setupProjectsWatcher() {
}
}
// Get the first non-localhost IP address
function getServerIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
const app = express();
const server = http.createServer(app);
@@ -183,14 +172,15 @@ app.use('/api/auth', authRoutes);
// Git API Routes (protected)
app.use('/api/git', authenticateToken, gitRoutes);
// MCP API Routes (protected)
app.use('/api/mcp', authenticateToken, mcpRoutes);
// Static files served after API routes
app.use(express.static(path.join(__dirname, '../dist')));
// API Routes (protected)
app.get('/api/config', authenticateToken, (req, res) => {
// Always use the server's actual IP and port for WebSocket connections
const serverIP = getServerIP();
const host = `${serverIP}:${PORT}`;
const host = req.headers.host || `${req.hostname}:${PORT}`;
const protocol = req.protocol === 'https' || req.get('x-forwarded-proto') === 'https' ? 'wss' : 'ws';
console.log('Config API called - Returning host:', host, 'Protocol:', protocol);
@@ -428,8 +418,6 @@ app.get('/api/projects/:projectName/files', authenticateToken, async (req, res)
const files = await getFileTree(actualPath, 3, 0, true);
const hiddenFiles = files.filter(f => f.name.startsWith('.'));
console.log('📄 Found', files.length, 'files/folders, including', hiddenFiles.length, 'hidden files');
console.log('🔍 Hidden files:', hiddenFiles.map(f => f.name));
res.json(files);
} catch (error) {
console.error('❌ File tree error:', error.message);
@@ -814,12 +802,104 @@ Agent instructions:`;
}
});
// Image upload endpoint
app.post('/api/projects/:projectName/upload-images', authenticateToken, async (req, res) => {
try {
const multer = (await import('multer')).default;
const path = (await import('path')).default;
const fs = (await import('fs')).promises;
const os = (await import('os')).default;
// Configure multer for image uploads
const storage = multer.diskStorage({
destination: async (req, file, cb) => {
const uploadDir = path.join(os.tmpdir(), 'claude-ui-uploads', String(req.user.id));
await fs.mkdir(uploadDir, { recursive: true });
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
cb(null, uniqueSuffix + '-' + sanitizedName);
}
});
const fileFilter = (req, file, cb) => {
const allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
if (allowedMimes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Invalid file type. Only JPEG, PNG, GIF, WebP, and SVG are allowed.'));
}
};
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: 5 * 1024 * 1024, // 5MB
files: 5
}
});
// Handle multipart form data
upload.array('images', 5)(req, res, async (err) => {
if (err) {
return res.status(400).json({ error: err.message });
}
if (!req.files || req.files.length === 0) {
return res.status(400).json({ error: 'No image files provided' });
}
try {
// Process uploaded images
const processedImages = await Promise.all(
req.files.map(async (file) => {
// Read file and convert to base64
const buffer = await fs.readFile(file.path);
const base64 = buffer.toString('base64');
const mimeType = file.mimetype;
// Clean up temp file immediately
await fs.unlink(file.path);
return {
name: file.originalname,
data: `data:${mimeType};base64,${base64}`,
size: file.size,
mimeType: mimeType
};
})
);
res.json({ images: processedImages });
} catch (error) {
console.error('Error processing images:', error);
// Clean up any remaining files
await Promise.all(req.files.map(f => fs.unlink(f.path).catch(() => {})));
res.status(500).json({ error: 'Failed to process images' });
}
});
} catch (error) {
console.error('Error in image upload endpoint:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Serve React app for all other routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
// Helper function to convert permissions to rwx format
function permToRwx(perm) {
const r = perm & 4 ? 'r' : '-';
const w = perm & 2 ? 'w' : '-';
const x = perm & 1 ? 'x' : '-';
return r + w + x;
}
async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden = true) {
// Using fsPromises from import
const items = [];
@@ -836,12 +916,34 @@ async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden =
entry.name === 'dist' ||
entry.name === 'build') continue;
const itemPath = path.join(dirPath, entry.name);
const item = {
name: entry.name,
path: path.join(dirPath, entry.name),
path: itemPath,
type: entry.isDirectory() ? 'directory' : 'file'
};
// Get file stats for additional metadata
try {
const stats = await fsPromises.stat(itemPath);
item.size = stats.size;
item.modified = stats.mtime.toISOString();
// Convert permissions to rwx format
const mode = stats.mode;
const ownerPerm = (mode >> 6) & 7;
const groupPerm = (mode >> 3) & 7;
const otherPerm = mode & 7;
item.permissions = ((mode >> 6) & 7).toString() + ((mode >> 3) & 7).toString() + (mode & 7).toString();
item.permissionsRwx = permToRwx(ownerPerm) + permToRwx(groupPerm) + permToRwx(otherPerm);
} catch (statError) {
// If stat fails, provide default values
item.size = 0;
item.modified = null;
item.permissions = '000';
item.permissionsRwx = '---------';
}
if (entry.isDirectory() && currentDepth < maxDepth) {
// Recursively get subdirectories but limit depth
try {
@@ -892,4 +994,4 @@ async function startServer() {
}
}
startServer();
startServer();

View File

@@ -11,7 +11,6 @@ let cacheTimestamp = Date.now();
function clearProjectDirectoryCache() {
projectDirectoryCache.clear();
cacheTimestamp = Date.now();
console.log('🗑️ Project directory cache cleared');
}
// Load project configuration file
@@ -73,7 +72,6 @@ async function extractProjectDirectory(projectName) {
return projectDirectoryCache.get(projectName);
}
console.log(`🔍 Extracting project directory for: ${projectName}`);
const projectDir = path.join(process.env.HOME, '.claude', 'projects', projectName);
const cwdCounts = new Map();
@@ -155,7 +153,6 @@ async function extractProjectDirectory(projectName) {
// Cache the result
projectDirectoryCache.set(projectName, extractedPath);
console.log(`💾 Cached project directory: ${projectName} -> ${extractedPath}`);
return extractedPath;

View File

@@ -420,4 +420,276 @@ function generateSimpleCommitMessage(files, diff) {
}
}
// Get remote status (ahead/behind commits with smart remote detection)
router.get('/remote-status', async (req, res) => {
const { project } = req.query;
if (!project) {
return res.status(400).json({ error: 'Project name is required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
// Get current branch
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
const branch = currentBranch.trim();
// Check if there's a remote tracking branch (smart detection)
let trackingBranch;
let remoteName;
try {
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
trackingBranch = stdout.trim();
remoteName = trackingBranch.split('/')[0]; // Extract remote name (e.g., "origin/main" -> "origin")
} catch (error) {
// No upstream branch configured
return res.json({
hasRemote: false,
branch,
message: 'No remote tracking branch configured'
});
}
// Get ahead/behind counts
const { stdout: countOutput } = await execAsync(
`git rev-list --count --left-right ${trackingBranch}...HEAD`,
{ cwd: projectPath }
);
const [behind, ahead] = countOutput.trim().split('\t').map(Number);
res.json({
hasRemote: true,
branch,
remoteBranch: trackingBranch,
remoteName,
ahead: ahead || 0,
behind: behind || 0,
isUpToDate: ahead === 0 && behind === 0
});
} catch (error) {
console.error('Git remote status error:', error);
res.json({ error: error.message });
}
});
// Fetch from remote (using smart remote detection)
router.post('/fetch', async (req, res) => {
const { project } = req.body;
if (!project) {
return res.status(400).json({ error: 'Project name is required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
// Get current branch and its upstream remote
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
const branch = currentBranch.trim();
let remoteName = 'origin'; // fallback
try {
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
remoteName = stdout.trim().split('/')[0]; // Extract remote name
} catch (error) {
// No upstream, try to fetch from origin anyway
console.log('No upstream configured, using origin as fallback');
}
const { stdout } = await execAsync(`git fetch ${remoteName}`, { cwd: projectPath });
res.json({ success: true, output: stdout || 'Fetch completed successfully', remoteName });
} catch (error) {
console.error('Git fetch error:', error);
res.status(500).json({
error: 'Fetch failed',
details: error.message.includes('Could not resolve hostname')
? 'Unable to connect to remote repository. Check your internet connection.'
: error.message.includes('fatal: \'origin\' does not appear to be a git repository')
? 'No remote repository configured. Add a remote with: git remote add origin <url>'
: error.message
});
}
});
// Pull from remote (fetch + merge using smart remote detection)
router.post('/pull', async (req, res) => {
const { project } = req.body;
if (!project) {
return res.status(400).json({ error: 'Project name is required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
// Get current branch and its upstream remote
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
const branch = currentBranch.trim();
let remoteName = 'origin'; // fallback
let remoteBranch = branch; // fallback
try {
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
const tracking = stdout.trim();
remoteName = tracking.split('/')[0]; // Extract remote name
remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
} catch (error) {
// No upstream, use fallback
console.log('No upstream configured, using origin/branch as fallback');
}
const { stdout } = await execAsync(`git pull ${remoteName} ${remoteBranch}`, { cwd: projectPath });
res.json({
success: true,
output: stdout || 'Pull completed successfully',
remoteName,
remoteBranch
});
} catch (error) {
console.error('Git pull error:', error);
// Enhanced error handling for common pull scenarios
let errorMessage = 'Pull failed';
let details = error.message;
if (error.message.includes('CONFLICT')) {
errorMessage = 'Merge conflicts detected';
details = 'Pull created merge conflicts. Please resolve conflicts manually in the editor, then commit the changes.';
} else if (error.message.includes('Please commit your changes or stash them')) {
errorMessage = 'Uncommitted changes detected';
details = 'Please commit or stash your local changes before pulling.';
} else if (error.message.includes('Could not resolve hostname')) {
errorMessage = 'Network error';
details = 'Unable to connect to remote repository. Check your internet connection.';
} else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
errorMessage = 'Remote not configured';
details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
} else if (error.message.includes('diverged')) {
errorMessage = 'Branches have diverged';
details = 'Your local branch and remote branch have diverged. Consider fetching first to review changes.';
}
res.status(500).json({
error: errorMessage,
details: details
});
}
});
// Push commits to remote repository
router.post('/push', async (req, res) => {
const { project } = req.body;
if (!project) {
return res.status(400).json({ error: 'Project name is required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
// Get current branch and its upstream remote
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
const branch = currentBranch.trim();
let remoteName = 'origin'; // fallback
let remoteBranch = branch; // fallback
try {
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
const tracking = stdout.trim();
remoteName = tracking.split('/')[0]; // Extract remote name
remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
} catch (error) {
// No upstream, use fallback
console.log('No upstream configured, using origin/branch as fallback');
}
const { stdout } = await execAsync(`git push ${remoteName} ${remoteBranch}`, { cwd: projectPath });
res.json({
success: true,
output: stdout || 'Push completed successfully',
remoteName,
remoteBranch
});
} catch (error) {
console.error('Git push error:', error);
// Enhanced error handling for common push scenarios
let errorMessage = 'Push failed';
let details = error.message;
if (error.message.includes('rejected')) {
errorMessage = 'Push rejected';
details = 'The remote has newer commits. Pull first to merge changes before pushing.';
} else if (error.message.includes('non-fast-forward')) {
errorMessage = 'Non-fast-forward push';
details = 'Your branch is behind the remote. Pull the latest changes first.';
} else if (error.message.includes('Could not resolve hostname')) {
errorMessage = 'Network error';
details = 'Unable to connect to remote repository. Check your internet connection.';
} else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
errorMessage = 'Remote not configured';
details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
} else if (error.message.includes('Permission denied')) {
errorMessage = 'Authentication failed';
details = 'Permission denied. Check your credentials or SSH keys.';
} else if (error.message.includes('no upstream branch')) {
errorMessage = 'No upstream branch';
details = 'No upstream branch configured. Use: git push --set-upstream origin <branch>';
}
res.status(500).json({
error: errorMessage,
details: details
});
}
});
// Discard changes for a specific file
router.post('/discard', async (req, res) => {
const { project, file } = req.body;
if (!project || !file) {
return res.status(400).json({ error: 'Project name and file path are required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
// Check file status to determine correct discard command
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
if (!statusOutput.trim()) {
return res.status(400).json({ error: 'No changes to discard for this file' });
}
const status = statusOutput.substring(0, 2);
if (status === '??') {
// Untracked file - delete it
await fs.unlink(path.join(projectPath, file));
} else if (status.includes('M') || status.includes('D')) {
// Modified or deleted file - restore from HEAD
await execAsync(`git restore "${file}"`, { cwd: projectPath });
} else if (status.includes('A')) {
// Added file - unstage it
await execAsync(`git reset HEAD "${file}"`, { cwd: projectPath });
}
res.json({ success: true, message: `Changes discarded for ${file}` });
} catch (error) {
console.error('Git discard error:', error);
res.status(500).json({ error: error.message });
}
});
export default router;

286
server/routes/mcp.js Normal file
View File

@@ -0,0 +1,286 @@
import express from 'express';
import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { spawn } from 'child_process';
const router = express.Router();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Claude CLI command routes
// GET /api/mcp/cli/list - List MCP servers using Claude CLI
router.get('/cli/list', async (req, res) => {
try {
console.log('📋 Listing MCP servers using Claude CLI');
const { spawn } = await import('child_process');
const { promisify } = await import('util');
const exec = promisify(spawn);
const process = spawn('claude', ['mcp', 'list', '-s', 'user'], {
stdio: ['pipe', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
process.stdout.on('data', (data) => {
stdout += data.toString();
});
process.stderr.on('data', (data) => {
stderr += data.toString();
});
process.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, servers: parseClaudeListOutput(stdout) });
} else {
console.error('Claude CLI error:', stderr);
res.status(500).json({ error: 'Claude CLI command failed', details: stderr });
}
});
process.on('error', (error) => {
console.error('Error running Claude CLI:', error);
res.status(500).json({ error: 'Failed to run Claude CLI', details: error.message });
});
} catch (error) {
console.error('Error listing MCP servers via CLI:', error);
res.status(500).json({ error: 'Failed to list MCP servers', details: error.message });
}
});
// POST /api/mcp/cli/add - Add MCP server using Claude CLI
router.post('/cli/add', async (req, res) => {
try {
const { name, type = 'stdio', command, args = [], url, headers = {}, env = {} } = req.body;
console.log(' Adding MCP server using Claude CLI:', name);
const { spawn } = await import('child_process');
let cliArgs = ['mcp', 'add'];
if (type === 'http') {
cliArgs.push('--transport', 'http', name, '-s', 'user', url);
// Add headers if provided
Object.entries(headers).forEach(([key, value]) => {
cliArgs.push('--header', `${key}: ${value}`);
});
} else if (type === 'sse') {
cliArgs.push('--transport', 'sse', name, '-s', 'user', url);
// Add headers if provided
Object.entries(headers).forEach(([key, value]) => {
cliArgs.push('--header', `${key}: ${value}`);
});
} else {
// stdio (default): claude mcp add <name> -s user <command> [args...]
cliArgs.push(name, '-s', 'user');
// Add environment variables
Object.entries(env).forEach(([key, value]) => {
cliArgs.push('-e', `${key}=${value}`);
});
cliArgs.push(command);
if (args && args.length > 0) {
cliArgs.push(...args);
}
}
console.log('🔧 Running Claude CLI command:', 'claude', cliArgs.join(' '));
const process = spawn('claude', cliArgs, {
stdio: ['pipe', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
process.stdout.on('data', (data) => {
stdout += data.toString();
});
process.stderr.on('data', (data) => {
stderr += data.toString();
});
process.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, message: `MCP server "${name}" added successfully` });
} else {
console.error('Claude CLI error:', stderr);
res.status(400).json({ error: 'Claude CLI command failed', details: stderr });
}
});
process.on('error', (error) => {
console.error('Error running Claude CLI:', error);
res.status(500).json({ error: 'Failed to run Claude CLI', details: error.message });
});
} catch (error) {
console.error('Error adding MCP server via CLI:', error);
res.status(500).json({ error: 'Failed to add MCP server', details: error.message });
}
});
// DELETE /api/mcp/cli/remove/:name - Remove MCP server using Claude CLI
router.delete('/cli/remove/:name', async (req, res) => {
try {
const { name } = req.params;
console.log('🗑️ Removing MCP server using Claude CLI:', name);
const { spawn } = await import('child_process');
const process = spawn('claude', ['mcp', 'remove', '-s', 'user', name], {
stdio: ['pipe', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
process.stdout.on('data', (data) => {
stdout += data.toString();
});
process.stderr.on('data', (data) => {
stderr += data.toString();
});
process.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, message: `MCP server "${name}" removed successfully` });
} else {
console.error('Claude CLI error:', stderr);
res.status(400).json({ error: 'Claude CLI command failed', details: stderr });
}
});
process.on('error', (error) => {
console.error('Error running Claude CLI:', error);
res.status(500).json({ error: 'Failed to run Claude CLI', details: error.message });
});
} catch (error) {
console.error('Error removing MCP server via CLI:', error);
res.status(500).json({ error: 'Failed to remove MCP server', details: error.message });
}
});
// GET /api/mcp/cli/get/:name - Get MCP server details using Claude CLI
router.get('/cli/get/:name', async (req, res) => {
try {
const { name } = req.params;
console.log('📄 Getting MCP server details using Claude CLI:', name);
const { spawn } = await import('child_process');
const process = spawn('claude', ['mcp', 'get', '-s', 'user', name], {
stdio: ['pipe', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
process.stdout.on('data', (data) => {
stdout += data.toString();
});
process.stderr.on('data', (data) => {
stderr += data.toString();
});
process.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, server: parseClaudeGetOutput(stdout) });
} else {
console.error('Claude CLI error:', stderr);
res.status(404).json({ error: 'Claude CLI command failed', details: stderr });
}
});
process.on('error', (error) => {
console.error('Error running Claude CLI:', error);
res.status(500).json({ error: 'Failed to run Claude CLI', details: error.message });
});
} catch (error) {
console.error('Error getting MCP server details via CLI:', error);
res.status(500).json({ error: 'Failed to get MCP server details', details: error.message });
}
});
// Helper functions to parse Claude CLI output
function parseClaudeListOutput(output) {
// Parse the output from 'claude mcp list' command
// Format: "name: command/url" or "name: url (TYPE)"
const servers = [];
const lines = output.split('\n').filter(line => line.trim());
for (const line of lines) {
if (line.includes(':')) {
const colonIndex = line.indexOf(':');
const name = line.substring(0, colonIndex).trim();
const rest = line.substring(colonIndex + 1).trim();
let type = 'stdio'; // default type
// Check if it has transport type in parentheses like "(SSE)" or "(HTTP)"
const typeMatch = rest.match(/\((\w+)\)\s*$/);
if (typeMatch) {
type = typeMatch[1].toLowerCase();
} else if (rest.startsWith('http://') || rest.startsWith('https://')) {
// If it's a URL but no explicit type, assume HTTP
type = 'http';
}
if (name) {
servers.push({
name,
type,
status: 'active'
});
}
}
}
console.log('🔍 Parsed Claude CLI servers:', servers);
return servers;
}
function parseClaudeGetOutput(output) {
// Parse the output from 'claude mcp get <name>' command
// This is a simple parser - might need adjustment based on actual output format
try {
// Try to extract JSON if present
const jsonMatch = output.match(/\{[\s\S]*\}/);
if (jsonMatch) {
return JSON.parse(jsonMatch[0]);
}
// Otherwise, parse as text
const server = { raw_output: output };
const lines = output.split('\n');
for (const line of lines) {
if (line.includes('Name:')) {
server.name = line.split(':')[1]?.trim();
} else if (line.includes('Type:')) {
server.type = line.split(':')[1]?.trim();
} else if (line.includes('Command:')) {
server.command = line.split(':')[1]?.trim();
} else if (line.includes('URL:')) {
server.url = line.split(':')[1]?.trim();
}
}
return server;
} catch (error) {
return { raw_output: output, parse_error: error.message };
}
}
export default router;

View File

@@ -18,6 +18,7 @@
import React, { useState, useEffect, useRef, useMemo, useCallback, memo } from 'react';
import ReactMarkdown from 'react-markdown';
import { useDropzone } from 'react-dropzone';
import TodoList from './TodoList';
import ClaudeLogo from './ClaudeLogo.jsx';
@@ -72,6 +73,19 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
<div className="text-sm whitespace-pre-wrap break-words">
{message.content}
</div>
{message.images && message.images.length > 0 && (
<div className="mt-2 grid grid-cols-2 gap-2">
{message.images.map((img, idx) => (
<img
key={idx}
src={img.data}
alt={img.name}
className="rounded-lg max-w-full h-auto cursor-pointer hover:opacity-90 transition-opacity"
onClick={() => window.open(img.data, '_blank')}
/>
))}
</div>
)}
<div className="text-xs text-blue-100 mt-1 text-right">
{new Date(message.timestamp).toLocaleTimeString()}
</div>
@@ -451,6 +465,32 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
}
}
// Special handling for exit_plan_mode tool
if (message.toolName === 'exit_plan_mode') {
try {
const input = JSON.parse(message.toolInput);
if (input.plan) {
// Replace escaped newlines with actual newlines
const planContent = input.plan.replace(/\\n/g, '\n');
return (
<details className="mt-2" open={autoExpandTools}>
<summary className="text-sm text-blue-700 dark:text-blue-300 cursor-pointer hover:text-blue-800 dark:hover:text-blue-200 flex items-center gap-2">
<svg className="w-4 h-4 transition-transform details-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
📋 View implementation plan
</summary>
<div className="mt-3 prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown>{planContent}</ReactMarkdown>
</div>
</details>
);
}
} catch (e) {
// Fall back to regular display
}
}
// Regular tool input display for other tools
return (
<details className="mt-2" open={autoExpandTools}>
@@ -537,6 +577,30 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
}
}
// Special handling for exit_plan_mode tool results
if (message.toolName === 'exit_plan_mode') {
try {
// The content should be JSON with a "plan" field
const parsed = JSON.parse(content);
if (parsed.plan) {
// Replace escaped newlines with actual newlines
const planContent = parsed.plan.replace(/\\n/g, '\n');
return (
<div>
<div className="flex items-center gap-2 mb-3">
<span className="font-medium">Implementation Plan</span>
</div>
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown>{planContent}</ReactMarkdown>
</div>
</div>
);
}
} catch (e) {
// Fall through to regular handling
}
}
// Special handling for interactive prompts
if (content.includes('Do you want to proceed?') && message.toolName === 'Bash') {
const lines = content.split('\n');
@@ -875,6 +939,43 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
);
});
// ImageAttachment component for displaying image previews
const ImageAttachment = ({ file, onRemove, uploadProgress, error }) => {
const [preview, setPreview] = useState(null);
useEffect(() => {
const url = URL.createObjectURL(file);
setPreview(url);
return () => URL.revokeObjectURL(url);
}, [file]);
return (
<div className="relative group">
<img src={preview} alt={file.name} className="w-20 h-20 object-cover rounded" />
{uploadProgress !== undefined && uploadProgress < 100 && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<div className="text-white text-xs">{uploadProgress}%</div>
</div>
)}
{error && (
<div className="absolute inset-0 bg-red-500/50 flex items-center justify-center">
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
)}
<button
onClick={onRemove}
className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
);
};
// ChatInterface: Main chat component with Session Protection System integration
//
// Session Protection System prevents automatic project updates from interrupting active conversations:
@@ -904,6 +1005,9 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
const [isLoadingSessionMessages, setIsLoadingSessionMessages] = useState(false);
const [isSystemSessionChange, setIsSystemSessionChange] = useState(false);
const [permissionMode, setPermissionMode] = useState('default');
const [attachedImages, setAttachedImages] = useState([]);
const [uploadingImages, setUploadingImages] = useState(new Map());
const [imageErrors, setImageErrors] = useState(new Map());
const messagesEndRef = useRef(null);
const textareaRef = useRef(null);
const scrollContainerRef = useRef(null);
@@ -923,6 +1027,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
const [isTextareaExpanded, setIsTextareaExpanded] = useState(false);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(-1);
const [slashPosition, setSlashPosition] = useState(-1);
const [visibleMessageCount, setVisibleMessageCount] = useState(100);
const [claudeStatus, setClaudeStatus] = useState(null);
@@ -1380,6 +1485,11 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
setCurrentSessionId(pendingSessionId);
sessionStorage.removeItem('pendingSessionId');
}
// Clear persisted chat messages after successful completion
if (selectedProject && latestMessage.exitCode === 0) {
localStorage.removeItem(`chat_messages_${selectedProject.name}`);
}
break;
case 'session-aborted':
@@ -1521,14 +1631,13 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
return () => clearTimeout(timer);
}, [input]);
// Show only recent messages for better performance (last 100 messages)
// Show only recent messages for better performance
const visibleMessages = useMemo(() => {
const maxMessages = 100;
if (chatMessages.length <= maxMessages) {
if (chatMessages.length <= visibleMessageCount) {
return chatMessages;
}
return chatMessages.slice(-maxMessages);
}, [chatMessages]);
return chatMessages.slice(-visibleMessageCount);
}, [chatMessages, visibleMessageCount]);
// Capture scroll position before render when auto-scroll is disabled
useEffect(() => {
@@ -1597,6 +1706,14 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
}
}, []); // Only run once on mount
// Reset textarea height when input is cleared programmatically
useEffect(() => {
if (textareaRef.current && !input.trim()) {
textareaRef.current.style.height = 'auto';
setIsTextareaExpanded(false);
}
}, [input]);
const handleTranscript = useCallback((text) => {
if (text.trim()) {
setInput(prevInput => {
@@ -1620,13 +1737,110 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
}
}, []);
const handleSubmit = (e) => {
// Load earlier messages by increasing the visible message count
const loadEarlierMessages = useCallback(() => {
setVisibleMessageCount(prevCount => prevCount + 100);
}, []);
// Handle image files from drag & drop or file picker
const handleImageFiles = useCallback((files) => {
const validFiles = files.filter(file => {
if (!file.type.startsWith('image/')) {
return false;
}
if (file.size > 5 * 1024 * 1024) {
setImageErrors(prev => new Map(prev).set(file.name, 'File too large (max 5MB)'));
return false;
}
return true;
});
if (validFiles.length > 0) {
setAttachedImages(prev => [...prev, ...validFiles].slice(0, 5)); // Max 5 images
}
}, []);
// Handle clipboard paste for images
const handlePaste = useCallback(async (e) => {
const items = Array.from(e.clipboardData.items);
for (const item of items) {
if (item.type.startsWith('image/')) {
const file = item.getAsFile();
if (file) {
handleImageFiles([file]);
}
}
}
// Fallback for some browsers/platforms
if (items.length === 0 && e.clipboardData.files.length > 0) {
const files = Array.from(e.clipboardData.files);
const imageFiles = files.filter(f => f.type.startsWith('image/'));
if (imageFiles.length > 0) {
handleImageFiles(imageFiles);
}
}
}, [handleImageFiles]);
// Setup dropzone
const { getRootProps, getInputProps, isDragActive, open } = useDropzone({
accept: {
'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg']
},
maxSize: 5 * 1024 * 1024, // 5MB
maxFiles: 5,
onDrop: handleImageFiles,
noClick: true, // We'll use our own button
noKeyboard: true
});
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim() || isLoading || !selectedProject) return;
// Upload images first if any
let uploadedImages = [];
if (attachedImages.length > 0) {
const formData = new FormData();
attachedImages.forEach(file => {
formData.append('images', file);
});
try {
const token = localStorage.getItem('auth-token');
const headers = {};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const response = await fetch(`/api/projects/${selectedProject.name}/upload-images`, {
method: 'POST',
headers: headers,
body: formData
});
if (!response.ok) {
throw new Error('Failed to upload images');
}
const result = await response.json();
uploadedImages = result.images;
} catch (error) {
console.error('Image upload failed:', error);
setChatMessages(prev => [...prev, {
type: 'error',
content: `Failed to upload images: ${error.message}`,
timestamp: new Date()
}]);
return;
}
}
const userMessage = {
type: 'user',
content: input,
images: uploadedImages,
timestamp: new Date()
};
@@ -1673,7 +1887,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
const toolsSettings = getToolsSettings();
// Send command to Claude CLI via WebSocket
// Send command to Claude CLI via WebSocket with images
sendMessage({
type: 'claude-command',
command: input,
@@ -1683,12 +1897,24 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
sessionId: currentSessionId,
resume: !!currentSessionId,
toolsSettings: toolsSettings,
permissionMode: permissionMode
permissionMode: permissionMode,
images: uploadedImages // Pass images to backend
}
});
setInput('');
setAttachedImages([]);
setUploadingImages(new Map());
setImageErrors(new Map());
setIsTextareaExpanded(false);
// Reset textarea height
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
// Clear the saved draft since message was sent
if (selectedProject) {
localStorage.removeItem(`draft_input_${selectedProject.name}`);
@@ -1759,25 +1985,47 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
const spaceIndex = textAfterAtQuery.indexOf(' ');
const textAfterQuery = spaceIndex !== -1 ? textAfterAtQuery.slice(spaceIndex) : '';
const newInput = textBeforeAt + '@' + file.path + textAfterQuery;
const newInput = textBeforeAt + '@' + file.path + ' ' + textAfterQuery;
const newCursorPos = textBeforeAt.length + 1 + file.path.length + 1;
// Immediately ensure focus is maintained
if (textareaRef.current && !textareaRef.current.matches(':focus')) {
textareaRef.current.focus();
}
// Update input and cursor position
setInput(newInput);
setCursorPosition(newCursorPos);
// Hide dropdown
setShowFileDropdown(false);
setAtSymbolPosition(-1);
// Focus back to textarea and set cursor position
// Set cursor position synchronously
if (textareaRef.current) {
textareaRef.current.focus();
const newCursorPos = textBeforeAt.length + 1 + file.path.length;
setTimeout(() => {
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos);
setCursorPosition(newCursorPos);
}, 0);
// Use requestAnimationFrame for smoother updates
requestAnimationFrame(() => {
if (textareaRef.current) {
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos);
// Ensure focus is maintained
if (!textareaRef.current.matches(':focus')) {
textareaRef.current.focus();
}
}
});
}
};
const handleInputChange = (e) => {
setInput(e.target.value);
const newValue = e.target.value;
setInput(newValue);
setCursorPosition(e.target.selectionStart);
// Handle height reset when input becomes empty
if (!newValue.trim()) {
e.target.style.height = 'auto';
setIsTextareaExpanded(false);
}
};
const handleTextareaClick = (e) => {
@@ -1853,10 +2101,13 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
</div>
) : (
<>
{chatMessages.length > 100 && (
{chatMessages.length > visibleMessageCount && (
<div className="text-center text-gray-500 dark:text-gray-400 text-sm py-2 border-b border-gray-200 dark:border-gray-700">
Showing last 100 messages ({chatMessages.length} total)
<button className="ml-1 text-blue-600 hover:text-blue-700 underline">
Showing last {visibleMessageCount} messages ({chatMessages.length} total)
<button
className="ml-1 text-blue-600 hover:text-blue-700 underline"
onClick={loadEarlierMessages}
>
Load earlier messages
</button>
</div>
@@ -1971,13 +2222,77 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
</div>
<form onSubmit={handleSubmit} className="relative max-w-4xl mx-auto">
<div className={`relative bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 focus-within:ring-2 focus-within:ring-blue-500 dark:focus-within:ring-blue-500 focus-within:border-blue-500 transition-all duration-200 ${isTextareaExpanded ? 'chat-input-expanded' : ''}`}>
{/* Drag overlay */}
{isDragActive && (
<div className="absolute inset-0 bg-blue-500/20 border-2 border-dashed border-blue-500 rounded-lg flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-lg">
<svg className="w-8 h-8 text-blue-500 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
<p className="text-sm font-medium">Drop images here</p>
</div>
</div>
)}
{/* Image attachments preview */}
{attachedImages.length > 0 && (
<div className="mb-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
<div className="flex flex-wrap gap-2">
{attachedImages.map((file, index) => (
<ImageAttachment
key={index}
file={file}
onRemove={() => {
setAttachedImages(prev => prev.filter((_, i) => i !== index));
}}
uploadProgress={uploadingImages.get(file.name)}
error={imageErrors.get(file.name)}
/>
))}
</div>
</div>
)}
{/* File dropdown - positioned outside dropzone to avoid conflicts */}
{showFileDropdown && filteredFiles.length > 0 && (
<div className="absolute bottom-full left-0 right-0 mb-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg max-h-48 overflow-y-auto z-50 backdrop-blur-sm">
{filteredFiles.map((file, index) => (
<div
key={file.path}
className={`px-4 py-3 cursor-pointer border-b border-gray-100 dark:border-gray-700 last:border-b-0 touch-manipulation ${
index === selectedFileIndex
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300'
: 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
onMouseDown={(e) => {
// Prevent textarea from losing focus on mobile
e.preventDefault();
e.stopPropagation();
}}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
selectFile(file);
}}
>
<div className="font-medium text-sm">{file.name}</div>
<div className="text-xs text-gray-500 dark:text-gray-400 font-mono">
{file.path}
</div>
</div>
))}
</div>
)}
<div {...getRootProps()} className={`relative bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 focus-within:ring-2 focus-within:ring-blue-500 dark:focus-within:ring-blue-500 focus-within:border-blue-500 transition-all duration-200 ${isTextareaExpanded ? 'chat-input-expanded' : ''}`}>
<input {...getInputProps()} />
<textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onClick={handleTextareaClick}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={() => setIsInputFocused(true)}
onBlur={() => setIsInputFocused(false)}
onInput={(e) => {
@@ -1994,7 +2309,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
placeholder="Ask Claude to help with your code... (@ to reference files)"
disabled={isLoading}
rows={1}
className="chat-input-placeholder w-full px-4 sm:px-6 py-3 sm:py-4 pr-28 sm:pr-40 bg-transparent rounded-2xl focus:outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 disabled:opacity-50 resize-none min-h-[40px] sm:min-h-[56px] max-h-[40vh] sm:max-h-[300px] overflow-y-auto text-sm sm:text-base transition-all duration-200"
className="chat-input-placeholder w-full pl-12 pr-28 sm:pr-40 py-3 sm:py-4 bg-transparent rounded-2xl focus:outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 disabled:opacity-50 resize-none min-h-[40px] sm:min-h-[56px] max-h-[40vh] sm:max-h-[300px] overflow-y-auto text-sm sm:text-base transition-all duration-200"
style={{ height: 'auto' }}
/>
{/* Clear button - shown when there's text */}
@@ -2039,6 +2354,18 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
</svg>
</button>
)}
{/* Image upload button */}
<button
type="button"
onClick={open}
className="absolute left-2 bottom-4 p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title="Attach images"
>
<svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</button>
{/* Mic button - HIDDEN */}
<div className="absolute right-16 sm:right-16 top-1/2 transform -translate-y-1/2" style={{ display: 'none' }}>
<MicButton
@@ -2074,28 +2401,6 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
/>
</svg>
</button>
{/* File dropdown */}
{showFileDropdown && filteredFiles.length > 0 && (
<div className="absolute bottom-full left-0 right-0 mb-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg max-h-48 overflow-y-auto z-50">
{filteredFiles.map((file, index) => (
<div
key={file.path}
className={`px-4 py-2 cursor-pointer border-b border-gray-100 dark:border-gray-700 last:border-b-0 ${
index === selectedFileIndex
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300'
: 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
onClick={() => selectFile(file)}
>
<div className="font-medium text-sm">{file.name}</div>
<div className="text-xs text-gray-500 dark:text-gray-400 font-mono">
{file.path}
</div>
</div>
))}
</div>
)}
</div>
{/* Hint text */}
<div className="text-xs text-gray-500 dark:text-gray-400 text-center mt-2 hidden sm:block">

View File

@@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';
import { ScrollArea } from './ui/scroll-area';
import { Button } from './ui/button';
import { Folder, FolderOpen, File, FileText, FileCode } from 'lucide-react';
import { Folder, FolderOpen, File, FileText, FileCode, List, TableProperties, Eye } from 'lucide-react';
import { cn } from '../lib/utils';
import CodeEditor from './CodeEditor';
import ImageViewer from './ImageViewer';
@@ -13,6 +13,7 @@ function FileTree({ selectedProject }) {
const [expandedDirs, setExpandedDirs] = useState(new Set());
const [selectedFile, setSelectedFile] = useState(null);
const [selectedImage, setSelectedImage] = useState(null);
const [viewMode, setViewMode] = useState('detailed'); // 'simple', 'detailed', 'compact'
useEffect(() => {
if (selectedProject) {
@@ -20,6 +21,14 @@ function FileTree({ selectedProject }) {
}
}, [selectedProject]);
// Load view mode preference from localStorage
useEffect(() => {
const savedViewMode = localStorage.getItem('file-tree-view-mode');
if (savedViewMode && ['simple', 'detailed', 'compact'].includes(savedViewMode)) {
setViewMode(savedViewMode);
}
}, []);
const fetchFiles = async () => {
setLoading(true);
try {
@@ -52,6 +61,35 @@ function FileTree({ selectedProject }) {
setExpandedDirs(newExpanded);
};
// Change view mode and save preference
const changeViewMode = (mode) => {
setViewMode(mode);
localStorage.setItem('file-tree-view-mode', mode);
};
// Format file size
const formatFileSize = (bytes) => {
if (!bytes || bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
// Format date as relative time
const formatRelativeTime = (date) => {
if (!date) return '-';
const now = new Date();
const past = new Date(date);
const diffInSeconds = Math.floor((now - past) / 1000);
if (diffInSeconds < 60) return 'just now';
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} min ago`;
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`;
return past.toLocaleDateString();
};
const renderFileTree = (items, level = 0) => {
return items.map((item) => (
<div key={item.path} className="select-none">
@@ -135,6 +173,129 @@ function FileTree({ selectedProject }) {
}
};
// Render detailed view with table-like layout
const renderDetailedView = (items, level = 0) => {
return items.map((item) => (
<div key={item.path} className="select-none">
<div
className={cn(
"grid grid-cols-12 gap-2 p-2 hover:bg-accent cursor-pointer items-center",
)}
style={{ paddingLeft: `${level * 16 + 12}px` }}
onClick={() => {
if (item.type === 'directory') {
toggleDirectory(item.path);
} else if (isImageFile(item.name)) {
setSelectedImage({
name: item.name,
path: item.path,
projectPath: selectedProject.path,
projectName: selectedProject.name
});
} else {
setSelectedFile({
name: item.name,
path: item.path,
projectPath: selectedProject.path,
projectName: selectedProject.name
});
}
}}
>
<div className="col-span-5 flex items-center gap-2 min-w-0">
{item.type === 'directory' ? (
expandedDirs.has(item.path) ? (
<FolderOpen className="w-4 h-4 text-blue-500 flex-shrink-0" />
) : (
<Folder className="w-4 h-4 text-muted-foreground flex-shrink-0" />
)
) : (
getFileIcon(item.name)
)}
<span className="text-sm truncate text-foreground">
{item.name}
</span>
</div>
<div className="col-span-2 text-sm text-muted-foreground">
{item.type === 'file' ? formatFileSize(item.size) : '-'}
</div>
<div className="col-span-3 text-sm text-muted-foreground">
{formatRelativeTime(item.modified)}
</div>
<div className="col-span-2 text-sm text-muted-foreground font-mono">
{item.permissionsRwx || '-'}
</div>
</div>
{item.type === 'directory' &&
expandedDirs.has(item.path) &&
item.children &&
renderDetailedView(item.children, level + 1)}
</div>
));
};
// Render compact view with inline details
const renderCompactView = (items, level = 0) => {
return items.map((item) => (
<div key={item.path} className="select-none">
<div
className={cn(
"flex items-center justify-between p-2 hover:bg-accent cursor-pointer",
)}
style={{ paddingLeft: `${level * 16 + 12}px` }}
onClick={() => {
if (item.type === 'directory') {
toggleDirectory(item.path);
} else if (isImageFile(item.name)) {
setSelectedImage({
name: item.name,
path: item.path,
projectPath: selectedProject.path,
projectName: selectedProject.name
});
} else {
setSelectedFile({
name: item.name,
path: item.path,
projectPath: selectedProject.path,
projectName: selectedProject.name
});
}
}}
>
<div className="flex items-center gap-2 min-w-0">
{item.type === 'directory' ? (
expandedDirs.has(item.path) ? (
<FolderOpen className="w-4 h-4 text-blue-500 flex-shrink-0" />
) : (
<Folder className="w-4 h-4 text-muted-foreground flex-shrink-0" />
)
) : (
getFileIcon(item.name)
)}
<span className="text-sm truncate text-foreground">
{item.name}
</span>
</div>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
{item.type === 'file' && (
<>
<span>{formatFileSize(item.size)}</span>
<span className="font-mono">{item.permissionsRwx}</span>
</>
)}
</div>
</div>
{item.type === 'directory' &&
expandedDirs.has(item.path) &&
item.children &&
renderCompactView(item.children, level + 1)}
</div>
));
};
if (loading) {
return (
<div className="h-full flex items-center justify-center">
@@ -147,6 +308,51 @@ function FileTree({ selectedProject }) {
return (
<div className="h-full flex flex-col bg-card">
{/* View Mode Toggle */}
<div className="p-4 border-b border-border flex items-center justify-between">
<h3 className="text-sm font-medium text-foreground">Files</h3>
<div className="flex gap-1">
<Button
variant={viewMode === 'simple' ? 'default' : 'ghost'}
size="sm"
className="h-8 w-8 p-0"
onClick={() => changeViewMode('simple')}
title="Simple view"
>
<List className="w-4 h-4" />
</Button>
<Button
variant={viewMode === 'compact' ? 'default' : 'ghost'}
size="sm"
className="h-8 w-8 p-0"
onClick={() => changeViewMode('compact')}
title="Compact view"
>
<Eye className="w-4 h-4" />
</Button>
<Button
variant={viewMode === 'detailed' ? 'default' : 'ghost'}
size="sm"
className="h-8 w-8 p-0"
onClick={() => changeViewMode('detailed')}
title="Detailed view"
>
<TableProperties className="w-4 h-4" />
</Button>
</div>
</div>
{/* Column Headers for Detailed View */}
{viewMode === 'detailed' && files.length > 0 && (
<div className="px-4 pt-2 pb-1 border-b border-border">
<div className="grid grid-cols-12 gap-2 px-2 text-xs font-medium text-muted-foreground">
<div className="col-span-5">Name</div>
<div className="col-span-2">Size</div>
<div className="col-span-3">Modified</div>
<div className="col-span-2">Permissions</div>
</div>
</div>
)}
<ScrollArea className="flex-1 p-4">
{files.length === 0 ? (
@@ -160,8 +366,10 @@ function FileTree({ selectedProject }) {
</p>
</div>
) : (
<div className="space-y-1">
{renderFileTree(files)}
<div className={viewMode === 'detailed' ? '' : 'space-y-1'}>
{viewMode === 'simple' && renderFileTree(files)}
{viewMode === 'compact' && renderCompactView(files)}
{viewMode === 'detailed' && renderDetailedView(files)}
</div>
)}
</ScrollArea>

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
import { GitBranch, GitCommit, Plus, Minus, RefreshCw, Check, X, ChevronDown, ChevronRight, Info, History, FileText, Mic, MicOff, Sparkles } from 'lucide-react';
import { GitBranch, GitCommit, Plus, Minus, RefreshCw, Check, X, ChevronDown, ChevronRight, Info, History, FileText, Mic, MicOff, Sparkles, Download, RotateCcw, Trash2, AlertTriangle, Upload } from 'lucide-react';
import { MicButton } from './MicButton.jsx';
import { authenticatedFetch } from '../utils/api';
@@ -24,6 +24,12 @@ function GitPanel({ selectedProject, isMobile }) {
const [expandedCommits, setExpandedCommits] = useState(new Set());
const [commitDiffs, setCommitDiffs] = useState({});
const [isGeneratingMessage, setIsGeneratingMessage] = useState(false);
const [remoteStatus, setRemoteStatus] = useState(null);
const [isFetching, setIsFetching] = useState(false);
const [isPulling, setIsPulling] = useState(false);
const [isPushing, setIsPushing] = useState(false);
const [isCommitAreaCollapsed, setIsCommitAreaCollapsed] = useState(isMobile); // Collapsed by default on mobile
const [confirmAction, setConfirmAction] = useState(null); // { type: 'discard|commit|pull|push', file?: string, message?: string }
const textareaRef = useRef(null);
const dropdownRef = useRef(null);
@@ -31,6 +37,7 @@ function GitPanel({ selectedProject, isMobile }) {
if (selectedProject) {
fetchGitStatus();
fetchBranches();
fetchRemoteStatus();
if (activeView === 'history') {
fetchRecentCommits();
}
@@ -105,6 +112,24 @@ function GitPanel({ selectedProject, isMobile }) {
}
};
const fetchRemoteStatus = async () => {
if (!selectedProject) return;
try {
const response = await authenticatedFetch(`/api/git/remote-status?project=${encodeURIComponent(selectedProject.name)}`);
const data = await response.json();
if (!data.error) {
setRemoteStatus(data);
} else {
setRemoteStatus(null);
}
} catch (error) {
console.error('Error fetching remote status:', error);
setRemoteStatus(null);
}
};
const switchBranch = async (branchName) => {
try {
const response = await authenticatedFetch('/api/git/checkout', {
@@ -161,6 +186,140 @@ function GitPanel({ selectedProject, isMobile }) {
}
};
const handleFetch = async () => {
setIsFetching(true);
try {
const response = await authenticatedFetch('/api/git/fetch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
project: selectedProject.name
})
});
const data = await response.json();
if (data.success) {
// Refresh status after successful fetch
fetchGitStatus();
fetchRemoteStatus();
} else {
console.error('Fetch failed:', data.error);
}
} catch (error) {
console.error('Error fetching from remote:', error);
} finally {
setIsFetching(false);
}
};
const handlePull = async () => {
setIsPulling(true);
try {
const response = await authenticatedFetch('/api/git/pull', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
project: selectedProject.name
})
});
const data = await response.json();
if (data.success) {
// Refresh status after successful pull
fetchGitStatus();
fetchRemoteStatus();
} else {
console.error('Pull failed:', data.error);
// TODO: Show user-friendly error message
}
} catch (error) {
console.error('Error pulling from remote:', error);
} finally {
setIsPulling(false);
}
};
const handlePush = async () => {
setIsPushing(true);
try {
const response = await authenticatedFetch('/api/git/push', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
project: selectedProject.name
})
});
const data = await response.json();
if (data.success) {
// Refresh status after successful push
fetchGitStatus();
fetchRemoteStatus();
} else {
console.error('Push failed:', data.error);
// TODO: Show user-friendly error message
}
} catch (error) {
console.error('Error pushing to remote:', error);
} finally {
setIsPushing(false);
}
};
const discardChanges = async (filePath) => {
try {
const response = await authenticatedFetch('/api/git/discard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
project: selectedProject.name,
file: filePath
})
});
const data = await response.json();
if (data.success) {
// Remove from selected files and refresh status
setSelectedFiles(prev => {
const newSet = new Set(prev);
newSet.delete(filePath);
return newSet;
});
fetchGitStatus();
} else {
console.error('Discard failed:', data.error);
}
} catch (error) {
console.error('Error discarding changes:', error);
}
};
const confirmAndExecute = async () => {
if (!confirmAction) return;
const { type, file, message } = confirmAction;
setConfirmAction(null);
try {
switch (type) {
case 'discard':
await discardChanges(file);
break;
case 'commit':
await handleCommit();
break;
case 'pull':
await handlePull();
break;
case 'push':
await handlePush();
break;
}
} catch (error) {
console.error(`Error executing ${type}:`, error);
}
};
const fetchFileDiff = async (filePath) => {
try {
const response = await authenticatedFetch(`/api/git/diff?project=${encodeURIComponent(selectedProject.name)}&file=${encodeURIComponent(filePath)}`);
@@ -292,6 +451,7 @@ function GitPanel({ selectedProject, isMobile }) {
setCommitMessage('');
setSelectedFiles(new Set());
fetchGitStatus();
fetchRemoteStatus();
} else {
console.error('Commit failed:', data.error);
}
@@ -384,39 +544,77 @@ function GitPanel({ selectedProject, isMobile }) {
return (
<div key={filePath} className="border-b border-gray-200 dark:border-gray-700 last:border-0">
<div className="flex items-center px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-800">
<div className={`flex items-center hover:bg-gray-50 dark:hover:bg-gray-800 ${isMobile ? 'px-2 py-1.5' : 'px-3 py-2'}`}>
<input
type="checkbox"
checked={isSelected}
onChange={() => toggleFileSelected(filePath)}
onClick={(e) => e.stopPropagation()}
className="mr-2 rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 dark:focus:ring-blue-400 dark:bg-gray-800 dark:checked:bg-blue-600"
className={`rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 dark:focus:ring-blue-400 dark:bg-gray-800 dark:checked:bg-blue-600 ${isMobile ? 'mr-1.5' : 'mr-2'}`}
/>
<div
className="flex items-center flex-1 cursor-pointer"
onClick={() => toggleFileExpanded(filePath)}
>
<div className="mr-2 p-0.5 hover:bg-gray-200 dark:hover:bg-gray-700 rounded">
{isExpanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
<div className={`p-0.5 hover:bg-gray-200 dark:hover:bg-gray-700 rounded ${isMobile ? 'mr-1' : 'mr-2'}`}>
<ChevronRight className={`w-3 h-3 transition-transform duration-200 ease-in-out ${isExpanded ? 'rotate-90' : 'rotate-0'}`} />
</div>
<span className={`flex-1 truncate ${isMobile ? 'text-xs' : 'text-sm'}`}>{filePath}</span>
<div className="flex items-center gap-1">
{(status === 'M' || status === 'D') && (
<button
onClick={(e) => {
e.stopPropagation();
setConfirmAction({
type: 'discard',
file: filePath,
message: `Discard all changes to "${filePath}"? This action cannot be undone.`
});
}}
className={`${isMobile ? 'px-2 py-1 text-xs' : 'p-1'} hover:bg-red-100 dark:hover:bg-red-900 rounded text-red-600 dark:text-red-400 font-medium flex items-center gap-1`}
title="Discard changes"
>
<Trash2 className={`${isMobile ? 'w-3 h-3' : 'w-3 h-3'}`} />
{isMobile && <span>Discard</span>}
</button>
)}
<span
className={`inline-flex items-center justify-center w-5 h-5 rounded text-xs font-bold border ${
status === 'M' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800' :
status === 'A' ? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300 border-green-200 dark:border-green-800' :
status === 'D' ? 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300 border-red-200 dark:border-red-800' :
'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300 border-gray-300 dark:border-gray-600'
}`}
title={getStatusLabel(status)}
>
{status}
</span>
</div>
<span className="flex-1 text-sm truncate">{filePath}</span>
<span
className={`inline-flex items-center justify-center w-5 h-5 rounded text-xs font-bold border ${
status === 'M' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800' :
status === 'A' ? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300 border-green-200 dark:border-green-800' :
status === 'D' ? 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300 border-red-200 dark:border-red-800' :
'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300 border-gray-300 dark:border-gray-600'
}`}
title={getStatusLabel(status)}
>
{status}
</span>
</div>
</div>
{isExpanded && diff && (
<div className="bg-gray-50 dark:bg-gray-900">
{isMobile && (
<div className="flex justify-end p-2 border-b border-gray-200 dark:border-gray-700">
<div className={`bg-gray-50 dark:bg-gray-900 transition-all duration-400 ease-in-out overflow-hidden ${
isExpanded && diff
? 'max-h-[600px] opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-1'
}`}>
{/* Operation header */}
<div className="flex items-center justify-between p-2 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<span
className={`inline-flex items-center justify-center w-5 h-5 rounded text-xs font-bold border ${
status === 'M' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800' :
status === 'A' ? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300 border-green-200 dark:border-green-800' :
status === 'D' ? 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300 border-red-200 dark:border-red-800' :
'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300 border-gray-300 dark:border-gray-600'
}`}
>
{status}
</span>
<span className="text-sm font-medium text-gray-900 dark:text-white">
{getStatusLabel(status)}
</span>
</div>
{isMobile && (
<button
onClick={(e) => {
e.stopPropagation();
@@ -427,13 +625,12 @@ function GitPanel({ selectedProject, isMobile }) {
>
{wrapText ? '↔️ Scroll' : '↩️ Wrap'}
</button>
</div>
)}
<div className="max-h-96 overflow-y-auto p-2">
{diff.split('\n').map((line, index) => renderDiffLine(line, index))}
)}
</div>
</div>
)}
<div className="max-h-96 overflow-y-auto p-2">
{diff && diff.split('\n').map((line, index) => renderDiffLine(line, index))}
</div>
</div>
</div>
);
};
@@ -449,14 +646,36 @@ function GitPanel({ selectedProject, isMobile }) {
return (
<div className="h-full flex flex-col bg-white dark:bg-gray-900">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className={`flex items-center justify-between border-b border-gray-200 dark:border-gray-700 ${isMobile ? 'px-3 py-2' : 'px-4 py-3'}`}>
<div className="relative" ref={dropdownRef}>
<button
onClick={() => setShowBranchDropdown(!showBranchDropdown)}
className="flex items-center space-x-2 px-3 py-1.5 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
className={`flex items-center hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors ${isMobile ? 'space-x-1 px-2 py-1' : 'space-x-2 px-3 py-1.5'}`}
>
<GitBranch className="w-4 h-4 text-gray-600 dark:text-gray-400" />
<span className="text-sm font-medium">{currentBranch}</span>
<GitBranch className={`text-gray-600 dark:text-gray-400 ${isMobile ? 'w-3 h-3' : 'w-4 h-4'}`} />
<div className="flex items-center gap-1">
<span className={`font-medium ${isMobile ? 'text-xs' : 'text-sm'}`}>{currentBranch}</span>
{/* Remote status indicators */}
{remoteStatus?.hasRemote && (
<div className="flex items-center gap-1 text-xs">
{remoteStatus.ahead > 0 && (
<span className="text-green-600 dark:text-green-400" title={`${remoteStatus.ahead} commit${remoteStatus.ahead !== 1 ? 's' : ''} ahead`}>
{remoteStatus.ahead}
</span>
)}
{remoteStatus.behind > 0 && (
<span className="text-blue-600 dark:text-blue-400" title={`${remoteStatus.behind} commit${remoteStatus.behind !== 1 ? 's' : ''} behind`}>
{remoteStatus.behind}
</span>
)}
{remoteStatus.isUpToDate && (
<span className="text-gray-500 dark:text-gray-400" title="Up to date with remote">
</span>
)}
</div>
)}
</div>
<ChevronDown className={`w-3 h-3 text-gray-500 transition-transform ${showBranchDropdown ? 'rotate-180' : ''}`} />
</button>
@@ -495,16 +714,69 @@ function GitPanel({ selectedProject, isMobile }) {
)}
</div>
<button
onClick={() => {
fetchGitStatus();
fetchBranches();
}}
disabled={isLoading}
className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-800 rounded"
>
<RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
</button>
<div className={`flex items-center ${isMobile ? 'gap-1' : 'gap-2'}`}>
{/* Remote action buttons - smart logic based on ahead/behind status */}
{remoteStatus?.hasRemote && !remoteStatus?.isUpToDate && (
<>
{/* Pull button - show when behind (primary action) */}
{remoteStatus.behind > 0 && (
<button
onClick={() => setConfirmAction({
type: 'pull',
message: `Pull ${remoteStatus.behind} commit${remoteStatus.behind !== 1 ? 's' : ''} from ${remoteStatus.remoteName}?`
})}
disabled={isPulling}
className="px-2 py-1 text-xs bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50 flex items-center gap-1"
title={`Pull ${remoteStatus.behind} commit${remoteStatus.behind !== 1 ? 's' : ''} from ${remoteStatus.remoteName}`}
>
<Download className={`w-3 h-3 ${isPulling ? 'animate-pulse' : ''}`} />
<span>{isPulling ? 'Pulling...' : `Pull ${remoteStatus.behind}`}</span>
</button>
)}
{/* Push button - show when ahead (primary action when ahead only) */}
{remoteStatus.ahead > 0 && (
<button
onClick={() => setConfirmAction({
type: 'push',
message: `Push ${remoteStatus.ahead} commit${remoteStatus.ahead !== 1 ? 's' : ''} to ${remoteStatus.remoteName}?`
})}
disabled={isPushing}
className="px-2 py-1 text-xs bg-orange-600 text-white rounded hover:bg-orange-700 disabled:opacity-50 flex items-center gap-1"
title={`Push ${remoteStatus.ahead} commit${remoteStatus.ahead !== 1 ? 's' : ''} to ${remoteStatus.remoteName}`}
>
<Upload className={`w-3 h-3 ${isPushing ? 'animate-pulse' : ''}`} />
<span>{isPushing ? 'Pushing...' : `Push ${remoteStatus.ahead}`}</span>
</button>
)}
{/* Fetch button - show when ahead only or when diverged (secondary action) */}
{(remoteStatus.ahead > 0 || (remoteStatus.behind > 0 && remoteStatus.ahead > 0)) && (
<button
onClick={handleFetch}
disabled={isFetching}
className="px-2 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 flex items-center gap-1"
title={`Fetch from ${remoteStatus.remoteName}`}
>
<RefreshCw className={`w-3 h-3 ${isFetching ? 'animate-spin' : ''}`} />
<span>{isFetching ? 'Fetching...' : 'Fetch'}</span>
</button>
)}
</>
)}
<button
onClick={() => {
fetchGitStatus();
fetchBranches();
fetchRemoteStatus();
}}
disabled={isLoading}
className={`hover:bg-gray-100 dark:hover:bg-gray-800 rounded ${isMobile ? 'p-1' : 'p-1.5'}`}
>
<RefreshCw className={`${isLoading ? 'animate-spin' : ''} ${isMobile ? 'w-3 h-3' : 'w-4 h-4'}`} />
</button>
</div>
</div>
{/* Git Repository Not Found Message */}
@@ -523,8 +795,12 @@ function GitPanel({ selectedProject, isMobile }) {
</div>
) : (
<>
{/* Tab Navigation - Only show when git is available */}
<div className="flex border-b border-gray-200 dark:border-gray-700">
{/* Tab Navigation - Only show when git is available and no files expanded */}
<div className={`flex border-b border-gray-200 dark:border-gray-700 transition-all duration-300 ease-in-out ${
expandedFiles.size === 0
? 'max-h-16 opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-2 overflow-hidden'
}`}>
<button
onClick={() => setActiveView('changes')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
@@ -556,68 +832,110 @@ function GitPanel({ selectedProject, isMobile }) {
{/* Changes View */}
{activeView === 'changes' && (
<>
{/* Commit Message Input */}
<div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className="relative">
<textarea
ref={textareaRef}
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
placeholder="Message (Ctrl+Enter to commit)"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 resize-none pr-20"
rows="3"
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
handleCommit();
}
}}
/>
<div className="absolute right-2 top-2 flex gap-1">
<button
onClick={generateCommitMessage}
disabled={selectedFiles.size === 0 || isGeneratingMessage}
className="p-1.5 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
title="Generate commit message"
>
{isGeneratingMessage ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : (
<Sparkles className="w-4 h-4" />
)}
</button>
<div style={{ display: 'none' }}>
<MicButton
onTranscript={(transcript) => setCommitMessage(transcript)}
mode="default"
className="p-1.5"
{/* Mobile Commit Toggle Button / Desktop Always Visible - Hide when files expanded */}
<div className={`transition-all duration-300 ease-in-out ${
expandedFiles.size === 0
? 'max-h-96 opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-2 overflow-hidden'
}`}>
{isMobile && isCommitAreaCollapsed ? (
<div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700">
<button
onClick={() => setIsCommitAreaCollapsed(false)}
className="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
<GitCommit className="w-4 h-4" />
<span>Commit {selectedFiles.size} file{selectedFiles.size !== 1 ? 's' : ''}</span>
<ChevronDown className="w-3 h-3" />
</button>
</div>
) : (
<>
{/* Commit Message Input */}
<div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
{/* Mobile collapse button */}
{isMobile && (
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium">Commit Changes</span>
<button
onClick={() => setIsCommitAreaCollapsed(true)}
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded"
>
<ChevronDown className="w-4 h-4 rotate-180" />
</button>
</div>
)}
<div className="relative">
<textarea
ref={textareaRef}
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
placeholder="Message (Ctrl+Enter to commit)"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 resize-none pr-20"
rows="3"
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
handleCommit();
}
}}
/>
<div className="absolute right-2 top-2 flex gap-1">
<button
onClick={generateCommitMessage}
disabled={selectedFiles.size === 0 || isGeneratingMessage}
className="p-1.5 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
title="Generate commit message"
>
{isGeneratingMessage ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : (
<Sparkles className="w-4 h-4" />
)}
</button>
<div style={{ display: 'none' }}>
<MicButton
onTranscript={(transcript) => setCommitMessage(transcript)}
mode="default"
className="p-1.5"
/>
</div>
</div>
</div>
<div className="flex items-center justify-between mt-2">
<span className="text-xs text-gray-500">
{selectedFiles.size} file{selectedFiles.size !== 1 ? 's' : ''} selected
</span>
<button
onClick={() => setConfirmAction({
type: 'commit',
message: `Commit ${selectedFiles.size} file${selectedFiles.size !== 1 ? 's' : ''} with message: "${commitMessage.trim()}"?`
})}
disabled={!commitMessage.trim() || selectedFiles.size === 0 || isCommitting}
className="px-3 py-1 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-1"
>
<Check className="w-3 h-3" />
<span>{isCommitting ? 'Committing...' : 'Commit'}</span>
</button>
</div>
</div>
</div>
<div className="flex items-center justify-between mt-2">
<span className="text-xs text-gray-500">
{selectedFiles.size} file{selectedFiles.size !== 1 ? 's' : ''} selected
</span>
<button
onClick={handleCommit}
disabled={!commitMessage.trim() || selectedFiles.size === 0 || isCommitting}
className="px-3 py-1 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-1"
>
<Check className="w-3 h-3" />
<span>{isCommitting ? 'Committing...' : 'Commit'}</span>
</button>
</div>
</>
)}
</div>
</>
)}
{/* File Selection Controls - Only show in changes view and when git is working */}
{/* File Selection Controls - Only show in changes view and when git is working and no files expanded */}
{activeView === 'changes' && gitStatus && !gitStatus.error && (
<div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<span className="text-xs text-gray-600 dark:text-gray-400">
{selectedFiles.size} of {(gitStatus?.modified?.length || 0) + (gitStatus?.added?.length || 0) + (gitStatus?.deleted?.length || 0) + (gitStatus?.untracked?.length || 0)} files selected
<div className={`border-b border-gray-200 dark:border-gray-700 flex items-center justify-between transition-all duration-300 ease-in-out ${isMobile ? 'px-3 py-1.5' : 'px-4 py-2'} ${
expandedFiles.size === 0
? 'max-h-16 opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-2 overflow-hidden'
}`}>
<span className={`text-gray-600 dark:text-gray-400 ${isMobile ? 'text-xs' : 'text-xs'}`}>
{selectedFiles.size} of {(gitStatus?.modified?.length || 0) + (gitStatus?.added?.length || 0) + (gitStatus?.deleted?.length || 0) + (gitStatus?.untracked?.length || 0)} {isMobile ? '' : 'files'} selected
</span>
<div className="flex gap-2">
<div className={`flex ${isMobile ? 'gap-1' : 'gap-2'}`}>
<button
onClick={() => {
const allFiles = new Set([
@@ -628,23 +946,23 @@ function GitPanel({ selectedProject, isMobile }) {
]);
setSelectedFiles(allFiles);
}}
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
className={`text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 ${isMobile ? 'text-xs' : 'text-xs'}`}
>
Select All
{isMobile ? 'All' : 'Select All'}
</button>
<span className="text-gray-300 dark:text-gray-600">|</span>
<button
onClick={() => setSelectedFiles(new Set())}
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
className={`text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 ${isMobile ? 'text-xs' : 'text-xs'}`}
>
Deselect All
{isMobile ? 'None' : 'Deselect All'}
</button>
</div>
</div>
)}
{/* Status Legend Toggle */}
{!gitStatus?.error && (
{/* Status Legend Toggle - Hide on mobile by default */}
{!gitStatus?.error && !isMobile && (
<div className="border-b border-gray-200 dark:border-gray-700">
<button
onClick={() => setShowLegend(!showLegend)}
@@ -793,6 +1111,78 @@ function GitPanel({ selectedProject, isMobile }) {
</div>
</div>
)}
{/* Confirmation Modal */}
{confirmAction && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setConfirmAction(null)} />
<div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full">
<div className="p-6">
<div className="flex items-center mb-4">
<div className={`p-2 rounded-full mr-3 ${
confirmAction.type === 'discard' ? 'bg-red-100 dark:bg-red-900' : 'bg-yellow-100 dark:bg-yellow-900'
}`}>
<AlertTriangle className={`w-5 h-5 ${
confirmAction.type === 'discard' ? 'text-red-600 dark:text-red-400' : 'text-yellow-600 dark:text-yellow-400'
}`} />
</div>
<h3 className="text-lg font-semibold">
{confirmAction.type === 'discard' ? 'Discard Changes' :
confirmAction.type === 'commit' ? 'Confirm Commit' :
confirmAction.type === 'pull' ? 'Confirm Pull' : 'Confirm Push'}
</h3>
</div>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-6">
{confirmAction.message}
</p>
<div className="flex justify-end space-x-3">
<button
onClick={() => setConfirmAction(null)}
className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md"
>
Cancel
</button>
<button
onClick={confirmAndExecute}
className={`px-4 py-2 text-sm text-white rounded-md ${
confirmAction.type === 'discard'
? 'bg-red-600 hover:bg-red-700'
: confirmAction.type === 'commit'
? 'bg-blue-600 hover:bg-blue-700'
: confirmAction.type === 'pull'
? 'bg-green-600 hover:bg-green-700'
: 'bg-orange-600 hover:bg-orange-700'
} flex items-center space-x-2`}
>
{confirmAction.type === 'discard' ? (
<>
<Trash2 className="w-4 h-4" />
<span>Discard</span>
</>
) : confirmAction.type === 'commit' ? (
<>
<Check className="w-4 h-4" />
<span>Commit</span>
</>
) : confirmAction.type === 'pull' ? (
<>
<Download className="w-4 h-4" />
<span>Pull</span>
</>
) : (
<>
<Upload className="w-4 h-4" />
<span>Push</span>
</>
)}
</button>
</div>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -5,6 +5,27 @@ import { ClipboardAddon } from '@xterm/addon-clipboard';
import { WebglAddon } from '@xterm/addon-webgl';
import 'xterm/css/xterm.css';
// CSS to remove xterm focus outline
const xtermStyles = `
.xterm .xterm-screen {
outline: none !important;
}
.xterm:focus .xterm-screen {
outline: none !important;
}
.xterm-screen:focus {
outline: none !important;
}
`;
// Inject styles
if (typeof document !== 'undefined') {
const styleSheet = document.createElement('style');
styleSheet.type = 'text/css';
styleSheet.innerText = xtermStyles;
document.head.appendChild(styleSheet);
}
// Global store for shell sessions to persist across tab switches
const shellSessions = new Map();
@@ -138,6 +159,14 @@ function Shell({ selectedProject, selectedSession, isActive }) {
setTimeout(() => {
if (fitAddon.current) {
fitAddon.current.fit();
// Send terminal size to backend after reattaching
if (ws.current && ws.current.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({
type: 'resize',
cols: terminal.current.cols,
rows: terminal.current.rows
}));
}
}
}, 100);
@@ -226,6 +255,13 @@ function Shell({ selectedProject, selectedSession, isActive }) {
terminal.current.open(terminalRef.current);
// Wait for terminal to be fully rendered, then fit
setTimeout(() => {
if (fitAddon.current) {
fitAddon.current.fit();
}
}, 50);
// Add keyboard shortcuts for copy/paste
terminal.current.attachCustomKeyEventHandler((event) => {
// Ctrl+C or Cmd+C for copy (when text is selected)
@@ -252,10 +288,18 @@ function Shell({ selectedProject, selectedSession, isActive }) {
return true;
});
// Ensure terminal takes full space
// Ensure terminal takes full space and notify backend of size
setTimeout(() => {
if (fitAddon.current) {
fitAddon.current.fit();
// Send terminal size to backend after fitting
if (terminal.current && ws.current && ws.current.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({
type: 'resize',
cols: terminal.current.cols,
rows: terminal.current.rows
}));
}
}
}, 100);
@@ -276,6 +320,14 @@ function Shell({ selectedProject, selectedSession, isActive }) {
if (fitAddon.current && terminal.current) {
setTimeout(() => {
fitAddon.current.fit();
// Send updated terminal size to backend after resize
if (ws.current && ws.current.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({
type: 'resize',
cols: terminal.current.cols,
rows: terminal.current.rows
}));
}
}, 50);
}
});
@@ -309,10 +361,18 @@ function Shell({ selectedProject, selectedSession, isActive }) {
useEffect(() => {
if (!isActive || !isInitialized) return;
// Fit terminal when tab becomes active
// Fit terminal when tab becomes active and notify backend
setTimeout(() => {
if (fitAddon.current) {
fitAddon.current.fit();
// Send terminal size to backend after tab activation
if (terminal.current && ws.current && ws.current.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({
type: 'resize',
cols: terminal.current.cols,
rows: terminal.current.rows
}));
}
}
}, 100);
}, [isActive, isInitialized]);
@@ -363,16 +423,38 @@ function Shell({ selectedProject, selectedSession, isActive }) {
setIsConnected(true);
setIsConnecting(false);
// Send initial setup with project path and session info
const initPayload = {
type: 'init',
projectPath: selectedProject.fullPath || selectedProject.path,
sessionId: selectedSession?.id,
hasSession: !!selectedSession
};
ws.current.send(JSON.stringify(initPayload));
// Wait for terminal to be ready, then fit and send dimensions
setTimeout(() => {
if (fitAddon.current && terminal.current) {
// Force a fit to ensure proper dimensions
fitAddon.current.fit();
// Wait a bit more for fit to complete, then send dimensions
setTimeout(() => {
const initPayload = {
type: 'init',
projectPath: selectedProject.fullPath || selectedProject.path,
sessionId: selectedSession?.id,
hasSession: !!selectedSession,
cols: terminal.current.cols,
rows: terminal.current.rows
};
ws.current.send(JSON.stringify(initPayload));
// Also send resize message immediately after init
setTimeout(() => {
if (terminal.current && ws.current && ws.current.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({
type: 'resize',
cols: terminal.current.cols,
rows: terminal.current.rows
}));
}
}, 100);
}, 50);
}
}, 200);
};
ws.current.onmessage = (event) => {
@@ -442,7 +524,7 @@ function Shell({ selectedProject, selectedSession, isActive }) {
}
return (
<div className="h-full flex flex-col bg-gray-900">
<div className="h-full flex flex-col bg-gray-900 w-full">
{/* Header */}
<div className="flex-shrink-0 bg-gray-800 border-b border-gray-700 px-4 py-2">
<div className="flex items-center justify-between">
@@ -494,7 +576,7 @@ function Shell({ selectedProject, selectedSession, isActive }) {
{/* Terminal */}
<div className="flex-1 p-2 overflow-hidden relative">
<div ref={terminalRef} className="h-full w-full" />
<div ref={terminalRef} className="h-full w-full focus:outline-none" style={{ outline: 'none' }} />
{/* Loading state */}
{!isInitialized && (

View File

@@ -3,7 +3,8 @@ import { ScrollArea } from './ui/scroll-area';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Input } from './ui/input';
import { FolderOpen, Folder, Plus, MessageSquare, Clock, ChevronDown, ChevronRight, Edit3, Check, X, Trash2, Settings, FolderPlus, RefreshCw, Sparkles, Edit2 } from 'lucide-react';
import { FolderOpen, Folder, Plus, MessageSquare, Clock, ChevronDown, ChevronRight, Edit3, Check, X, Trash2, Settings, FolderPlus, RefreshCw, Sparkles, Edit2, Star, Search } from 'lucide-react';
import { cn } from '../lib/utils';
import ClaudeLogo from './ClaudeLogo';
import { api } from '../utils/api';
@@ -61,10 +62,24 @@ function Sidebar({
const [additionalSessions, setAdditionalSessions] = useState({});
const [initialSessionsLoaded, setInitialSessionsLoaded] = useState(new Set());
const [currentTime, setCurrentTime] = useState(new Date());
const [projectSortOrder, setProjectSortOrder] = useState('name');
const [isRefreshing, setIsRefreshing] = useState(false);
const [editingSession, setEditingSession] = useState(null);
const [editingSessionName, setEditingSessionName] = useState('');
const [generatingSummary, setGeneratingSummary] = useState({});
const [searchFilter, setSearchFilter] = useState('');
// Starred projects state - persisted in localStorage
const [starredProjects, setStarredProjects] = useState(() => {
try {
const saved = localStorage.getItem('starredProjects');
return saved ? new Set(JSON.parse(saved)) : new Set();
} catch (error) {
console.error('Error loading starred projects:', error);
return new Set();
}
});
// Touch handler to prevent double-tap issues on iPad (only for buttons, not scroll areas)
const handleTouchClick = (callback) => {
@@ -114,6 +129,45 @@ function Sidebar({
}
}, [projects, isLoading]);
// Load project sort order from settings
useEffect(() => {
const loadSortOrder = () => {
try {
const savedSettings = localStorage.getItem('claude-tools-settings');
if (savedSettings) {
const settings = JSON.parse(savedSettings);
setProjectSortOrder(settings.projectSortOrder || 'name');
}
} catch (error) {
console.error('Error loading sort order:', error);
}
};
// Load initially
loadSortOrder();
// Listen for storage changes
const handleStorageChange = (e) => {
if (e.key === 'claude-tools-settings') {
loadSortOrder();
}
};
window.addEventListener('storage', handleStorageChange);
// Also check periodically when component is focused (for same-tab changes)
const checkInterval = setInterval(() => {
if (document.hasFocus()) {
loadSortOrder();
}
}, 1000);
return () => {
window.removeEventListener('storage', handleStorageChange);
clearInterval(checkInterval);
};
}, []);
const toggleProject = (projectName) => {
const newExpanded = new Set(expandedProjects);
if (newExpanded.has(projectName)) {
@@ -124,6 +178,71 @@ function Sidebar({
setExpandedProjects(newExpanded);
};
// Starred projects utility functions
const toggleStarProject = (projectName) => {
const newStarred = new Set(starredProjects);
if (newStarred.has(projectName)) {
newStarred.delete(projectName);
} else {
newStarred.add(projectName);
}
setStarredProjects(newStarred);
// Persist to localStorage
try {
localStorage.setItem('starredProjects', JSON.stringify([...newStarred]));
} catch (error) {
console.error('Error saving starred projects:', error);
}
};
const isProjectStarred = (projectName) => {
return starredProjects.has(projectName);
};
// Helper function to get all sessions for a project (initial + additional)
const getAllSessions = (project) => {
const initialSessions = project.sessions || [];
const additional = additionalSessions[project.name] || [];
return [...initialSessions, ...additional];
};
// Helper function to get the last activity date for a project
const getProjectLastActivity = (project) => {
const allSessions = getAllSessions(project);
if (allSessions.length === 0) {
return new Date(0); // Return epoch date for projects with no sessions
}
// Find the most recent session activity
const mostRecentDate = allSessions.reduce((latest, session) => {
const sessionDate = new Date(session.lastActivity);
return sessionDate > latest ? sessionDate : latest;
}, new Date(0));
return mostRecentDate;
};
// Combined sorting: starred projects first, then by selected order
const sortedProjects = [...projects].sort((a, b) => {
const aStarred = isProjectStarred(a.name);
const bStarred = isProjectStarred(b.name);
// First, sort by starred status
if (aStarred && !bStarred) return -1;
if (!aStarred && bStarred) return 1;
// For projects with same starred status, sort by selected order
if (projectSortOrder === 'date') {
// Sort by most recent activity (descending)
return getProjectLastActivity(b) - getProjectLastActivity(a);
} else {
// Sort by display name (user-defined) or fallback to name (ascending)
const nameA = a.displayName || a.name;
const nameB = b.displayName || b.name;
return nameA.localeCompare(nameB);
}
});
const startEditing = (project) => {
setEditingProject(project.name);
@@ -284,12 +403,17 @@ function Sidebar({
}
};
// Helper function to get all sessions for a project (initial + additional)
const getAllSessions = (project) => {
const initialSessions = project.sessions || [];
const additional = additionalSessions[project.name] || [];
return [...initialSessions, ...additional];
};
// Filter projects based on search input
const filteredProjects = sortedProjects.filter(project => {
if (!searchFilter.trim()) return true;
const searchLower = searchFilter.toLowerCase();
const displayName = (project.displayName || project.name).toLowerCase();
const projectName = project.name.toLowerCase();
// Search in both display name and actual project name/path
return displayName.includes(searchLower) || projectName.includes(searchLower);
});
return (
<div className="h-full flex flex-col bg-card md:select-none">
@@ -475,6 +599,30 @@ function Sidebar({
</div>
)}
{/* Search Filter */}
{projects.length > 0 && !isLoading && (
<div className="px-3 md:px-4 py-2 border-b border-border">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
type="text"
placeholder="Search projects..."
value={searchFilter}
onChange={(e) => setSearchFilter(e.target.value)}
className="pl-9 h-9 text-sm bg-muted/50 border-0 focus:bg-background focus:ring-1 focus:ring-primary/20"
/>
{searchFilter && (
<button
onClick={() => setSearchFilter('')}
className="absolute right-2 top-1/2 transform -translate-y-1/2 p-1 hover:bg-accent rounded"
>
<X className="w-3 h-3 text-muted-foreground" />
</button>
)}
</div>
</div>
)}
{/* Projects List */}
<ScrollArea className="flex-1 md:px-2 md:py-3 overflow-y-auto overscroll-contain">
<div className="md:space-y-1 pb-safe-area-inset-bottom">
@@ -498,10 +646,21 @@ function Sidebar({
Run Claude CLI in a project directory to get started
</p>
</div>
) : filteredProjects.length === 0 ? (
<div className="text-center py-12 md:py-8 px-4">
<div className="w-12 h-12 bg-muted rounded-lg flex items-center justify-center mx-auto mb-4 md:mb-3">
<Search className="w-6 h-6 text-muted-foreground" />
</div>
<h3 className="text-base font-medium text-foreground mb-2 md:mb-1">No matching projects</h3>
<p className="text-sm text-muted-foreground">
Try adjusting your search term
</p>
</div>
) : (
projects.map((project) => {
filteredProjects.map((project) => {
const isExpanded = expandedProjects.has(project.name);
const isSelected = selectedProject?.name === project.name;
const isStarred = isProjectStarred(project.name);
return (
<div key={project.name} className="md:space-y-1">
@@ -512,7 +671,8 @@ function Sidebar({
<div
className={cn(
"p-3 mx-3 my-1 rounded-lg bg-card border border-border/50 active:scale-[0.98] transition-all duration-150",
isSelected && "bg-primary/5 border-primary/20"
isSelected && "bg-primary/5 border-primary/20",
isStarred && !isSelected && "bg-yellow-50/50 dark:bg-yellow-900/5 border-yellow-200/30 dark:border-yellow-800/30"
)}
onClick={() => {
// On mobile, just toggle the folder - don't select the project
@@ -594,6 +754,28 @@ function Sidebar({
</>
) : (
<>
{/* Star button */}
<button
className={cn(
"w-8 h-8 rounded-lg flex items-center justify-center active:scale-90 transition-all duration-150 border",
isStarred
? "bg-yellow-500/10 dark:bg-yellow-900/30 border-yellow-200 dark:border-yellow-800"
: "bg-gray-500/10 dark:bg-gray-900/30 border-gray-200 dark:border-gray-800"
)}
onClick={(e) => {
e.stopPropagation();
toggleStarProject(project.name);
}}
onTouchEnd={handleTouchClick(() => toggleStarProject(project.name))}
title={isStarred ? "Remove from favorites" : "Add to favorites"}
>
<Star className={cn(
"w-4 h-4 transition-colors",
isStarred
? "text-yellow-600 dark:text-yellow-400 fill-current"
: "text-gray-600 dark:text-gray-400"
)} />
</button>
{getAllSessions(project).length === 0 && (
<button
className="w-8 h-8 rounded-lg bg-red-500/10 dark:bg-red-900/30 flex items-center justify-center active:scale-90 border border-red-200 dark:border-red-800"
@@ -635,7 +817,8 @@ function Sidebar({
variant="ghost"
className={cn(
"hidden md:flex w-full justify-between p-2 h-auto font-normal hover:bg-accent/50",
isSelected && "bg-accent text-accent-foreground"
isSelected && "bg-accent text-accent-foreground",
isStarred && !isSelected && "bg-yellow-50/50 dark:bg-yellow-900/10 hover:bg-yellow-100/50 dark:hover:bg-yellow-900/20"
)}
onClick={() => {
// Desktop behavior: select project and toggle
@@ -722,6 +905,27 @@ function Sidebar({
</>
) : (
<>
{/* Star button */}
<div
className={cn(
"w-6 h-6 opacity-0 group-hover:opacity-100 transition-all duration-200 flex items-center justify-center rounded cursor-pointer touch:opacity-100",
isStarred
? "hover:bg-yellow-50 dark:hover:bg-yellow-900/20 opacity-100"
: "hover:bg-accent"
)}
onClick={(e) => {
e.stopPropagation();
toggleStarProject(project.name);
}}
title={isStarred ? "Remove from favorites" : "Add to favorites"}
>
<Star className={cn(
"w-3 h-3 transition-colors",
isStarred
? "text-yellow-600 dark:text-yellow-400 fill-current"
: "text-muted-foreground"
)} />
</div>
<div
className="w-6 h-6 opacity-0 group-hover:opacity-100 transition-all duration-200 hover:bg-accent flex items-center justify-center rounded cursor-pointer touch:opacity-100"
onClick={(e) => {

File diff suppressed because it is too large Load Diff

View File

@@ -32,9 +32,31 @@ export const ThemeProvider = ({ children }) => {
if (isDarkMode) {
document.documentElement.classList.add('dark');
localStorage.setItem('theme', 'dark');
// Update iOS status bar style and theme color for dark mode
const statusBarMeta = document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]');
if (statusBarMeta) {
statusBarMeta.setAttribute('content', 'black-translucent');
}
const themeColorMeta = document.querySelector('meta[name="theme-color"]');
if (themeColorMeta) {
themeColorMeta.setAttribute('content', '#0c1117'); // Dark background color (hsl(222.2 84% 4.9%))
}
} else {
document.documentElement.classList.remove('dark');
localStorage.setItem('theme', 'light');
// Update iOS status bar style and theme color for light mode
const statusBarMeta = document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]');
if (statusBarMeta) {
statusBarMeta.setAttribute('content', 'default');
}
const themeColorMeta = document.querySelector('meta[name="theme-color"]');
if (themeColorMeta) {
themeColorMeta.setAttribute('content', '#ffffff'); // Light background color
}
}
}, [isDarkMode]);

View File

@@ -64,7 +64,7 @@
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
--ring: 217.2 91.2% 59.8%;
}
}
@@ -99,8 +99,12 @@
transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);
}
/* Color transitions for theme switching */
* {
/* Color transitions for theme switching - exclude interactive elements */
body, div, section, article, aside, header, footer, nav, main,
h1, h2, h3, h4, h5, h6, p, span, blockquote,
ul, ol, li, dl, dt, dd,
table, thead, tbody, tfoot, tr, td, th,
form, fieldset, legend, label {
transition: background-color 200ms ease-in-out,
border-color 200ms ease-in-out,
color 200ms ease-in-out;