5 Commits

12 changed files with 724 additions and 95 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "claude-code-ui",
"version": "1.7.0",
"version": "1.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-code-ui",
"version": "1.7.0",
"version": "1.8.0",
"license": "MIT",
"dependencies": {
"@codemirror/lang-css": "^6.3.1",

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-ui",
"version": "v1.8.0",
"version": "1.8.1",
"description": "A web-based UI for Claude Code CLI",
"type": "module",
"main": "server/index.js",

View File

@@ -301,6 +301,66 @@ app.post('/api/projects/create', authenticateToken, async (req, res) => {
}
});
// Browse filesystem endpoint for project suggestions - uses existing getFileTree
app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
try {
const { path: dirPath } = req.query;
// Default to home directory if no path provided
const homeDir = os.homedir();
let targetPath = dirPath ? dirPath.replace('~', homeDir) : homeDir;
// Resolve and normalize the path
targetPath = path.resolve(targetPath);
// Security check - ensure path is accessible
try {
await fs.promises.access(targetPath);
const stats = await fs.promises.stat(targetPath);
if (!stats.isDirectory()) {
return res.status(400).json({ error: 'Path is not a directory' });
}
} catch (err) {
return res.status(404).json({ error: 'Directory not accessible' });
}
// Use existing getFileTree function with shallow depth (only direct children)
const fileTree = await getFileTree(targetPath, 1, 0, false); // maxDepth=1, showHidden=false
// Filter only directories and format for suggestions
const directories = fileTree
.filter(item => item.type === 'directory')
.map(item => ({
path: item.path,
name: item.name,
type: 'directory'
}))
.slice(0, 20); // Limit results
// Add common directories if browsing home directory
const suggestions = [];
if (targetPath === homeDir) {
const commonDirs = ['Desktop', 'Documents', 'Projects', 'Development', 'Dev', 'Code', 'workspace'];
const existingCommon = directories.filter(dir => commonDirs.includes(dir.name));
const otherDirs = directories.filter(dir => !commonDirs.includes(dir.name));
suggestions.push(...existingCommon, ...otherDirs);
} else {
suggestions.push(...directories);
}
res.json({
path: targetPath,
suggestions: suggestions
});
} catch (error) {
console.error('Error browsing filesystem:', error);
res.status(500).json({ error: 'Failed to browse filesystem' });
}
});
// Read file content endpoint
app.get('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
try {

View File

@@ -532,7 +532,7 @@ async function getSessions(projectName, limit = 5, offset = 0) {
return { sessions: [], hasMore: false, total: 0 };
}
// For performance, get file stats to sort by modification time
// Sort files by modification time (newest first)
const filesWithStats = await Promise.all(
jsonlFiles.map(async (file) => {
const filePath = path.join(projectDir, file);
@@ -540,40 +540,97 @@ async function getSessions(projectName, limit = 5, offset = 0) {
return { file, mtime: stats.mtime };
})
);
// Sort files by modification time (newest first) for better performance
filesWithStats.sort((a, b) => b.mtime - a.mtime);
const allSessions = new Map();
let processedCount = 0;
const allEntries = [];
const uuidToSessionMap = new Map();
// Process files in order of modification time
// Collect all sessions and entries from all files
for (const { file } of filesWithStats) {
const jsonlFile = path.join(projectDir, file);
const sessions = await parseJsonlSessions(jsonlFile);
const result = await parseJsonlSessions(jsonlFile);
// Merge sessions, avoiding duplicates by session ID
sessions.forEach(session => {
result.sessions.forEach(session => {
if (!allSessions.has(session.id)) {
allSessions.set(session.id, session);
}
});
processedCount++;
allEntries.push(...result.entries);
// Early exit optimization: if we have enough sessions and processed recent files
if (allSessions.size >= (limit + offset) * 2 && processedCount >= Math.min(3, filesWithStats.length)) {
// Early exit optimization for large projects
if (allSessions.size >= (limit + offset) * 2 && allEntries.length >= Math.min(3, filesWithStats.length)) {
break;
}
}
// Convert to array and sort by last activity
const sortedSessions = Array.from(allSessions.values()).sort((a, b) =>
new Date(b.lastActivity) - new Date(a.lastActivity)
);
// Build UUID-to-session mapping for timeline detection
allEntries.forEach(entry => {
if (entry.uuid && entry.sessionId) {
uuidToSessionMap.set(entry.uuid, entry.sessionId);
}
});
const total = sortedSessions.length;
const paginatedSessions = sortedSessions.slice(offset, offset + limit);
// Group sessions by first user message ID
const sessionGroups = new Map(); // firstUserMsgId -> { latestSession, allSessions[] }
const sessionToFirstUserMsgId = new Map(); // sessionId -> firstUserMsgId
// Find the first user message for each session
allEntries.forEach(entry => {
if (entry.sessionId && entry.type === 'user' && entry.parentUuid === null && entry.uuid) {
// This is a first user message in a session (parentUuid is null)
const firstUserMsgId = entry.uuid;
if (!sessionToFirstUserMsgId.has(entry.sessionId)) {
sessionToFirstUserMsgId.set(entry.sessionId, firstUserMsgId);
const session = allSessions.get(entry.sessionId);
if (session) {
if (!sessionGroups.has(firstUserMsgId)) {
sessionGroups.set(firstUserMsgId, {
latestSession: session,
allSessions: [session]
});
} else {
const group = sessionGroups.get(firstUserMsgId);
group.allSessions.push(session);
// Update latest session if this one is more recent
if (new Date(session.lastActivity) > new Date(group.latestSession.lastActivity)) {
group.latestSession = session;
}
}
}
}
}
});
// Collect all sessions that don't belong to any group (standalone sessions)
const groupedSessionIds = new Set();
sessionGroups.forEach(group => {
group.allSessions.forEach(session => groupedSessionIds.add(session.id));
});
const standaloneSessionsArray = Array.from(allSessions.values())
.filter(session => !groupedSessionIds.has(session.id));
// Combine grouped sessions (only show latest from each group) + standalone sessions
const latestFromGroups = Array.from(sessionGroups.values()).map(group => {
const session = { ...group.latestSession };
// Add metadata about grouping
if (group.allSessions.length > 1) {
session.isGrouped = true;
session.groupSize = group.allSessions.length;
session.groupSessions = group.allSessions.map(s => s.id);
}
return session;
});
const visibleSessions = [...latestFromGroups, ...standaloneSessionsArray]
.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
const total = visibleSessions.length;
const paginatedSessions = visibleSessions.slice(offset, offset + limit);
const hasMore = offset + limit < total;
return {
@@ -591,6 +648,7 @@ async function getSessions(projectName, limit = 5, offset = 0) {
async function parseJsonlSessions(filePath) {
const sessions = new Map();
const entries = [];
try {
const fileStream = fsSync.createReadStream(filePath);
@@ -599,14 +657,11 @@ async function parseJsonlSessions(filePath) {
crlfDelay: Infinity
});
// console.log(`[JSONL Parser] Reading file: ${filePath}`);
let lineCount = 0;
for await (const line of rl) {
if (line.trim()) {
lineCount++;
try {
const entry = JSON.parse(line);
entries.push(entry);
if (entry.sessionId) {
if (!sessions.has(entry.sessionId)) {
@@ -621,43 +676,37 @@ async function parseJsonlSessions(filePath) {
const session = sessions.get(entry.sessionId);
// Update summary if this is a summary entry
// Update summary from summary entries or first user message
if (entry.type === 'summary' && entry.summary) {
session.summary = entry.summary;
} else if (entry.message?.role === 'user' && entry.message?.content && session.summary === 'New Session') {
// Use first user message as summary if no summary entry exists
const content = entry.message.content;
if (typeof content === 'string' && content.length > 0) {
// Skip command messages that start with <command-name>
if (!content.startsWith('<command-name>')) {
session.summary = content.length > 50 ? content.substring(0, 50) + '...' : content;
}
if (typeof content === 'string' && content.length > 0 && !content.startsWith('<command-name>')) {
session.summary = content.length > 50 ? content.substring(0, 50) + '...' : content;
}
}
// Count messages instead of storing them all
session.messageCount = (session.messageCount || 0) + 1;
session.messageCount++;
// Update last activity
if (entry.timestamp) {
session.lastActivity = new Date(entry.timestamp);
}
}
} catch (parseError) {
console.warn(`[JSONL Parser] Error parsing line ${lineCount}:`, parseError.message);
// Skip malformed lines silently
}
}
}
// console.log(`[JSONL Parser] Processed ${lineCount} lines, found ${sessions.size} sessions`);
return {
sessions: Array.from(sessions.values()),
entries: entries
};
} catch (error) {
console.error('Error reading JSONL file:', error);
return { sessions: [], entries: [] };
}
// Convert Map to Array and sort by last activity
return Array.from(sessions.values()).sort((a, b) =>
new Date(b.lastActivity) - new Date(a.lastActivity)
);
}
// Get messages for a specific session with pagination support

View File

@@ -23,7 +23,7 @@ import { BrowserRouter as Router, Routes, Route, useNavigate, useParams } from '
import Sidebar from './components/Sidebar';
import MainContent from './components/MainContent';
import MobileNav from './components/MobileNav';
import ToolsSettings from './components/ToolsSettings';
import Settings from './components/Settings';
import QuickSettingsPanel from './components/QuickSettingsPanel';
import { ThemeProvider } from './contexts/ThemeContext';
@@ -52,7 +52,7 @@ function AppContent() {
const [sidebarOpen, setSidebarOpen] = useState(false);
const [isLoadingProjects, setIsLoadingProjects] = useState(true);
const [isInputFocused, setIsInputFocused] = useState(false);
const [showToolsSettings, setShowToolsSettings] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [showQuickSettings, setShowQuickSettings] = useState(false);
const [autoExpandTools, setAutoExpandTools] = useState(() => {
const saved = localStorage.getItem('autoExpandTools');
@@ -556,7 +556,7 @@ function AppContent() {
onProjectDelete={handleProjectDelete}
isLoading={isLoadingProjects}
onRefresh={handleSidebarRefresh}
onShowSettings={() => setShowToolsSettings(true)}
onShowSettings={() => setShowSettings(true)}
updateAvailable={updateAvailable}
latestVersion={latestVersion}
currentVersion={currentVersion}
@@ -584,9 +584,10 @@ function AppContent() {
}}
/>
<div
className={`relative w-[85vw] max-w-sm sm:w-80 bg-card border-r border-border h-full transform transition-transform duration-150 ease-out ${
className={`relative w-[85vw] max-w-sm sm:w-80 bg-card border-r border-border transform transition-transform duration-150 ease-out ${
sidebarOpen ? 'translate-x-0' : '-translate-x-full'
}`}
style={{ height: 'calc(100vh - 80px)' }}
onClick={(e) => e.stopPropagation()}
onTouchStart={(e) => e.stopPropagation()}
>
@@ -601,7 +602,7 @@ function AppContent() {
onProjectDelete={handleProjectDelete}
isLoading={isLoadingProjects}
onRefresh={handleSidebarRefresh}
onShowSettings={() => setShowToolsSettings(true)}
onShowSettings={() => setShowSettings(true)}
updateAvailable={updateAvailable}
latestVersion={latestVersion}
currentVersion={currentVersion}
@@ -629,7 +630,7 @@ function AppContent() {
onSessionInactive={markSessionAsInactive}
onReplaceTemporarySession={replaceTemporarySession}
onNavigateToSession={(sessionId) => navigate(`/session/${sessionId}`)}
onShowSettings={() => setShowToolsSettings(true)}
onShowSettings={() => setShowSettings(true)}
autoExpandTools={autoExpandTools}
showRawParameters={showRawParameters}
autoScrollToBottom={autoScrollToBottom}
@@ -674,10 +675,10 @@ function AppContent() {
/>
)}
{/* Tools Settings Modal */}
<ToolsSettings
isOpen={showToolsSettings}
onClose={() => setShowToolsSettings(false)}
{/* Settings Modal */}
<Settings
isOpen={showSettings}
onClose={() => setShowSettings(false)}
projects={projects}
/>

View File

@@ -2017,6 +2017,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
// When resuming a session, Claude CLI creates a new session instead of resuming.
// We detect this by checking for system/init messages with session_id that differs
// from our current session. When found, we need to switch the user to the new session.
// This works exactly like new session detection - preserve messages during navigation.
if (latestMessage.data.type === 'system' &&
latestMessage.data.subtype === 'init' &&
latestMessage.data.session_id &&
@@ -2029,6 +2030,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
});
// Mark this as a system-initiated session change to preserve messages
// This works exactly like new session init - messages stay visible during navigation
setIsSystemSessionChange(true);
// Switch to the new session using React Router navigation
@@ -2743,7 +2745,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
// Get tools settings from localStorage based on provider
const getToolsSettings = () => {
try {
const settingsKey = provider === 'cursor' ? 'cursor-tools-settings' : 'claude-tools-settings';
const settingsKey = provider === 'cursor' ? 'cursor-tools-settings' : 'claude-settings';
const savedSettings = safeLocalStorage.getItem(settingsKey);
if (savedSettings) {
return JSON.parse(savedSettings);

View File

@@ -15,7 +15,7 @@ import React, { useState, useEffect } from 'react';
import ChatInterface from './ChatInterface';
import FileTree from './FileTree';
import CodeEditor from './CodeEditor';
import Shell from './Shell';
import StandaloneShell from './StandaloneShell';
import GitPanel from './GitPanel';
import ErrorBoundary from './ErrorBoundary';
import ClaudeLogo from './ClaudeLogo';
@@ -426,10 +426,11 @@ function MainContent({
<FileTree selectedProject={selectedProject} />
</div>
<div className={`h-full overflow-hidden ${activeTab === 'shell' ? 'block' : 'hidden'}`}>
<Shell
selectedProject={selectedProject}
selectedSession={selectedSession}
<StandaloneShell
project={selectedProject}
session={selectedSession}
isActive={activeTab === 'shell'}
showHeader={false}
/>
</div>
<div className={`h-full overflow-hidden ${activeTab === 'git' ? 'block' : 'hidden'}`}>

View File

@@ -2,11 +2,14 @@ import { useState, useEffect } from 'react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Badge } from './ui/badge';
import { X, Plus, Settings, Shield, AlertTriangle, Moon, Sun, Server, Edit3, Trash2, Globe, Terminal, Zap, FolderOpen } from 'lucide-react';
import { X, Plus, Settings as SettingsIcon, Shield, AlertTriangle, Moon, Sun, Server, Edit3, Trash2, Globe, Terminal, Zap, FolderOpen, LogIn } from 'lucide-react';
import { useTheme } from '../contexts/ThemeContext';
import { useTasksSettings } from '../contexts/TasksSettingsContext';
import StandaloneShell from './StandaloneShell';
import ClaudeLogo from './ClaudeLogo';
import CursorLogo from './CursorLogo';
function ToolsSettings({ isOpen, onClose, projects = [] }) {
function Settings({ isOpen, onClose, projects = [] }) {
const { isDarkMode, toggleDarkMode } = useTheme();
const {
tasksEnabled,
@@ -59,6 +62,11 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
const [newCursorCommand, setNewCursorCommand] = useState('');
const [newCursorDisallowedCommand, setNewCursorDisallowedCommand] = useState('');
const [cursorMcpServers, setCursorMcpServers] = useState([]);
// Login modal states
const [showLoginModal, setShowLoginModal] = useState(false);
const [loginProvider, setLoginProvider] = useState(''); // 'claude' or 'cursor'
const [selectedProject, setSelectedProject] = useState(null);
// Common tool patterns for Claude
const commonTools = [
'Bash(git log:*)',
@@ -325,7 +333,7 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
try {
// Load Claude settings from localStorage
const savedSettings = localStorage.getItem('claude-tools-settings');
const savedSettings = localStorage.getItem('claude-settings');
if (savedSettings) {
const settings = JSON.parse(savedSettings);
@@ -371,6 +379,26 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
}
};
// Login handlers
const handleClaudeLogin = () => {
setLoginProvider('claude');
setSelectedProject(projects?.[0] || { name: 'default', fullPath: process.cwd() });
setShowLoginModal(true);
};
const handleCursorLogin = () => {
setLoginProvider('cursor');
setSelectedProject(projects?.[0] || { name: 'default', fullPath: process.cwd() });
setShowLoginModal(true);
};
const handleLoginComplete = (exitCode) => {
if (exitCode === 0) {
// Login successful - could show a success message here
}
setShowLoginModal(false);
};
const saveSettings = () => {
setIsSaving(true);
setSaveStatus(null);
@@ -394,7 +422,7 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
};
// Save to localStorage
localStorage.setItem('claude-tools-settings', JSON.stringify(claudeSettings));
localStorage.setItem('claude-settings', JSON.stringify(claudeSettings));
localStorage.setItem('cursor-tools-settings', JSON.stringify(cursorSettings));
setSaveStatus('success');
@@ -600,7 +628,7 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
<div className="bg-background border border-border md:rounded-lg shadow-xl w-full md:max-w-4xl h-full md:h-[90vh] flex flex-col">
<div className="flex items-center justify-between p-4 md:p-6 border-b border-border flex-shrink-0">
<div className="flex items-center gap-3">
<Settings className="w-5 h-5 md:w-6 md:h-6 text-blue-600" />
<SettingsIcon className="w-5 h-5 md:w-6 md:h-6 text-blue-600" />
<h2 className="text-lg md:text-xl font-semibold text-foreground">
Settings
</h2>
@@ -739,7 +767,10 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
: 'border-transparent text-muted-foreground hover:text-foreground'
}`}
>
Claude Tools
<div className="flex items-center gap-2">
<ClaudeLogo className="w-4 h-4" />
<span>Claude</span>
</div>
</button>
<button
onClick={() => setToolsProvider('cursor')}
@@ -749,12 +780,15 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
: 'border-transparent text-muted-foreground hover:text-foreground'
}`}
>
Cursor Tools
<div className="flex items-center gap-2">
<CursorLogo className="w-4 h-4" />
<span>Cursor</span>
</div>
</button>
</div>
</div>
{/* Claude Tools Content */}
{/* Claude Content */}
{toolsProvider === 'claude' && (
<div className="space-y-6 md:space-y-8">
@@ -786,6 +820,36 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
</div>
</div>
{/* Claude Login */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<LogIn className="w-5 h-5 text-blue-500" />
<h3 className="text-lg font-medium text-foreground">
Authentication
</h3>
</div>
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex items-center justify-between">
<div>
<div className="font-medium text-blue-900 dark:text-blue-100">
Claude CLI Login
</div>
<div className="text-sm text-blue-700 dark:text-blue-300">
Sign in to your Claude account to enable AI features
</div>
</div>
<Button
onClick={handleClaudeLogin}
className="bg-blue-600 hover:bg-blue-700 text-white"
size="sm"
>
<LogIn className="w-4 h-4 mr-2" />
Login
</Button>
</div>
</div>
</div>
{/* Allowed Tools */}
<div className="space-y-4">
<div className="flex items-center gap-3">
@@ -1484,7 +1548,7 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
</div>
)}
{/* Cursor Tools Content */}
{/* Cursor Content */}
{toolsProvider === 'cursor' && (
<div className="space-y-6 md:space-y-8">
@@ -1516,6 +1580,36 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
</div>
</div>
{/* Cursor Login */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<LogIn className="w-5 h-5 text-purple-500" />
<h3 className="text-lg font-medium text-foreground">
Authentication
</h3>
</div>
<div className="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg p-4">
<div className="flex items-center justify-between">
<div>
<div className="font-medium text-purple-900 dark:text-purple-100">
Cursor CLI Login
</div>
<div className="text-sm text-purple-700 dark:text-purple-300">
Sign in to your Cursor account to enable AI features
</div>
</div>
<Button
onClick={handleCursorLogin}
className="bg-purple-600 hover:bg-purple-700 text-white"
size="sm"
>
<LogIn className="w-4 h-4 mr-2" />
Login
</Button>
</div>
</div>
</div>
{/* Allowed Shell Commands */}
<div className="space-y-4">
<div className="flex items-center gap-3">
@@ -1895,8 +1989,35 @@ function ToolsSettings({ isOpen, onClose, projects = [] }) {
</div>
</div>
</div>
{/* Login Modal */}
{showLoginModal && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-4xl h-3/4 flex flex-col">
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{loginProvider === 'claude' ? 'Claude CLI Login' : 'Cursor CLI Login'}
</h3>
<button
onClick={() => setShowLoginModal(false)}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
>
<X className="w-6 h-6" />
</button>
</div>
<div className="flex-1 overflow-hidden">
<StandaloneShell
project={selectedProject}
command={loginProvider === 'claude' ? 'claude /login' : 'cursor-agent login'}
onComplete={handleLoginComplete}
showHeader={false}
/>
</div>
</div>
</div>
)}
</div>
);
}
export default ToolsSettings;
export default Settings;

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { ScrollArea } from './ui/scroll-area';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
@@ -72,6 +72,10 @@ function Sidebar({
const [editingSessionName, setEditingSessionName] = useState('');
const [generatingSummary, setGeneratingSummary] = useState({});
const [searchFilter, setSearchFilter] = useState('');
const [showPathDropdown, setShowPathDropdown] = useState(false);
const [pathList, setPathList] = useState([]);
const [filteredPaths, setFilteredPaths] = useState([]);
const [selectedPathIndex, setSelectedPathIndex] = useState(-1);
// TaskMaster context
const { setCurrentProject, mcpServerStatus } = useTaskMaster();
@@ -141,7 +145,7 @@ function Sidebar({
useEffect(() => {
const loadSortOrder = () => {
try {
const savedSettings = localStorage.getItem('claude-tools-settings');
const savedSettings = localStorage.getItem('claude-settings');
if (savedSettings) {
const settings = JSON.parse(savedSettings);
setProjectSortOrder(settings.projectSortOrder || 'name');
@@ -156,7 +160,7 @@ function Sidebar({
// Listen for storage changes
const handleStorageChange = (e) => {
if (e.key === 'claude-tools-settings') {
if (e.key === 'claude-settings') {
loadSortOrder();
}
};
@@ -176,6 +180,124 @@ function Sidebar({
};
}, []);
// Load available paths for suggestions
useEffect(() => {
const loadPaths = async () => {
try {
// Get recent paths from localStorage
const recentPaths = JSON.parse(localStorage.getItem('recentProjectPaths') || '[]');
// Load common/home directory paths
const response = await api.browseFilesystem();
const data = await response.json();
if (data.suggestions) {
const homePaths = data.suggestions.map(s => ({ name: s.name, path: s.path }));
const allPaths = [...recentPaths.map(path => ({ name: path.split('/').pop(), path })), ...homePaths];
setPathList(allPaths);
} else {
setPathList(recentPaths.map(path => ({ name: path.split('/').pop(), path })));
}
} catch (error) {
console.error('Error loading paths:', error);
const recentPaths = JSON.parse(localStorage.getItem('recentProjectPaths') || '[]');
setPathList(recentPaths.map(path => ({ name: path.split('/').pop(), path })));
}
};
loadPaths();
}, []);
// Handle input change and path filtering with dynamic browsing (ChatInterface pattern + dynamic browsing)
useEffect(() => {
const inputValue = newProjectPath.trim();
if (inputValue.length === 0) {
setShowPathDropdown(false);
return;
}
// Show dropdown when user starts typing
setShowPathDropdown(true);
const updateSuggestions = async () => {
// First show filtered existing suggestions from pathList
const staticFiltered = pathList.filter(pathItem =>
pathItem.name.toLowerCase().includes(inputValue.toLowerCase()) ||
pathItem.path.toLowerCase().includes(inputValue.toLowerCase())
);
// Check if input looks like a directory path for dynamic browsing
const isDirPath = inputValue.includes('/') && inputValue.length > 1;
if (isDirPath) {
try {
let dirToSearch;
// Determine which directory to search
if (inputValue.endsWith('/')) {
// User typed "/home/simos/" - search inside /home/simos
dirToSearch = inputValue.slice(0, -1);
} else {
// User typed "/home/simos/con" - search inside /home/simos for items starting with "con"
const lastSlashIndex = inputValue.lastIndexOf('/');
dirToSearch = inputValue.substring(0, lastSlashIndex);
}
// Only search if we have a valid directory path (not root only)
if (dirToSearch && dirToSearch !== '') {
const response = await api.browseFilesystem(dirToSearch);
const data = await response.json();
if (data.suggestions) {
// Filter directories that match the current input
const partialName = inputValue.substring(inputValue.lastIndexOf('/') + 1);
const dynamicPaths = data.suggestions
.filter(suggestion => {
const dirName = suggestion.name;
return partialName ? dirName.toLowerCase().startsWith(partialName.toLowerCase()) : true;
})
.map(s => ({ name: s.name, path: s.path }))
.slice(0, 8);
// Combine static and dynamic suggestions, prioritize dynamic
const combined = [...dynamicPaths, ...staticFiltered].slice(0, 8);
setFilteredPaths(combined);
setSelectedPathIndex(-1);
return;
}
}
} catch (error) {
console.debug('Dynamic browsing failed:', error.message);
}
}
// Fallback to just static filtered suggestions
setFilteredPaths(staticFiltered.slice(0, 8));
setSelectedPathIndex(-1);
};
updateSuggestions();
}, [newProjectPath, pathList]);
// Select path from dropdown (ChatInterface pattern)
const selectPath = (pathItem) => {
setNewProjectPath(pathItem.path);
setShowPathDropdown(false);
setSelectedPathIndex(-1);
};
// Save path to recent paths
const saveToRecentPaths = (path) => {
try {
const recentPaths = JSON.parse(localStorage.getItem('recentProjectPaths') || '[]');
const updatedPaths = [path, ...recentPaths.filter(p => p !== path)].slice(0, 10);
localStorage.setItem('recentProjectPaths', JSON.stringify(updatedPaths));
} catch (error) {
console.error('Error saving recent paths:', error);
}
};
const toggleProject = (projectName) => {
const newExpanded = new Set(expandedProjects);
if (newExpanded.has(projectName)) {
@@ -347,8 +469,13 @@ function Sidebar({
if (response.ok) {
const result = await response.json();
// Save the path to recent paths before clearing
saveToRecentPaths(newProjectPath.trim());
setShowNewProject(false);
setNewProjectPath('');
setShowSuggestions(false);
// Refresh projects to show the new one
if (window.refreshProjects) {
@@ -371,6 +498,7 @@ function Sidebar({
const cancelNewProject = () => {
setShowNewProject(false);
setNewProjectPath('');
setShowSuggestions(false);
};
const loadMoreSessions = async (project) => {
@@ -526,17 +654,96 @@ function Sidebar({
<FolderPlus className="w-4 h-4" />
Create New Project
</div>
<Input
value={newProjectPath}
onChange={(e) => setNewProjectPath(e.target.value)}
placeholder="/path/to/project or relative/path"
className="text-sm focus:ring-2 focus:ring-primary/20"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') createNewProject();
if (e.key === 'Escape') cancelNewProject();
}}
/>
<div className="relative">
<Input
value={newProjectPath}
onChange={(e) => setNewProjectPath(e.target.value)}
placeholder="/path/to/project or relative/path"
className="text-sm focus:ring-2 focus:ring-primary/20"
autoFocus
onKeyDown={(e) => {
// Handle path dropdown navigation (ChatInterface pattern)
if (showPathDropdown && filteredPaths.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedPathIndex(prev =>
prev < filteredPaths.length - 1 ? prev + 1 : 0
);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedPathIndex(prev =>
prev > 0 ? prev - 1 : filteredPaths.length - 1
);
} else if (e.key === 'Enter') {
e.preventDefault();
if (selectedPathIndex >= 0) {
selectPath(filteredPaths[selectedPathIndex]);
} else if (filteredPaths.length > 0) {
selectPath(filteredPaths[0]);
} else {
createNewProject();
}
return;
} else if (e.key === 'Escape') {
e.preventDefault();
setShowPathDropdown(false);
return;
} else if (e.key === 'Tab') {
e.preventDefault();
if (selectedPathIndex >= 0) {
selectPath(filteredPaths[selectedPathIndex]);
} else if (filteredPaths.length > 0) {
selectPath(filteredPaths[0]);
}
return;
}
}
// Regular input handling
if (e.key === 'Enter') {
createNewProject();
}
if (e.key === 'Escape') {
cancelNewProject();
}
}}
/>
{/* Path dropdown (ChatInterface pattern) */}
{showPathDropdown && filteredPaths.length > 0 && (
<div className="absolute top-full left-0 right-0 mt-1 bg-popover border border-border rounded-md shadow-lg max-h-48 overflow-y-auto z-50">
{filteredPaths.map((pathItem, index) => (
<div
key={pathItem.path}
className={`px-3 py-2 cursor-pointer border-b border-border last:border-b-0 ${
index === selectedPathIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
}`}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
selectPath(pathItem);
}}
>
<div className="flex items-center gap-2">
<Folder className="w-3 h-3 text-muted-foreground flex-shrink-0" />
<div>
<div className="font-medium text-sm">{pathItem.name}</div>
<div className="text-xs text-muted-foreground font-mono">
{pathItem.path}
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
<div className="flex gap-2">
<Button
size="sm"
@@ -559,8 +766,8 @@ function Sidebar({
</div>
{/* Mobile Form - Simple Overlay */}
<div className="md:hidden fixed inset-0 z-50 bg-black/50 backdrop-blur-sm">
<div className="absolute bottom-0 left-0 right-0 bg-card rounded-t-lg border-t border-border p-4 space-y-4 animate-in slide-in-from-bottom duration-300">
<div className="md:hidden fixed inset-0 z-[70] bg-black/50 backdrop-blur-sm flex items-end justify-center px-4 pb-24">
<div className="w-full max-w-sm bg-card rounded-t-lg border-t border-border p-4 space-y-4 animate-in slide-in-from-bottom duration-300">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="w-6 h-6 bg-primary/10 rounded-md flex items-center justify-center">
@@ -580,17 +787,92 @@ function Sidebar({
</div>
<div className="space-y-3">
<Input
value={newProjectPath}
onChange={(e) => setNewProjectPath(e.target.value)}
placeholder="/path/to/project or relative/path"
className="text-sm h-10 rounded-md focus:border-primary transition-colors"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') createNewProject();
if (e.key === 'Escape') cancelNewProject();
}}
/>
<div className="relative">
<Input
value={newProjectPath}
onChange={(e) => setNewProjectPath(e.target.value)}
placeholder="/path/to/project or relative/path"
className="text-sm h-10 rounded-md focus:border-primary transition-colors"
autoFocus
onKeyDown={(e) => {
// Handle path dropdown navigation (same as desktop)
if (showPathDropdown && filteredPaths.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedPathIndex(prev =>
prev < filteredPaths.length - 1 ? prev + 1 : 0
);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedPathIndex(prev =>
prev > 0 ? prev - 1 : filteredPaths.length - 1
);
} else if (e.key === 'Enter') {
e.preventDefault();
if (selectedPathIndex >= 0) {
selectPath(filteredPaths[selectedPathIndex]);
} else if (filteredPaths.length > 0) {
selectPath(filteredPaths[0]);
} else {
createNewProject();
}
return;
} else if (e.key === 'Escape') {
e.preventDefault();
setShowPathDropdown(false);
return;
}
}
// Regular input handling
if (e.key === 'Enter') {
createNewProject();
}
if (e.key === 'Escape') {
cancelNewProject();
}
}}
style={{
fontSize: '16px', // Prevents zoom on iOS
WebkitAppearance: 'none'
}}
/>
{/* Mobile Path dropdown */}
{showPathDropdown && filteredPaths.length > 0 && (
<div className="absolute bottom-full left-0 right-0 mb-2 bg-popover border border-border rounded-md shadow-lg max-h-40 overflow-y-auto">
{filteredPaths.map((pathItem, index) => (
<div
key={pathItem.path}
className={`px-3 py-2.5 cursor-pointer border-b border-border last:border-b-0 active:scale-95 transition-all ${
index === selectedPathIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
}`}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
selectPath(pathItem);
}}
>
<div className="flex items-center gap-2">
<Folder className="w-3 h-3 text-muted-foreground flex-shrink-0" />
<div>
<div className="font-medium text-sm">{pathItem.name}</div>
<div className="text-xs text-muted-foreground font-mono">
{pathItem.path}
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
<div className="flex gap-2">
<Button
@@ -1365,7 +1647,7 @@ function Sidebar({
onClick={onShowSettings}
>
<Settings className="w-3 h-3" />
<span className="text-xs">Tools Settings</span>
<span className="text-xs">Settings</span>
</Button>
</div>
</div>

View File

@@ -0,0 +1,106 @@
import React, { useState, useEffect } from 'react';
import Shell from './Shell.jsx';
/**
* Generic Shell wrapper that can be used in tabs, modals, and other contexts.
* Provides a flexible API for both standalone and session-based usage.
*
* @param {Object} project - Project object with name, fullPath/path, displayName
* @param {Object} session - Session object (optional, for tab usage)
* @param {string} command - Initial command to run (optional)
* @param {boolean} isActive - Whether the shell is active (for tab usage, default: true)
* @param {boolean} isPlainShell - Use plain shell mode vs Claude CLI (default: auto-detect)
* @param {boolean} autoConnect - Whether to auto-connect when mounted (default: true)
* @param {function} onComplete - Callback when process completes (receives exitCode)
* @param {function} onClose - Callback for close button (optional)
* @param {string} title - Custom header title (optional)
* @param {string} className - Additional CSS classes
* @param {boolean} showHeader - Whether to show custom header (default: true)
* @param {boolean} compact - Use compact layout (default: false)
*/
function StandaloneShell({
project,
session = null,
command = null,
isActive = true,
isPlainShell = null, // Auto-detect: true if command provided, false if session provided
autoConnect = true,
onComplete = null,
onClose = null,
title = null,
className = "",
showHeader = true,
compact = false
}) {
const [isCompleted, setIsCompleted] = useState(false);
// Auto-detect isPlainShell based on props
const shouldUsePlainShell = isPlainShell !== null ? isPlainShell : (command !== null);
// Handle process completion
const handleProcessComplete = (exitCode) => {
setIsCompleted(true);
if (onComplete) {
onComplete(exitCode);
}
};
if (!project) {
return (
<div className={`h-full flex items-center justify-center ${className}`}>
<div className="text-center text-gray-500 dark:text-gray-400">
<div className="w-16 h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
<svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 002 2z" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">No Project Selected</h3>
<p>A project is required to open a shell</p>
</div>
</div>
);
}
return (
<div className={`h-full flex flex-col ${className}`}>
{/* Optional custom header */}
{showHeader && title && (
<div className="flex-shrink-0 bg-gray-800 border-b border-gray-700 px-4 py-2">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2">
<h3 className="text-sm font-medium text-gray-200">{title}</h3>
{isCompleted && (
<span className="text-xs text-green-400">(Completed)</span>
)}
</div>
{onClose && (
<button
onClick={onClose}
className="text-gray-400 hover:text-white"
title="Close"
>
<svg className="w-4 h-4" 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>
</div>
)}
{/* Shell component wrapper */}
<div className="flex-1">
<Shell
selectedProject={project}
selectedSession={session}
isActive={isActive}
initialCommand={command}
isPlainShell={shouldUsePlainShell}
onProcessComplete={handleProcessComplete}
/>
</div>
</div>
);
}
export default StandaloneShell;

View File

@@ -128,6 +128,14 @@ export const api = {
}),
},
// Browse filesystem for project suggestions
browseFilesystem: (dirPath = null) => {
const params = new URLSearchParams();
if (dirPath) params.append('path', dirPath);
return authenticatedFetch(`/api/browse-filesystem?${params}`);
},
// Generic GET method for any endpoint
get: (endpoint) => authenticatedFetch(`/api${endpoint}`),
};

View File

@@ -1 +0,0 @@
hello world 5