feat: Implement CLAUDE.md Manager View with file tree, viewer, and metadata actions

- Added main JavaScript functionality for CLAUDE.md management including file loading, rendering, and editing capabilities.
- Created a test HTML file to validate the functionality of the CLAUDE.md manager.
- Introduced CLI generation examples and documentation for rules creation via CLI.
- Enhanced error handling and notifications for file operations.
This commit is contained in:
catlog22
2025-12-14 23:08:36 +08:00
parent 0529b57694
commit d91477ad80
30 changed files with 7961 additions and 298 deletions

View File

@@ -1528,6 +1528,11 @@ code.ctx-meta-chip-value {
color: white;
}
.status-toast.warning {
background: hsl(38 92% 50%);
color: white;
}
.status-toast.fade-out {
animation: toastFadeOut 0.3s ease forwards;
}

View File

@@ -214,3 +214,113 @@
border-color: hsl(var(--primary));
box-shadow: 0 0 0 2px hsl(var(--primary) / 0.2);
}
/* ==========================================
CREATE MODAL STYLES (Skills & Rules)
========================================== */
/* Modal Overlay */
.modal-overlay {
animation: fadeIn 0.15s ease-out;
backdrop-filter: blur(2px);
}
/* Modal Dialog */
.modal-dialog {
animation: slideUpModal 0.2s ease-out;
}
@keyframes slideUpModal {
from {
opacity: 0;
transform: translateY(20px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
/* Location Selection Buttons */
.location-btn {
cursor: pointer;
}
.location-btn:active {
transform: scale(0.98);
}
/* Validation Result Animations */
#skillValidationResult > div,
#ruleValidationResult > div {
animation: slideDown 0.2s ease-out;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Path Input List Animations */
#rulePathsList > div {
animation: slideDown 0.15s ease-out;
}
/* Form Input Focus States */
.modal-dialog input:focus,
.modal-dialog textarea:focus,
.modal-dialog select:focus {
outline: none;
border-color: hsl(var(--primary));
ring: 2px;
ring-color: hsl(var(--primary) / 0.2);
}
/* Checkbox Custom Styling */
.modal-dialog input[type="checkbox"] {
cursor: pointer;
accent-color: hsl(var(--primary));
}
/* Textarea Specific */
.modal-dialog textarea {
resize: vertical;
min-height: 100px;
}
/* Button Hover States */
.modal-dialog button:not(:disabled):hover {
opacity: 0.9;
}
.modal-dialog button:not(:disabled):active {
transform: scale(0.98);
}
/* Loading Spinner in Validation */
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* Responsive Modal */
@media (max-width: 640px) {
.modal-dialog {
max-width: 95vw;
max-height: 95vh;
}
}

View File

@@ -0,0 +1,759 @@
/* ========================================
* CLAUDE.md Manager Styles
* Three-column layout: File Tree | Viewer/Editor | Metadata
* ======================================== */
/* ========================================
* Main Layout
* ======================================== */
.claude-manager-view {
height: 100%;
min-height: calc(100vh - 180px);
max-height: calc(100vh - 180px);
overflow: hidden;
display: flex;
flex-direction: column;
}
.claude-manager-view.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* ========================================
* Header
* ======================================== */
.claude-manager-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 0;
margin-bottom: 0.5rem;
border-bottom: 1px solid hsl(var(--border));
flex-shrink: 0;
}
.claude-manager-header-left {
display: flex;
align-items: center;
gap: 0.75rem;
}
.claude-manager-header-left h2 {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1.125rem;
font-weight: 600;
color: hsl(var(--foreground));
margin: 0;
}
.file-count-badge {
font-size: 0.75rem;
padding: 0.25rem 0.5rem;
background: hsl(var(--muted));
color: hsl(var(--muted-foreground));
border-radius: 0.25rem;
}
.claude-manager-header-right {
display: flex;
align-items: center;
gap: 0.5rem;
}
/* ========================================
* Three-Column Grid
* ======================================== */
.claude-manager-columns {
display: grid;
grid-template-columns: 280px 1fr 320px;
gap: 1rem;
flex: 1;
min-height: 0;
overflow: hidden;
}
.claude-manager-column {
display: flex;
flex-direction: column;
min-height: 0;
background: hsl(var(--card));
border: 1px solid hsl(var(--border));
border-radius: 0.5rem;
}
.claude-manager-column.left {
overflow-y: auto;
height: 100%;
}
.claude-manager-column.center {
overflow: hidden;
height: 100%;
}
.claude-manager-column.right {
overflow-y: auto;
height: 100%;
}
/* ========================================
* File Tree (Left Column)
* ======================================== */
.file-tree {
padding: 0;
}
/* Search Box */
.file-tree-search {
position: relative;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid hsl(var(--border));
}
.file-tree-search input {
width: 100%;
padding: 0.5rem 2.5rem 0.5rem 0.75rem;
border: 1px solid hsl(var(--border));
border-radius: 0.375rem;
background: hsl(var(--background));
color: hsl(var(--foreground));
font-size: 0.875rem;
}
.file-tree-search input:focus {
outline: none;
border-color: hsl(var(--primary));
box-shadow: 0 0 0 2px hsl(var(--primary) / 0.1);
}
.file-tree-search i {
position: absolute;
right: 1.5rem;
top: 50%;
transform: translateY(-50%);
color: hsl(var(--muted-foreground));
pointer-events: none;
}
.file-tree-section {
margin-bottom: 0.5rem;
}
.file-tree-header {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
cursor: pointer;
font-weight: 600;
color: hsl(var(--foreground));
border-radius: 0.25rem;
transition: background-color 0.15s;
}
.file-tree-header:hover {
background: hsl(var(--muted));
}
.file-tree-header .file-count {
margin-left: auto;
font-size: 0.75rem;
padding: 0.125rem 0.375rem;
background: hsl(var(--muted));
color: hsl(var(--muted-foreground));
border-radius: 0.25rem;
}
.file-tree-subheader {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.375rem 0.5rem;
cursor: pointer;
font-size: 0.875rem;
color: hsl(var(--muted-foreground));
border-radius: 0.25rem;
transition: background-color 0.15s;
}
.file-tree-subheader:hover {
background: hsl(var(--muted) / 0.5);
}
.file-tree-subheader .file-count {
margin-left: auto;
font-size: 0.7rem;
padding: 0.125rem 0.25rem;
background: hsl(var(--muted));
color: hsl(var(--muted-foreground));
border-radius: 0.25rem;
}
.file-tree-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.375rem 0.5rem;
cursor: pointer;
font-size: 0.875rem;
color: hsl(var(--foreground));
border-radius: 0.25rem;
transition: background-color 0.15s;
}
.file-tree-item:hover {
background: hsl(var(--muted) / 0.5);
}
.file-tree-item.selected {
background: hsl(var(--primary) / 0.1);
color: hsl(var(--primary));
font-weight: 500;
}
.file-tree-item.empty {
color: hsl(var(--muted-foreground));
cursor: default;
font-style: italic;
}
.file-tree-item.empty:hover {
background: transparent;
}
.file-tree-item .file-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-tree-item .file-path-hint {
font-size: 0.7rem;
color: hsl(var(--muted-foreground));
opacity: 0.7;
}
/* Color coding for level icons */
.text-orange-500 {
color: hsl(25, 95%, 53%);
}
.text-green-500 {
color: hsl(142, 71%, 45%);
}
.text-blue-500 {
color: hsl(217, 91%, 60%);
}
/* ========================================
* File Viewer (Center Column)
* ======================================== */
.file-viewer {
display: flex;
flex-direction: column;
height: 100%;
}
.file-viewer-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1rem;
border-bottom: 1px solid hsl(var(--border));
flex-shrink: 0;
}
.file-viewer-header h3 {
font-size: 1rem;
font-weight: 600;
color: hsl(var(--foreground));
margin: 0;
}
.file-viewer-actions {
display: flex;
gap: 0.5rem;
}
.file-viewer-content {
flex: 1;
overflow-y: auto;
padding: 1rem;
}
.markdown-content {
line-height: 1.6;
color: hsl(var(--foreground));
}
.markdown-content h1 {
font-size: 1.5rem;
font-weight: 700;
margin: 1.5rem 0 1rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid hsl(var(--border));
}
.markdown-content h2 {
font-size: 1.25rem;
font-weight: 600;
margin: 1.25rem 0 0.75rem;
}
.markdown-content h3 {
font-size: 1.125rem;
font-weight: 600;
margin: 1rem 0 0.5rem;
}
.markdown-content strong {
font-weight: 600;
color: hsl(var(--foreground));
}
.markdown-content em {
font-style: italic;
}
.markdown-content code {
font-family: 'Consolas', 'Monaco', monospace;
font-size: 0.875rem;
padding: 0.125rem 0.375rem;
background: hsl(var(--muted));
border-radius: 0.25rem;
}
.file-editor {
width: 100%;
height: 100%;
min-height: 400px;
padding: 1rem;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 0.875rem;
line-height: 1.5;
color: hsl(var(--foreground));
background: hsl(var(--background));
border: none;
outline: none;
resize: none;
}
.file-editor:focus {
background: hsl(var(--background));
}
/* ========================================
* File Metadata (Right Column)
* ======================================== */
.file-metadata {
padding: 1rem;
}
.metadata-section {
margin-bottom: 1.5rem;
}
.metadata-section h4 {
font-size: 0.875rem;
font-weight: 600;
color: hsl(var(--muted-foreground));
text-transform: uppercase;
letter-spacing: 0.05em;
margin: 0 0 0.75rem;
}
.metadata-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
margin-bottom: 0.75rem;
}
.metadata-item .label {
font-size: 0.75rem;
color: hsl(var(--muted-foreground));
}
.metadata-item .value {
font-size: 0.875rem;
color: hsl(var(--foreground));
font-weight: 500;
}
.metadata-item .value.path {
font-family: 'Consolas', 'Monaco', monospace;
font-size: 0.75rem;
word-break: break-all;
background: hsl(var(--muted));
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
}
.metadata-section .btn.full-width {
width: 100%;
margin-bottom: 0.5rem;
justify-content: center;
}
/* ========================================
* CLI Sync Panel
* ======================================== */
.cli-sync-panel {
padding: 1rem;
border: 1px solid hsl(var(--border));
border-radius: 0.5rem;
background: hsl(var(--card));
}
.cli-sync-panel .panel-header {
display: flex;
align-items: center;
gap: 0.5rem;
font-weight: 600;
margin-bottom: 1rem;
color: hsl(var(--primary));
}
.sync-config {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-bottom: 1rem;
}
.sync-config label {
font-size: 0.875rem;
font-weight: 500;
color: hsl(var(--muted-foreground));
margin-bottom: 0.25rem;
}
.sync-config .sync-select,
.sync-config select {
padding: 0.5rem;
border: 1px solid hsl(var(--border));
border-radius: 0.375rem;
background: hsl(var(--background));
color: hsl(var(--foreground));
font-size: 0.875rem;
width: 100%;
}
.sync-config .sync-select:focus,
.sync-config select:focus {
outline: none;
border-color: hsl(var(--primary));
box-shadow: 0 0 0 2px hsl(var(--primary) / 0.1);
}
.sync-button {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.625rem;
background: hsl(var(--primary));
color: white;
border: none;
border-radius: 0.375rem;
font-weight: 500;
cursor: pointer;
transition: opacity 0.2s;
}
.sync-button:hover:not(:disabled) {
opacity: 0.9;
}
.sync-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.sync-progress {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem;
margin-top: 0.75rem;
background: hsl(var(--accent));
border-radius: 0.375rem;
font-size: 0.875rem;
color: hsl(var(--accent-foreground));
}
.sync-progress i {
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* ========================================
* Empty State
* ======================================== */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: hsl(var(--muted-foreground));
text-align: center;
padding: 2rem;
}
.empty-state i {
margin-bottom: 1rem;
}
.empty-state p {
margin: 0;
font-size: 0.875rem;
}
/* ========================================
* File Type Icons
* ======================================== */
.file-icon {
flex-shrink: 0;
}
.file-icon.directory {
color: hsl(var(--primary));
}
.file-icon.markdown {
color: hsl(25, 95%, 53%);
}
.file-icon.code {
color: hsl(217, 91%, 60%);
}
.file-icon.json {
color: hsl(142, 71%, 45%);
}
.file-icon.css {
color: hsl(262, 83%, 58%);
}
.file-size {
margin-left: auto;
font-size: 0.7rem;
color: hsl(var(--muted-foreground));
opacity: 0.7;
}
/* Search Highlight */
.search-highlight {
background: hsl(45, 100%, 70%);
color: hsl(0, 0%, 10%);
font-weight: 600;
padding: 0.125rem 0.25rem;
border-radius: 0.125rem;
}
/* ========================================
* Create Dialog (Modal)
* ======================================== */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
animation: fadeIn 0.2s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.create-dialog {
background: hsl(var(--card));
border: 1px solid hsl(var(--border));
border-radius: 0.5rem;
padding: 1.5rem;
width: 90%;
max-width: 500px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
animation: slideUp 0.3s;
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.create-dialog h3 {
margin: 0 0 1.5rem 0;
color: hsl(var(--foreground));
font-size: 1.125rem;
font-weight: 600;
}
.dialog-form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.dialog-form label {
display: block;
font-size: 0.875rem;
font-weight: 500;
margin-bottom: 0.5rem;
color: hsl(var(--muted-foreground));
}
.dialog-form input,
.dialog-form select {
width: 100%;
padding: 0.5rem 0.75rem;
border: 1px solid hsl(var(--border));
border-radius: 0.375rem;
background: hsl(var(--background));
color: hsl(var(--foreground));
font-size: 0.875rem;
}
.dialog-form input:focus,
.dialog-form select:focus {
outline: none;
border-color: hsl(var(--primary));
box-shadow: 0 0 0 2px hsl(var(--primary) / 0.1);
}
.dialog-buttons {
display: flex;
gap: 0.75rem;
margin-top: 1.5rem;
}
.dialog-buttons button {
flex: 1;
}
/* ========================================
* Enhanced Markdown Content
* ======================================== */
.markdown-content a {
color: hsl(var(--primary));
text-decoration: underline;
}
.markdown-content a:hover {
opacity: 0.8;
}
.markdown-content table {
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
font-size: 0.875rem;
}
.markdown-content table th,
.markdown-content table td {
padding: 0.5rem 0.75rem;
border: 1px solid hsl(var(--border));
}
.markdown-content table th {
background: hsl(var(--muted));
font-weight: 600;
}
.markdown-content pre {
background: hsl(var(--muted));
padding: 1rem;
border-radius: 0.375rem;
overflow-x: auto;
margin: 1rem 0;
}
.markdown-content pre code {
background: transparent;
padding: 0;
}
.markdown-content ul,
.markdown-content ol {
margin: 0.5rem 0;
padding-left: 1.5rem;
}
.markdown-content li {
margin: 0.25rem 0;
}
.task-list-item {
list-style: none;
margin-left: -1.5rem;
}
.task-list-item input[type="checkbox"] {
margin-right: 0.5rem;
}
/* ========================================
* Button Styles
* ======================================== */
.btn-danger {
background: hsl(0, 72%, 51%);
color: white;
border-color: hsl(0, 72%, 51%);
}
.btn-danger:hover:not(:disabled) {
background: hsl(0, 72%, 45%);
border-color: hsl(0, 72%, 45%);
}
/* ========================================
* Responsive Design
* ======================================== */
@media (max-width: 1400px) {
.claude-manager-columns {
grid-template-columns: 240px 1fr 280px;
}
}
@media (max-width: 1024px) {
.claude-manager-columns {
grid-template-columns: 1fr;
grid-template-rows: auto 1fr auto;
}
.claude-manager-column.left {
max-height: 200px;
}
.claude-manager-column.right {
max-height: 300px;
}
}

View File

@@ -184,6 +184,9 @@ function renderCliStatus() {
</button>`
: `<button class="btn-sm btn-outline flex items-center gap-1" onclick="initCodexLensIndex()">
<i data-lucide="database" class="w-3 h-3"></i> Init Index
</button>
<button class="btn-sm btn-outline flex items-center gap-1" onclick="uninstallCodexLens()">
<i data-lucide="trash-2" class="w-3 h-3"></i> Uninstall
</button>`
}
</div>
@@ -379,8 +382,121 @@ async function refreshAllCliStatus() {
renderCliStatus();
}
async function installCodexLens() {
showRefreshToast('Installing CodexLens...', 'info');
function installCodexLens() {
openCodexLensInstallWizard();
}
function openCodexLensInstallWizard() {
const modal = document.createElement('div');
modal.id = 'codexlensInstallModal';
modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50';
modal.innerHTML = `
<div class="bg-card rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden">
<div class="p-6">
<div class="flex items-center gap-3 mb-4">
<div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
<i data-lucide="database" class="w-5 h-5 text-primary"></i>
</div>
<div>
<h3 class="text-lg font-semibold">Install CodexLens</h3>
<p class="text-sm text-muted-foreground">Python-based code indexing engine</p>
</div>
</div>
<div class="space-y-4">
<div class="bg-muted/50 rounded-lg p-4">
<h4 class="font-medium mb-2">What will be installed:</h4>
<ul class="text-sm space-y-2 text-muted-foreground">
<li class="flex items-start gap-2">
<i data-lucide="check" class="w-4 h-4 text-success mt-0.5"></i>
<span><strong>Python virtual environment</strong> - Isolated Python environment</span>
</li>
<li class="flex items-start gap-2">
<i data-lucide="check" class="w-4 h-4 text-success mt-0.5"></i>
<span><strong>CodexLens package</strong> - Code indexing and search engine</span>
</li>
<li class="flex items-start gap-2">
<i data-lucide="check" class="w-4 h-4 text-success mt-0.5"></i>
<span><strong>SQLite FTS5</strong> - Full-text search database</span>
</li>
</ul>
</div>
<div class="bg-primary/5 border border-primary/20 rounded-lg p-3">
<div class="flex items-start gap-2">
<i data-lucide="info" class="w-4 h-4 text-primary mt-0.5"></i>
<div class="text-sm text-muted-foreground">
<p class="font-medium text-foreground">Installation Location</p>
<p class="mt-1"><code class="bg-muted px-1 rounded">~/.codexlens/venv</code></p>
<p class="mt-1">First installation may take 2-3 minutes to download and setup Python packages.</p>
</div>
</div>
</div>
<div id="codexlensInstallProgress" class="hidden">
<div class="flex items-center gap-3">
<div class="animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full"></div>
<span class="text-sm" id="codexlensInstallStatus">Starting installation...</span>
</div>
<div class="mt-2 h-2 bg-muted rounded-full overflow-hidden">
<div id="codexlensProgressBar" class="h-full bg-primary transition-all duration-300" style="width: 0%"></div>
</div>
</div>
</div>
</div>
<div class="border-t border-border p-4 flex justify-end gap-3 bg-muted/30">
<button class="btn-outline px-4 py-2" onclick="closeCodexLensInstallWizard()">Cancel</button>
<button id="codexlensInstallBtn" class="btn-primary px-4 py-2" onclick="startCodexLensInstall()">
<i data-lucide="download" class="w-4 h-4 mr-2"></i>
Install Now
</button>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) {
lucide.createIcons();
}
}
function closeCodexLensInstallWizard() {
const modal = document.getElementById('codexlensInstallModal');
if (modal) {
modal.remove();
}
}
async function startCodexLensInstall() {
const progressDiv = document.getElementById('codexlensInstallProgress');
const installBtn = document.getElementById('codexlensInstallBtn');
const statusText = document.getElementById('codexlensInstallStatus');
const progressBar = document.getElementById('codexlensProgressBar');
// Show progress, disable button
progressDiv.classList.remove('hidden');
installBtn.disabled = true;
installBtn.innerHTML = '<span class="animate-pulse">Installing...</span>';
// Simulate progress stages
const stages = [
{ progress: 10, text: 'Creating virtual environment...' },
{ progress: 30, text: 'Installing pip packages...' },
{ progress: 50, text: 'Installing CodexLens package...' },
{ progress: 70, text: 'Setting up Python dependencies...' },
{ progress: 90, text: 'Finalizing installation...' }
];
let currentStage = 0;
const progressInterval = setInterval(() => {
if (currentStage < stages.length) {
statusText.textContent = stages[currentStage].text;
progressBar.style.width = `${stages[currentStage].progress}%`;
currentStage++;
}
}, 1500);
try {
const response = await fetch('/api/codexlens/bootstrap', {
@@ -389,40 +505,288 @@ async function installCodexLens() {
body: JSON.stringify({})
});
clearInterval(progressInterval);
const result = await response.json();
if (result.success) {
showRefreshToast('CodexLens installed successfully!', 'success');
await loadCodexLensStatus();
renderCliStatus();
progressBar.style.width = '100%';
statusText.textContent = 'Installation complete!';
setTimeout(() => {
closeCodexLensInstallWizard();
showRefreshToast('CodexLens installed successfully!', 'success');
loadCodexLensStatus().then(() => renderCliStatus());
}, 1000);
} else {
showRefreshToast(`Install failed: ${result.error}`, 'error');
statusText.textContent = `Error: ${result.error}`;
progressBar.classList.add('bg-destructive');
installBtn.disabled = false;
installBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
} catch (err) {
showRefreshToast(`Install error: ${err.message}`, 'error');
clearInterval(progressInterval);
statusText.textContent = `Error: ${err.message}`;
progressBar.classList.add('bg-destructive');
installBtn.disabled = false;
installBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
}
function uninstallCodexLens() {
openCodexLensUninstallWizard();
}
function openCodexLensUninstallWizard() {
const modal = document.createElement('div');
modal.id = 'codexlensUninstallModal';
modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50';
modal.innerHTML = `
<div class="bg-card rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden">
<div class="p-6">
<div class="flex items-center gap-3 mb-4">
<div class="w-10 h-10 rounded-full bg-destructive/10 flex items-center justify-center">
<i data-lucide="trash-2" class="w-5 h-5 text-destructive"></i>
</div>
<div>
<h3 class="text-lg font-semibold">Uninstall CodexLens</h3>
<p class="text-sm text-muted-foreground">Remove CodexLens and all data</p>
</div>
</div>
<div class="space-y-4">
<div class="bg-destructive/5 border border-destructive/20 rounded-lg p-4">
<h4 class="font-medium text-destructive mb-2">What will be removed:</h4>
<ul class="text-sm space-y-2 text-muted-foreground">
<li class="flex items-start gap-2">
<i data-lucide="x" class="w-4 h-4 text-destructive mt-0.5"></i>
<span>Virtual environment at <code class="bg-muted px-1 rounded">~/.codexlens/venv</code></span>
</li>
<li class="flex items-start gap-2">
<i data-lucide="x" class="w-4 h-4 text-destructive mt-0.5"></i>
<span>All CodexLens indexed data and databases</span>
</li>
<li class="flex items-start gap-2">
<i data-lucide="x" class="w-4 h-4 text-destructive mt-0.5"></i>
<span>Configuration and semantic search models</span>
</li>
</ul>
</div>
<div class="bg-warning/10 border border-warning/20 rounded-lg p-3">
<div class="flex items-start gap-2">
<i data-lucide="alert-triangle" class="w-4 h-4 text-warning mt-0.5"></i>
<div class="text-sm">
<p class="font-medium text-warning">Warning</p>
<p class="text-muted-foreground">This action cannot be undone. All indexed code data will be permanently deleted.</p>
</div>
</div>
</div>
<div id="codexlensUninstallProgress" class="hidden">
<div class="flex items-center gap-3">
<div class="animate-spin w-5 h-5 border-2 border-destructive border-t-transparent rounded-full"></div>
<span class="text-sm" id="codexlensUninstallStatus">Removing files...</span>
</div>
<div class="mt-2 h-2 bg-muted rounded-full overflow-hidden">
<div id="codexlensUninstallProgressBar" class="h-full bg-destructive transition-all duration-300" style="width: 0%"></div>
</div>
</div>
</div>
</div>
<div class="border-t border-border p-4 flex justify-end gap-3 bg-muted/30">
<button class="btn-outline px-4 py-2" onclick="closeCodexLensUninstallWizard()">Cancel</button>
<button id="codexlensUninstallBtn" class="btn-destructive px-4 py-2" onclick="startCodexLensUninstall()">
<i data-lucide="trash-2" class="w-4 h-4 mr-2"></i>
Uninstall
</button>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) {
lucide.createIcons();
}
}
function closeCodexLensUninstallWizard() {
const modal = document.getElementById('codexlensUninstallModal');
if (modal) {
modal.remove();
}
}
async function startCodexLensUninstall() {
const progressDiv = document.getElementById('codexlensUninstallProgress');
const uninstallBtn = document.getElementById('codexlensUninstallBtn');
const statusText = document.getElementById('codexlensUninstallStatus');
const progressBar = document.getElementById('codexlensUninstallProgressBar');
// Show progress, disable button
progressDiv.classList.remove('hidden');
uninstallBtn.disabled = true;
uninstallBtn.innerHTML = '<span class="animate-pulse">Uninstalling...</span>';
// Simulate progress stages
const stages = [
{ progress: 25, text: 'Removing virtual environment...' },
{ progress: 50, text: 'Deleting indexed data...' },
{ progress: 75, text: 'Cleaning up configuration...' },
{ progress: 90, text: 'Finalizing removal...' }
];
let currentStage = 0;
const progressInterval = setInterval(() => {
if (currentStage < stages.length) {
statusText.textContent = stages[currentStage].text;
progressBar.style.width = `${stages[currentStage].progress}%`;
currentStage++;
}
}, 500);
try {
const response = await fetch('/api/codexlens/uninstall', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
clearInterval(progressInterval);
const result = await response.json();
if (result.success) {
progressBar.style.width = '100%';
statusText.textContent = 'Uninstallation complete!';
setTimeout(() => {
closeCodexLensUninstallWizard();
showRefreshToast('CodexLens uninstalled successfully!', 'success');
loadCodexLensStatus().then(() => renderCliStatus());
}, 1000);
} else {
statusText.textContent = `Error: ${result.error}`;
progressBar.classList.remove('bg-destructive');
progressBar.classList.add('bg-destructive');
uninstallBtn.disabled = false;
uninstallBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
} catch (err) {
clearInterval(progressInterval);
statusText.textContent = `Error: ${err.message}`;
progressBar.classList.remove('bg-destructive');
progressBar.classList.add('bg-destructive');
uninstallBtn.disabled = false;
uninstallBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
}
async function initCodexLensIndex() {
// Get current workspace path from multiple sources
let targetPath = null;
// Helper function to check if path is valid
const isValidPath = (path) => {
return path && typeof path === 'string' && path.length > 0 &&
(path.includes('/') || path.includes('\\')) &&
!path.startsWith('{{') && !path.endsWith('}}');
};
console.log('[CodexLens] Attempting to get project path...');
// Try 1: Global projectPath variable
if (isValidPath(projectPath)) {
targetPath = projectPath;
console.log('[CodexLens] ✓ Using global projectPath:', targetPath);
}
// Try 2: Get from workflowData
if (!targetPath && typeof workflowData !== 'undefined' && workflowData && isValidPath(workflowData.projectPath)) {
targetPath = workflowData.projectPath;
console.log('[CodexLens] ✓ Using workflowData.projectPath:', targetPath);
}
// Try 3: Get from current path display element
if (!targetPath) {
const currentPathEl = document.getElementById('currentPath');
if (currentPathEl && currentPathEl.textContent) {
const pathText = currentPathEl.textContent.trim();
if (isValidPath(pathText)) {
targetPath = pathText;
console.log('[CodexLens] ✓ Using currentPath element text:', targetPath);
}
}
}
// Final validation
if (!targetPath) {
showRefreshToast('Error: No workspace loaded. Please open a workspace first.', 'error');
console.error('[CodexLens] No valid project path available');
console.error('[CodexLens] Attempted sources: projectPath:', projectPath, 'workflowData:', workflowData);
return;
}
showRefreshToast('Initializing CodexLens index...', 'info');
console.log('[CodexLens] Initializing index for path:', targetPath);
try {
const response = await fetch('/api/codexlens/init', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: projectPath })
body: JSON.stringify({ path: targetPath })
});
const result = await response.json();
console.log('[CodexLens] Init result:', result);
if (result.success) {
const data = result.result?.result || result.result || result;
let data = null;
// Try to parse nested JSON in output field
if (result.output && typeof result.output === 'string') {
try {
// Extract JSON from output (it may contain other text before the JSON)
const jsonMatch = result.output.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]);
data = parsed.result || parsed;
console.log('[CodexLens] Parsed from output:', data);
}
} catch (e) {
console.warn('[CodexLens] Failed to parse output as JSON:', e);
}
}
// Fallback to direct result field
if (!data) {
data = result.result?.result || result.result || result;
}
const files = data.files_indexed || 0;
const dirs = data.dirs_indexed || 0;
const symbols = data.symbols_indexed || 0;
showRefreshToast(`Index created: ${files} files, ${symbols} symbols`, 'success');
console.log('[CodexLens] Parsed data:', { files, dirs, symbols });
if (files === 0 && dirs === 0) {
showRefreshToast(`Warning: No files indexed. Path: ${targetPath}`, 'warning');
console.warn('[CodexLens] No files indexed. Full data:', data);
} else {
showRefreshToast(`Index created: ${files} files, ${dirs} directories`, 'success');
console.log('[CodexLens] Index created successfully');
}
} else {
showRefreshToast(`Init failed: ${result.error}`, 'error');
console.error('[CodexLens] Init error:', result.error);
}
} catch (err) {
showRefreshToast(`Init error: ${err.message}`, 'error');
console.error('[CodexLens] Exception:', err);
}
}
@@ -591,7 +955,7 @@ function openSemanticSettingsModal() {
tool.charAt(0).toUpperCase() + tool.slice(1) + '</option>';
}).join('');
const fallbackOptions = '<option value="">None</option>' + availableTools.map(function(tool) {
const fallbackOptions = '<option value="">' + t('semantic.none') + '</option>' + availableTools.map(function(tool) {
return '<option value="' + tool + '"' + (llmEnhancementSettings.fallbackTool === tool ? ' selected' : '') + '>' +
tool.charAt(0).toUpperCase() + tool.slice(1) + '</option>';
}).join('');
@@ -607,16 +971,16 @@ function openSemanticSettingsModal() {
'<i data-lucide="sparkles" class="w-5 h-5 text-primary"></i>' +
'</div>' +
'<div>' +
'<h3 class="text-lg font-semibold">Semantic Search Settings</h3>' +
'<p class="text-sm text-muted-foreground">Configure LLM enhancement for semantic indexing</p>' +
'<h3 class="text-lg font-semibold">' + t('semantic.settings') + '</h3>' +
'<p class="text-sm text-muted-foreground">' + t('semantic.configDesc') + '</p>' +
'</div>' +
'</div>' +
'<div class="space-y-4">' +
'<div class="flex items-center justify-between p-4 bg-muted/50 rounded-lg">' +
'<div>' +
'<h4 class="font-medium flex items-center gap-2">' +
'<i data-lucide="brain" class="w-4 h-4"></i>LLM Enhancement</h4>' +
'<p class="text-sm text-muted-foreground mt-1">Use LLM to generate code summaries for better semantic search</p>' +
'<i data-lucide="brain" class="w-4 h-4"></i>' + t('semantic.llmEnhancement') + '</h4>' +
'<p class="text-sm text-muted-foreground mt-1">' + t('semantic.llmDesc') + '</p>' +
'</div>' +
'<label class="cli-toggle">' +
'<input type="checkbox" id="llmEnhancementToggle" ' + (llmEnhancementSettings.enabled ? 'checked' : '') +
@@ -628,29 +992,29 @@ function openSemanticSettingsModal() {
'<div class="grid grid-cols-2 gap-4">' +
'<div>' +
'<label class="block text-sm font-medium mb-2">' +
'<i data-lucide="cpu" class="w-3 h-3 inline mr-1"></i>Primary LLM Tool</label>' +
'<i data-lucide="cpu" class="w-3 h-3 inline mr-1"></i>' + t('semantic.primaryTool') + '</label>' +
'<select class="cli-setting-select w-full" id="llmToolSelect" onchange="updateLlmTool(this.value)" ' + disabled + '>' + toolOptions + '</select>' +
'</div>' +
'<div>' +
'<label class="block text-sm font-medium mb-2">' +
'<i data-lucide="refresh-cw" class="w-3 h-3 inline mr-1"></i>Fallback Tool</label>' +
'<i data-lucide="refresh-cw" class="w-3 h-3 inline mr-1"></i>' + t('semantic.fallbackTool') + '</label>' +
'<select class="cli-setting-select w-full" id="llmFallbackSelect" onchange="updateLlmFallback(this.value)" ' + disabled + '>' + fallbackOptions + '</select>' +
'</div>' +
'</div>' +
'<div class="grid grid-cols-2 gap-4">' +
'<div>' +
'<label class="block text-sm font-medium mb-2">' +
'<i data-lucide="layers" class="w-3 h-3 inline mr-1"></i>Batch Size</label>' +
'<i data-lucide="layers" class="w-3 h-3 inline mr-1"></i>' + t('semantic.batchSize') + '</label>' +
'<select class="cli-setting-select w-full" id="llmBatchSelect" onchange="updateLlmBatchSize(this.value)" ' + disabled + '>' +
'<option value="1"' + (llmEnhancementSettings.batchSize === 1 ? ' selected' : '') + '>1 file</option>' +
'<option value="3"' + (llmEnhancementSettings.batchSize === 3 ? ' selected' : '') + '>3 files</option>' +
'<option value="5"' + (llmEnhancementSettings.batchSize === 5 ? ' selected' : '') + '>5 files</option>' +
'<option value="10"' + (llmEnhancementSettings.batchSize === 10 ? ' selected' : '') + '>10 files</option>' +
'<option value="1"' + (llmEnhancementSettings.batchSize === 1 ? ' selected' : '') + '>1 ' + t('semantic.file') + '</option>' +
'<option value="3"' + (llmEnhancementSettings.batchSize === 3 ? ' selected' : '') + '>3 ' + t('semantic.files') + '</option>' +
'<option value="5"' + (llmEnhancementSettings.batchSize === 5 ? ' selected' : '') + '>5 ' + t('semantic.files') + '</option>' +
'<option value="10"' + (llmEnhancementSettings.batchSize === 10 ? ' selected' : '') + '>10 ' + t('semantic.files') + '</option>' +
'</select>' +
'</div>' +
'<div>' +
'<label class="block text-sm font-medium mb-2">' +
'<i data-lucide="clock" class="w-3 h-3 inline mr-1"></i>Timeout</label>' +
'<i data-lucide="clock" class="w-3 h-3 inline mr-1"></i>' + t('semantic.timeout') + '</label>' +
'<select class="cli-setting-select w-full" id="llmTimeoutSelect" onchange="updateLlmTimeout(this.value)" ' + disabled + '>' +
'<option value="60000"' + (llmEnhancementSettings.timeoutMs === 60000 ? ' selected' : '') + '>1 min</option>' +
'<option value="180000"' + (llmEnhancementSettings.timeoutMs === 180000 ? ' selected' : '') + '>3 min</option>' +
@@ -664,26 +1028,110 @@ function openSemanticSettingsModal() {
'<div class="flex items-start gap-2">' +
'<i data-lucide="info" class="w-4 h-4 text-primary mt-0.5"></i>' +
'<div class="text-sm text-muted-foreground">' +
'<p>LLM enhancement generates code summaries and keywords for each file, improving semantic search accuracy.</p>' +
'<p class="mt-1">Run <code class="bg-muted px-1 rounded">codex-lens enhance</code> after enabling to process existing files.</p>' +
'<p>' + t('semantic.enhanceInfo') + '</p>' +
'<p class="mt-1">' + t('semantic.enhanceCommand') + ' <code class="bg-muted px-1 rounded">codex-lens enhance</code> ' + t('semantic.enhanceAfterEnable') + '</p>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="flex gap-2 pt-2">' +
'<button class="btn-sm btn-outline flex items-center gap-1 flex-1" onclick="runEnhanceCommand()" ' + disabled + '>' +
'<i data-lucide="zap" class="w-3 h-3"></i>Run Enhance Now</button>' +
'<i data-lucide="zap" class="w-3 h-3"></i>' + t('semantic.runEnhanceNow') + '</button>' +
'<button class="btn-sm btn-outline flex items-center gap-1 flex-1" onclick="viewEnhanceStatus()">' +
'<i data-lucide="bar-chart-2" class="w-3 h-3"></i>View Status</button>' +
'<i data-lucide="bar-chart-2" class="w-3 h-3"></i>' + t('semantic.viewStatus') + '</button>' +
'</div>' +
'<div class="border-t border-border my-4"></div>' +
'<div>' +
'<h4 class="font-medium mb-3 flex items-center gap-2">' +
'<i data-lucide="search" class="w-4 h-4"></i>' + t('semantic.testSearch') + '</h4>' +
'<div class="space-y-3">' +
'<div>' +
'<input type="text" id="semanticSearchInput" class="tool-config-input w-full" ' +
'placeholder="' + t('semantic.searchPlaceholder') + '" />' +
'</div>' +
'<div>' +
'<button class="btn-sm btn-primary w-full" id="runSemanticSearchBtn">' +
'<i data-lucide="search" class="w-3 h-3"></i> ' + t('semantic.runSearch') +
'</button>' +
'</div>' +
'<div id="semanticSearchResults" class="hidden">' +
'<div class="bg-muted/30 rounded-lg p-3 max-h-64 overflow-y-auto">' +
'<div class="flex items-center justify-between mb-2">' +
'<p class="text-sm font-medium">' + t('codexlens.results') + ':</p>' +
'<span id="semanticResultCount" class="text-xs text-muted-foreground"></span>' +
'</div>' +
'<pre id="semanticResultContent" class="text-xs font-mono whitespace-pre-wrap break-all"></pre>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="border-t border-border p-4 flex justify-end gap-3 bg-muted/30">' +
'<button class="btn-outline px-4 py-2" onclick="closeSemanticSettingsModal()">Close</button>' +
'<button class="btn-outline px-4 py-2" onclick="closeSemanticSettingsModal()">' + t('semantic.close') + '</button>' +
'</div>' +
'</div>';
document.body.appendChild(modal);
// Add semantic search button handler
setTimeout(function() {
var runSemanticSearchBtn = document.getElementById('runSemanticSearchBtn');
if (runSemanticSearchBtn) {
runSemanticSearchBtn.onclick = async function() {
var query = document.getElementById('semanticSearchInput').value.trim();
var resultsDiv = document.getElementById('semanticSearchResults');
var resultCount = document.getElementById('semanticResultCount');
var resultContent = document.getElementById('semanticResultContent');
if (!query) {
showRefreshToast(t('codexlens.enterQuery'), 'warning');
return;
}
runSemanticSearchBtn.disabled = true;
runSemanticSearchBtn.innerHTML = '<span class="animate-pulse">' + t('codexlens.searching') + '</span>';
resultsDiv.classList.add('hidden');
try {
var params = new URLSearchParams({
query: query,
mode: 'semantic',
limit: '10'
});
var response = await fetch('/api/codexlens/search?' + params.toString());
var result = await response.json();
console.log('[Semantic Search Test] Result:', result);
if (result.success) {
var results = result.results || [];
resultCount.textContent = results.length + ' ' + t('codexlens.resultsCount');
resultContent.textContent = JSON.stringify(results, null, 2);
resultsDiv.classList.remove('hidden');
showRefreshToast(t('codexlens.searchCompleted') + ': ' + results.length + ' ' + t('codexlens.resultsCount'), 'success');
} else {
resultContent.textContent = t('common.error') + ': ' + (result.error || t('common.unknownError'));
resultsDiv.classList.remove('hidden');
showRefreshToast(t('codexlens.searchFailed') + ': ' + result.error, 'error');
}
runSemanticSearchBtn.disabled = false;
runSemanticSearchBtn.innerHTML = '<i data-lucide="search" class="w-3 h-3"></i> ' + t('semantic.runSearch');
if (window.lucide) lucide.createIcons();
} catch (err) {
console.error('[Semantic Search Test] Error:', err);
resultContent.textContent = t('common.exception') + ': ' + err.message;
resultsDiv.classList.remove('hidden');
showRefreshToast(t('common.error') + ': ' + err.message, 'error');
runSemanticSearchBtn.disabled = false;
runSemanticSearchBtn.innerHTML = '<i data-lucide="search" class="w-3 h-3"></i> ' + t('semantic.runSearch');
if (window.lucide) lucide.createIcons();
}
};
}
}, 100);
var handleEscape = function(e) {
if (e.key === 'Escape') {
closeSemanticSettingsModal();
@@ -713,37 +1161,37 @@ function toggleLlmEnhancement(enabled) {
}
renderCliStatus();
showRefreshToast('LLM Enhancement ' + (enabled ? 'enabled' : 'disabled'), 'success');
showRefreshToast(t('semantic.llmEnhancement') + ' ' + (enabled ? t('semantic.enabled') : t('semantic.disabled')), 'success');
}
function updateLlmTool(tool) {
llmEnhancementSettings.tool = tool;
localStorage.setItem('ccw-llm-enhancement-tool', tool);
showRefreshToast('Primary LLM tool set to ' + tool, 'success');
showRefreshToast(t('semantic.toolSetTo') + ' ' + tool, 'success');
}
function updateLlmFallback(tool) {
llmEnhancementSettings.fallbackTool = tool;
localStorage.setItem('ccw-llm-enhancement-fallback', tool);
showRefreshToast('Fallback tool set to ' + (tool || 'none'), 'success');
showRefreshToast(t('semantic.fallbackSetTo') + ' ' + (tool || t('semantic.none')), 'success');
}
function updateLlmBatchSize(size) {
llmEnhancementSettings.batchSize = parseInt(size, 10);
localStorage.setItem('ccw-llm-enhancement-batch-size', size);
showRefreshToast('Batch size set to ' + size + ' files', 'success');
showRefreshToast(t('semantic.batchSetTo') + ' ' + size + ' ' + t('semantic.files'), 'success');
}
function updateLlmTimeout(ms) {
llmEnhancementSettings.timeoutMs = parseInt(ms, 10);
localStorage.setItem('ccw-llm-enhancement-timeout', ms);
var mins = parseInt(ms, 10) / 60000;
showRefreshToast('Timeout set to ' + mins + ' minute' + (mins > 1 ? 's' : ''), 'success');
showRefreshToast(t('semantic.timeoutSetTo') + ' ' + mins + ' ' + (mins > 1 ? t('semantic.minutes') : t('semantic.minute')), 'success');
}
async function runEnhanceCommand() {
if (!llmEnhancementSettings.enabled) {
showRefreshToast('Please enable LLM Enhancement first', 'warning');
showRefreshToast(t('semantic.enableFirst'), 'warning');
return;
}

View File

@@ -142,6 +142,59 @@ async function removeMcpServerFromProject(serverName) {
}
}
async function addGlobalMcpServer(serverName, serverConfig) {
try {
const response = await fetch('/api/mcp-add-global-server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
serverName: serverName,
serverConfig: serverConfig
})
});
if (!response.ok) throw new Error('Failed to add global MCP server');
const result = await response.json();
if (result.success) {
await loadMcpConfig();
renderMcpManager();
showRefreshToast(`Global MCP server "${serverName}" added`, 'success');
}
return result;
} catch (err) {
console.error('Failed to add global MCP server:', err);
showRefreshToast(`Failed to add global MCP server: ${err.message}`, 'error');
return null;
}
}
async function removeGlobalMcpServer(serverName) {
try {
const response = await fetch('/api/mcp-remove-global-server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
serverName: serverName
})
});
if (!response.ok) throw new Error('Failed to remove global MCP server');
const result = await response.json();
if (result.success) {
await loadMcpConfig();
renderMcpManager();
showRefreshToast(`Global MCP server "${serverName}" removed`, 'success');
}
return result;
} catch (err) {
console.error('Failed to remove global MCP server:', err);
showRefreshToast(`Failed to remove global MCP server: ${err.message}`, 'error');
return null;
}
}
// ========== Badge Update ==========
function updateMcpBadge() {
const badge = document.getElementById('badgeMcpServers');
@@ -260,8 +313,40 @@ function isServerInCurrentProject(serverName) {
return serverName in servers;
}
// Generate install command for MCP server
function generateMcpInstallCommand(serverName, serverConfig, scope = 'project') {
const command = serverConfig.command || '';
const args = serverConfig.args || [];
// Check if it's an npx-based package
if (command === 'npx' && args.length > 0) {
const packageName = args[0];
// Check if it's a scoped package or standard package
if (packageName.startsWith('@') || packageName.includes('/')) {
const scopeFlag = scope === 'global' ? ' --global' : '';
return `claude mcp add ${packageName}${scopeFlag}`;
}
}
// For custom servers, return JSON configuration
const scopeFlag = scope === 'global' ? ' --global' : '';
return `claude mcp add ${serverName}${scopeFlag}`;
}
// Copy install command to clipboard
async function copyMcpInstallCommand(serverName, serverConfig, scope = 'project') {
try {
const command = generateMcpInstallCommand(serverName, serverConfig, scope);
await navigator.clipboard.writeText(command);
showRefreshToast(t('mcp.installCmdCopied'), 'success');
} catch (error) {
console.error('Failed to copy install command:', error);
showRefreshToast(t('mcp.installCmdFailed'), 'error');
}
}
// ========== MCP Create Modal ==========
function openMcpCreateModal() {
function openMcpCreateModal(scope = 'project') {
const modal = document.getElementById('mcpCreateModal');
if (modal) {
modal.classList.remove('hidden');
@@ -276,6 +361,11 @@ function openMcpCreateModal() {
// Clear JSON input
document.getElementById('mcpServerJson').value = '';
document.getElementById('mcpJsonPreview').classList.add('hidden');
// Set scope (global or project)
const scopeSelect = document.getElementById('mcpServerScope');
if (scopeSelect) {
scopeSelect.value = scope;
}
// Focus on name input
document.getElementById('mcpServerName').focus();
// Setup JSON input listener
@@ -427,6 +517,8 @@ async function submitMcpCreateFromForm() {
const command = document.getElementById('mcpServerCommand').value.trim();
const argsText = document.getElementById('mcpServerArgs').value.trim();
const envText = document.getElementById('mcpServerEnv').value.trim();
const scopeSelect = document.getElementById('mcpServerScope');
const scope = scopeSelect ? scopeSelect.value : 'project';
// Validate required fields
if (!name) {
@@ -471,7 +563,7 @@ async function submitMcpCreateFromForm() {
serverConfig.env = env;
}
await createMcpServerWithConfig(name, serverConfig);
await createMcpServerWithConfig(name, serverConfig, scope);
}
async function submitMcpCreateFromJson() {
@@ -550,18 +642,30 @@ async function submitMcpCreateFromJson() {
}
}
async function createMcpServerWithConfig(name, serverConfig) {
async function createMcpServerWithConfig(name, serverConfig, scope = 'project') {
// Submit to API
try {
const response = await fetch('/api/mcp-copy-server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
projectPath: projectPath,
serverName: name,
serverConfig: serverConfig
})
});
let response;
if (scope === 'global') {
response = await fetch('/api/mcp-add-global-server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
serverName: name,
serverConfig: serverConfig
})
});
} else {
response = await fetch('/api/mcp-copy-server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
projectPath: projectPath,
serverName: name,
serverConfig: serverConfig
})
});
}
if (!response.ok) throw new Error('Failed to create MCP server');
@@ -570,7 +674,8 @@ async function createMcpServerWithConfig(name, serverConfig) {
closeMcpCreateModal();
await loadMcpConfig();
renderMcpManager();
showRefreshToast(`MCP server "${name}" created successfully`, 'success');
const scopeLabel = scope === 'global' ? 'global' : 'project';
showRefreshToast(`MCP server "${name}" created in ${scopeLabel} scope`, 'success');
} else {
showRefreshToast(result.error || 'Failed to create MCP server', 'error');
}

View File

@@ -112,6 +112,8 @@ function initNavigation() {
renderSkillsManager();
} else if (currentView === 'rules-manager') {
renderRulesManager();
} else if (currentView === 'claude-manager') {
renderClaudeManager();
}
});
});
@@ -144,6 +146,8 @@ function updateContentTitle() {
titleEl.textContent = t('title.skillsManager');
} else if (currentView === 'rules-manager') {
titleEl.textContent = t('title.rulesManager');
} else if (currentView === 'claude-manager') {
titleEl.textContent = t('title.claudeManager');
} else if (currentView === 'liteTasks') {
const names = { 'lite-plan': t('title.litePlanSessions'), 'lite-fix': t('title.liteFixSessions') };
titleEl.textContent = names[currentLiteType] || t('title.liteTasks');

View File

@@ -214,13 +214,13 @@ function handleNotification(data) {
if (typeof handleMemoryUpdated === 'function') {
handleMemoryUpdated(payload);
}
// Force refresh of memory view if active
if (getCurrentView && getCurrentView() === 'memory') {
if (typeof loadMemoryStats === 'function') {
loadMemoryStats().then(function() {
if (typeof renderHotspotsColumn === 'function') renderHotspotsColumn();
});
}
// Force refresh of memory view
if (typeof loadMemoryStats === 'function') {
loadMemoryStats().then(function() {
if (typeof renderHotspotsColumn === 'function') renderHotspotsColumn();
}).catch(function(err) {
console.error('[Memory] Failed to refresh stats:', err);
});
}
break;
@@ -254,15 +254,142 @@ function handleNotification(data) {
'Memory'
);
}
// Refresh Active Memory status if on memory view
if (getCurrentView && getCurrentView() === 'memory') {
if (typeof loadActiveMemoryStatus === 'function') {
loadActiveMemoryStatus();
}
// Refresh Active Memory status
if (typeof loadActiveMemoryStatus === 'function') {
loadActiveMemoryStatus().catch(function(err) {
console.error('[Active Memory] Failed to refresh status:', err);
});
}
console.log('[Active Memory] Sync completed:', payload);
break;
case 'CLAUDE_FILE_SYNCED':
// Handle CLAUDE.md file sync completion
if (typeof addGlobalNotification === 'function') {
const { path, level, tool, mode } = payload;
const fileName = path.split(/[/\\]/).pop();
addGlobalNotification(
'success',
`${fileName} synced`,
{
'Level': level,
'Tool': tool,
'Mode': mode,
'Time': new Date(payload.timestamp).toLocaleTimeString()
},
'CLAUDE.md'
);
}
// Refresh file list
if (typeof loadClaudeFiles === 'function') {
loadClaudeFiles().then(() => {
// Re-render the view to show updated content
if (typeof renderClaudeManager === 'function') {
renderClaudeManager();
}
}).catch(err => console.error('[CLAUDE.md] Failed to refresh files:', err));
}
console.log('[CLAUDE.md] Sync completed:', payload);
break;
case 'CLI_TOOL_INSTALLED':
// Handle CLI tool installation completion
if (typeof addGlobalNotification === 'function') {
const { tool } = payload;
addGlobalNotification(
'success',
`${tool} installed successfully`,
{
'Tool': tool,
'Time': new Date(payload.timestamp).toLocaleTimeString()
},
'CLI Tools'
);
}
// Refresh CLI manager
if (typeof loadCliToolStatus === 'function') {
loadCliToolStatus().then(() => {
if (typeof renderToolsSection === 'function') {
renderToolsSection();
}
}).catch(err => console.error('[CLI Tools] Failed to refresh status:', err));
}
console.log('[CLI Tools] Installation completed:', payload);
break;
case 'CLI_TOOL_UNINSTALLED':
// Handle CLI tool uninstallation completion
if (typeof addGlobalNotification === 'function') {
const { tool } = payload;
addGlobalNotification(
'success',
`${tool} uninstalled successfully`,
{
'Tool': tool,
'Time': new Date(payload.timestamp).toLocaleTimeString()
},
'CLI Tools'
);
}
// Refresh CLI manager
if (typeof loadCliToolStatus === 'function') {
loadCliToolStatus().then(() => {
if (typeof renderToolsSection === 'function') {
renderToolsSection();
}
}).catch(err => console.error('[CLI Tools] Failed to refresh status:', err));
}
console.log('[CLI Tools] Uninstallation completed:', payload);
break;
case 'CODEXLENS_INSTALLED':
// Handle CodexLens installation completion
if (typeof addGlobalNotification === 'function') {
const { version } = payload;
addGlobalNotification(
'success',
`CodexLens installed successfully`,
{
'Version': version || 'latest',
'Time': new Date(payload.timestamp).toLocaleTimeString()
},
'CodexLens'
);
}
// Refresh CLI status if active
if (typeof loadCodexLensStatus === 'function') {
loadCodexLensStatus().then(() => {
if (typeof renderCliStatus === 'function') {
renderCliStatus();
}
});
}
console.log('[CodexLens] Installation completed:', payload);
break;
case 'CODEXLENS_UNINSTALLED':
// Handle CodexLens uninstallation completion
if (typeof addGlobalNotification === 'function') {
addGlobalNotification(
'success',
`CodexLens uninstalled successfully`,
{
'Time': new Date(payload.timestamp).toLocaleTimeString()
},
'CodexLens'
);
}
// Refresh CLI status if active
if (typeof loadCodexLensStatus === 'function') {
loadCodexLensStatus().then(() => {
if (typeof renderCliStatus === 'function') {
renderCliStatus();
}
});
}
console.log('[CodexLens] Uninstallation completed:', payload);
break;
default:
console.log('[WS] Unknown notification type:', type);
}

View File

@@ -107,6 +107,8 @@ const i18n = {
'empty.noLiteSessionsText': 'No sessions found in .workflow/.{type}/',
'empty.noMcpServers': 'No MCP servers configured for this project',
'empty.addMcpServersHint': 'Add servers from the available list below',
'empty.noGlobalMcpServers': 'No global MCP servers configured',
'empty.globalServersHint': 'Global servers are available to all projects from ~/.claude.json',
'empty.noAdditionalMcp': 'No additional MCP servers found in other projects',
'empty.noHooks': 'No hooks configured for this project',
'empty.createHookHint': 'Create a hook to automate actions on tool usage',
@@ -197,6 +199,7 @@ const i18n = {
'cli.setDefault': 'Set Default',
'cli.default': 'Default',
'cli.install': 'Install',
'cli.uninstall': 'Uninstall',
'cli.initIndex': 'Init Index',
'cli.geminiDesc': 'Google AI for code analysis',
'cli.qwenDesc': 'Alibaba AI assistant',
@@ -205,6 +208,80 @@ const i18n = {
'cli.codexLensDescFull': 'Full-text code search engine',
'cli.semanticDesc': 'AI-powered code understanding',
'cli.semanticDescFull': 'Natural language code search',
// CodexLens Configuration
'codexlens.config': 'CodexLens Configuration',
'codexlens.status': 'Status',
'codexlens.installed': 'Installed',
'codexlens.notInstalled': 'Not Installed',
'codexlens.indexes': 'Indexes',
'codexlens.currentWorkspace': 'Current Workspace',
'codexlens.indexStoragePath': 'Index Storage Path',
'codexlens.whereIndexesStored': 'where indexes are stored',
'codexlens.currentPath': 'Current Path',
'codexlens.newStoragePath': 'New Storage Path',
'codexlens.pathPlaceholder': 'e.g., /path/to/indexes or ~/.codexlens/indexes',
'codexlens.pathInfo': 'Supports ~ for home directory. Changes take effect immediately.',
'codexlens.migrationRequired': 'Migration Required',
'codexlens.migrationWarning': 'After changing the path, existing indexes will need to be re-initialized for each workspace.',
'codexlens.actions': 'Actions',
'codexlens.initializeIndex': 'Initialize Index',
'codexlens.cleanAllIndexes': 'Clean All Indexes',
'codexlens.installCodexLens': 'Install CodexLens',
'codexlens.testSearch': 'Test Search',
'codexlens.testFunctionality': 'test CodexLens functionality',
'codexlens.textSearch': 'Text Search',
'codexlens.fileSearch': 'File Search',
'codexlens.symbolSearch': 'Symbol Search',
'codexlens.searchPlaceholder': 'Enter search query (e.g., function name, file path, code snippet)',
'codexlens.runSearch': 'Run Search',
'codexlens.results': 'Results',
'codexlens.resultsCount': 'results',
'codexlens.saveConfig': 'Save Configuration',
'codexlens.searching': 'Searching...',
'codexlens.searchCompleted': 'Search completed',
'codexlens.searchFailed': 'Search failed',
'codexlens.enterQuery': 'Please enter a search query',
'codexlens.configSaved': 'Configuration saved successfully',
'codexlens.pathEmpty': 'Index directory path cannot be empty',
'codexlens.cleanConfirm': 'Are you sure you want to clean all CodexLens indexes? This cannot be undone.',
'codexlens.cleaning': 'Cleaning indexes...',
'codexlens.cleanSuccess': 'All indexes cleaned successfully',
'codexlens.cleanFailed': 'Failed to clean indexes',
'codexlens.loadingConfig': 'Loading configuration...',
// Semantic Search Configuration
'semantic.settings': 'Semantic Search Settings',
'semantic.configDesc': 'Configure LLM enhancement for semantic indexing',
'semantic.llmEnhancement': 'LLM Enhancement',
'semantic.llmDesc': 'Use LLM to generate code summaries for better semantic search',
'semantic.primaryTool': 'Primary LLM Tool',
'semantic.fallbackTool': 'Fallback Tool',
'semantic.batchSize': 'Batch Size',
'semantic.timeout': 'Timeout',
'semantic.file': 'file',
'semantic.files': 'files',
'semantic.enhanceInfo': 'LLM enhancement generates code summaries and keywords for each file, improving semantic search accuracy.',
'semantic.enhanceCommand': 'Run',
'semantic.enhanceAfterEnable': 'after enabling to process existing files.',
'semantic.runEnhanceNow': 'Run Enhance Now',
'semantic.viewStatus': 'View Status',
'semantic.testSearch': 'Test Semantic Search',
'semantic.searchPlaceholder': 'Enter semantic query (e.g., authentication logic, error handling)',
'semantic.runSearch': 'Run Semantic Search',
'semantic.close': 'Close',
'semantic.enabled': 'enabled',
'semantic.disabled': 'disabled',
'semantic.toolSetTo': 'Primary LLM tool set to',
'semantic.fallbackSetTo': 'Fallback tool set to',
'semantic.none': 'none',
'semantic.llmEnhancement': 'LLM Enhancement',
'semantic.batchSetTo': 'Batch size set to',
'semantic.timeoutSetTo': 'Timeout set to',
'semantic.minute': 'minute',
'semantic.minutes': 'minutes',
'semantic.enableFirst': 'Please enable LLM Enhancement first',
'cli.settings': 'CLI Execution Settings',
'cli.promptFormat': 'Prompt Format',
'cli.promptFormatDesc': 'Format for multi-turn conversation concatenation',
@@ -296,9 +373,18 @@ const i18n = {
'updateClaudeMd.cancel': 'Cancel',
// MCP Manager
'mcp.currentProject': 'Current Project MCP Servers',
'mcp.currentAvailable': 'Current Available MCP',
'mcp.projectAvailable': 'Current Available MCP',
'mcp.newProjectServer': 'New Project Server',
'mcp.newServer': 'New Server',
'mcp.newGlobalServer': 'New Global Server',
'mcp.copyInstallCmd': 'Copy Install Command',
'mcp.installCmdCopied': 'Install command copied to clipboard',
'mcp.installCmdFailed': 'Failed to copy install command',
'mcp.serversConfigured': 'servers configured',
'mcp.serversAvailable': 'servers available',
'mcp.globalAvailable': '全局可用 MCP',
'mcp.globalServersFrom': '个服务器来自 ~/.claude.json',
'mcp.enterprise': 'Enterprise MCP Servers',
'mcp.enterpriseManaged': 'Managed',
'mcp.enterpriseReadOnly': 'servers (read-only)',
@@ -315,21 +401,28 @@ const i18n = {
'mcp.noMcpServers': 'No MCP servers',
'mcp.add': 'Add',
'mcp.addToProject': 'Add to Project',
'mcp.installToProject': 'Install to project',
'mcp.installToGlobal': 'Install to global',
'mcp.removeFromProject': 'Remove from project',
'mcp.removeConfirm': 'Remove MCP server "{name}" from this project?',
'mcp.removeGlobal': 'Remove from global scope',
'mcp.removeGlobalConfirm': 'Remove global MCP server "{name}"? This will affect all projects.',
'mcp.readOnly': 'Read-only',
'mcp.usedIn': 'Used in {count} project',
'mcp.usedInPlural': 'Used in {count} projects',
'mcp.availableToAll': 'Available to all projects from ~/.claude.json',
'mcp.managedByOrg': 'Managed by organization (highest priority)',
'mcp.variables': 'variables',
// MCP Create Modal
'mcp.createTitle': 'Create MCP Server',
'mcp.form': 'Form',
'mcp.json': 'JSON',
'mcp.serverName': 'Server Name',
'mcp.serverNamePlaceholder': 'e.g., my-mcp-server',
'mcp.scope': 'Scope',
'mcp.scopeProject': 'Project - Only this project',
'mcp.scopeGlobal': 'Global - All projects (~/.claude.json)',
'mcp.command': 'Command',
'mcp.commandPlaceholder': 'e.g., npx, uvx, node, python',
'mcp.arguments': 'Arguments (one per line)',
@@ -653,6 +746,30 @@ const i18n = {
'skills.deleteError': 'Failed to delete skill',
'skills.editNotImplemented': 'Edit feature coming soon',
'skills.createNotImplemented': 'Create feature coming soon',
'skills.createSkill': 'Create Skill', 'skills.sourceFolder': 'Source Folder', 'skills.sourceFolderPlaceholder': 'Path to skill folder', 'skills.sourceFolderHint': 'Select a folder containing a valid SKILL.md file', 'skills.sourceFolderRequired': 'Source folder path is required', 'skills.customName': 'Custom Name', 'skills.customNamePlaceholder': 'Leave empty to use skill name from SKILL.md', 'skills.customNameHint': 'Optional: Override the skill name', 'skills.validate': 'Validate', 'skills.import': 'Import', 'skills.validating': 'Validating...', 'skills.validSkill': 'Valid Skill', 'skills.invalidSkill': 'Invalid Skill', 'skills.validateFirst': 'Please validate the skill folder first', 'skills.created': 'Skill "{name}" created successfully', 'skills.createError': 'Failed to create skill', 'skills.validationError': 'Validation failed', 'skills.enterFolderPath': 'Enter skill folder path', 'skills.name': 'Name',
'skills.createMode': 'Creation Mode',
'skills.importFolder': 'Import Folder',
'skills.importFolderHint': 'Import existing skill folder',
'skills.cliGenerate': 'CLI Generate',
'skills.cliGenerateHint': 'Generate using AI',
'skills.generationType': 'Generation Type',
'skills.fromDescription': 'From Description',
'skills.fromDescriptionHint': 'Describe what you need',
'skills.fromTemplate': 'From Template',
'skills.comingSoon': 'Coming soon',
'skills.skillName': 'Skill Name',
'skills.skillNamePlaceholder': 'e.g., code-review, testing-helper',
'skills.skillNameHint': 'Choose a descriptive name for the skill',
'skills.skillNameRequired': 'Skill name is required',
'skills.descriptionPlaceholder': 'Describe what this skill should help with...\nExample: Help review code for security vulnerabilities and best practices',
'skills.descriptionRequired': 'Description is required',
'skills.descriptionGenerateHint': 'Be specific about what the skill should do',
'skills.generating': 'Generating skill via CLI... This may take a few minutes.',
'skills.generated': 'Skill "{name}" generated successfully',
'skills.generateError': 'Failed to generate skill',
'skills.generate': 'Generate',
'skills.cliGenerateInfo': 'AI will generate a complete skill based on your description',
'skills.cliGenerateTimeHint': 'Generation may take a few minutes depending on complexity',
// Rules
'nav.rules': 'Rules',
@@ -679,9 +796,116 @@ const i18n = {
'rules.deleteError': 'Failed to delete rule',
'rules.editNotImplemented': 'Edit feature coming soon',
'rules.createNotImplemented': 'Create feature coming soon',
'rules.createRule': 'Create Rule',
'rules.location': 'Location',
'rules.fileName': 'File Name',
'rules.fileNameHint': 'Must end with .md',
'rules.fileNameRequired': 'File name is required',
'rules.fileNameMustEndMd': 'File name must end with .md',
'rules.subdirectory': 'Subdirectory',
'rules.subdirectoryHint': 'Optional: Organize rules into subdirectories',
'rules.conditionalRule': 'Conditional Rule',
'rules.conditionalHint': 'Apply this rule only to specific file paths',
'rules.addPath': 'Add Path',
'rules.contentPlaceholder': 'Enter rule content in Markdown format...',
'rules.contentHint': 'Use Markdown to write rule instructions for Claude',
'rules.contentRequired': 'Content is required',
'rules.created': 'Rule "{name}" created successfully',
'rules.createError': 'Failed to create rule',
'rules.createMode': 'Creation Mode',
'rules.manualInput': 'Manual Input',
'rules.manualInputHint': 'Write content directly',
'rules.cliGenerate': 'CLI Generate',
'rules.cliGenerateHint': 'Auto-generate via AI',
'rules.generationType': 'Generation Type',
'rules.fromDescription': 'From Description',
'rules.fromTemplate': 'From Template',
'rules.fromCodeExtract': 'Extract from Code',
'rules.description': 'Description',
'rules.descriptionPlaceholder': 'Describe the rule purpose and instructions...',
'rules.descriptionHint': 'AI will generate rule content based on your description',
'rules.descriptionRequired': 'Description is required',
'rules.extractScope': 'Analysis Scope',
'rules.extractScopeHint': 'File patterns to analyze (e.g., src/**/*.ts)',
'rules.extractScopeRequired': 'Analysis scope is required',
'rules.extractFocus': 'Focus Areas',
'rules.extractFocusHint': 'Comma-separated aspects to focus on (e.g., naming, error-handling)',
'rules.cliGenerating': 'Generating rule via CLI (this may take a few minutes)...',
// CLAUDE.md Manager
'nav.claudeManager': 'CLAUDE.md',
'title.claudeManager': 'CLAUDE.md Manager',
'claudeManager.title': 'CLAUDE.md Files',
'claudeManager.files': 'files',
'claudeManager.userLevel': 'User Level',
'claudeManager.projectLevel': 'Project Level',
'claudeManager.moduleLevel': 'Module Level',
'claudeManager.noFile': 'No CLAUDE.md file',
'claudeManager.noModules': 'No module CLAUDE.md files',
'claudeManager.selectFile': 'Select a file to view',
'claudeManager.noMetadata': 'Select a file to see metadata',
'claudeManager.fileInfo': 'File Information',
'claudeManager.level': 'Level',
'claudeManager.level_user': 'User (~/.claude/)',
'claudeManager.level_project': 'Project (.claude/)',
'claudeManager.level_module': 'Module',
'claudeManager.path': 'Path',
'claudeManager.size': 'Size',
'claudeManager.modified': 'Modified',
'claudeManager.statistics': 'Statistics',
'claudeManager.lines': 'Lines',
'claudeManager.words': 'Words',
'claudeManager.characters': 'Characters',
'claudeManager.actions': 'Actions',
'claudeManager.loadError': 'Failed to load CLAUDE.md files',
'claudeManager.refreshed': 'Files refreshed successfully',
'claudeManager.unsavedChanges': 'You have unsaved changes. Discard them?',
'claudeManager.saved': 'File saved successfully',
'claudeManager.saveError': 'Failed to save file',
// CLI Sync (used in claude-manager.js)
'claude.cliSync': 'CLI Auto-Sync',
'claude.tool': 'Tool',
'claude.mode': 'Mode',
'claude.syncButton': 'Sync with CLI',
'claude.syncing': 'Analyzing with {tool}...',
'claude.syncSuccess': '{file} synced successfully',
'claude.syncError': 'Sync failed: {error}',
'claude.modeUpdate': 'Update (Smart Merge)',
'claude.modeGenerate': 'Generate (Full Replace)',
'claude.modeAppend': 'Append',
'claude.searchPlaceholder': 'Search files...',
'claude.viewModeClaude': 'CLAUDE.md Only',
'claude.viewModeAll': 'All Files',
'claude.createFile': 'Create File',
'claude.createDialogTitle': 'Create CLAUDE.md File',
'claude.selectLevel': 'Level',
'claude.levelUser': 'User (~/.claude/)',
'claude.levelProject': 'Project (.claude/)',
'claude.levelModule': 'Module (custom path)',
'claude.modulePath': 'Module Path',
'claude.selectTemplate': 'Template',
'claude.templateDefault': 'Default',
'claude.templateMinimal': 'Minimal',
'claude.templateComprehensive': 'Comprehensive',
'claude.deleteFile': 'Delete File',
'claude.deleteConfirm': 'Are you sure you want to delete {file}?',
'claude.deleteWarning': 'This action cannot be undone.',
'claude.copyContent': 'Copy Content',
'claude.contentCopied': 'Content copied to clipboard',
'claude.copyError': 'Failed to copy content',
'claude.modulePathRequired': 'Module path is required',
'claude.fileCreated': 'File created successfully',
'claude.createFileError': 'Failed to create file',
'claude.fileDeleted': 'File deleted successfully',
'claude.deleteFileError': 'Failed to delete file',
'claude.loadAllFilesError': 'Failed to load all files',
'claude.unsupportedFileType': 'Unsupported file type',
'claude.loadFileError': 'Failed to load file',
// Common
'common.cancel': 'Cancel',
'common.optional': '(Optional)',
'common.create': 'Create',
'common.save': 'Save',
'common.delete': 'Delete',
@@ -696,6 +920,10 @@ const i18n = {
'common.remove': 'Remove',
'common.removeFromRecent': 'Remove from recent',
'common.noDescription': 'No description',
'common.saving': 'Saving...',
'common.saveFailed': 'Failed to save',
'common.unknownError': 'Unknown error',
'common.exception': 'Exception',
},
zh: {
@@ -797,6 +1025,8 @@ const i18n = {
'empty.noLiteSessionsText': '在 .workflow/.{type}/ 目录中未找到会话',
'empty.noMcpServers': '该项目未配置 MCP 服务器',
'empty.addMcpServersHint': '从下方可用列表中添加服务器',
'empty.noGlobalMcpServers': '未配置全局 MCP 服务器',
'empty.globalServersHint': '全局服务器对所有项目可用,来自 ~/.claude.json',
'empty.noAdditionalMcp': '其他项目中未找到其他 MCP 服务器',
'empty.noHooks': '该项目未配置钩子',
'empty.createHookHint': '创建钩子以自动化工具使用时的操作',
@@ -887,6 +1117,7 @@ const i18n = {
'cli.setDefault': '设为默认',
'cli.default': '默认',
'cli.install': '安装',
'cli.uninstall': '卸载',
'cli.initIndex': '初始化索引',
'cli.geminiDesc': 'Google AI 代码分析',
'cli.qwenDesc': '阿里通义 AI 助手',
@@ -895,6 +1126,80 @@ const i18n = {
'cli.codexLensDescFull': '全文代码搜索引擎',
'cli.semanticDesc': 'AI 驱动的代码理解',
'cli.semanticDescFull': '自然语言代码搜索',
// CodexLens 配置
'codexlens.config': 'CodexLens 配置',
'codexlens.status': '状态',
'codexlens.installed': '已安装',
'codexlens.notInstalled': '未安装',
'codexlens.indexes': '索引',
'codexlens.currentWorkspace': '当前工作区',
'codexlens.indexStoragePath': '索引存储路径',
'codexlens.whereIndexesStored': '索引存储位置',
'codexlens.currentPath': '当前路径',
'codexlens.newStoragePath': '新存储路径',
'codexlens.pathPlaceholder': '例如:/path/to/indexes 或 ~/.codexlens/indexes',
'codexlens.pathInfo': '支持 ~ 表示用户目录。更改立即生效。',
'codexlens.migrationRequired': '需要迁移',
'codexlens.migrationWarning': '更改路径后,需要为每个工作区重新初始化索引。',
'codexlens.actions': '操作',
'codexlens.initializeIndex': '初始化索引',
'codexlens.cleanAllIndexes': '清理所有索引',
'codexlens.installCodexLens': '安装 CodexLens',
'codexlens.testSearch': '测试搜索',
'codexlens.testFunctionality': '测试 CodexLens 功能',
'codexlens.textSearch': '文本搜索',
'codexlens.fileSearch': '文件搜索',
'codexlens.symbolSearch': '符号搜索',
'codexlens.searchPlaceholder': '输入搜索查询(例如:函数名、文件路径、代码片段)',
'codexlens.runSearch': '运行搜索',
'codexlens.results': '结果',
'codexlens.resultsCount': '个结果',
'codexlens.saveConfig': '保存配置',
'codexlens.searching': '搜索中...',
'codexlens.searchCompleted': '搜索完成',
'codexlens.searchFailed': '搜索失败',
'codexlens.enterQuery': '请输入搜索查询',
'codexlens.configSaved': '配置保存成功',
'codexlens.pathEmpty': '索引目录路径不能为空',
'codexlens.cleanConfirm': '确定要清理所有 CodexLens 索引吗?此操作无法撤销。',
'codexlens.cleaning': '清理索引中...',
'codexlens.cleanSuccess': '所有索引已成功清理',
'codexlens.cleanFailed': '清理索引失败',
'codexlens.loadingConfig': '加载配置中...',
// Semantic Search 配置
'semantic.settings': '语义搜索设置',
'semantic.configDesc': '配置语义索引的 LLM 增强功能',
'semantic.llmEnhancement': 'LLM 增强',
'semantic.llmDesc': '使用 LLM 生成代码摘要以改进语义搜索',
'semantic.primaryTool': '主 LLM 工具',
'semantic.fallbackTool': '备用工具',
'semantic.batchSize': '批处理大小',
'semantic.timeout': '超时时间',
'semantic.file': '个文件',
'semantic.files': '个文件',
'semantic.enhanceInfo': 'LLM 增强为每个文件生成代码摘要和关键词,提高语义搜索准确度。',
'semantic.enhanceCommand': '运行',
'semantic.enhanceAfterEnable': '启用后处理现有文件。',
'semantic.runEnhanceNow': '立即运行增强',
'semantic.viewStatus': '查看状态',
'semantic.testSearch': '测试语义搜索',
'semantic.searchPlaceholder': '输入语义查询(例如:身份验证逻辑、错误处理)',
'semantic.runSearch': '运行语义搜索',
'semantic.close': '关闭',
'semantic.enabled': '已启用',
'semantic.disabled': '已禁用',
'semantic.toolSetTo': '主 LLM 工具已设置为',
'semantic.fallbackSetTo': '备用工具已设置为',
'semantic.none': '无',
'semantic.llmEnhancement': 'LLM 增强',
'semantic.batchSetTo': '批量大小已设置为',
'semantic.timeoutSetTo': '超时已设置为',
'semantic.minute': '分钟',
'semantic.minutes': '分钟',
'semantic.enableFirst': '请先启用 LLM 增强',
'cli.settings': 'CLI 调用设置',
'cli.promptFormat': '提示词格式',
'cli.promptFormatDesc': '多轮对话拼接格式',
@@ -986,9 +1291,18 @@ const i18n = {
'updateClaudeMd.cancel': '取消',
// MCP Manager
'mcp.currentProject': '当前项目 MCP 服务器',
'mcp.currentAvailable': '当前可用 MCP',
'mcp.copyInstallCmd': '复制安装命令',
'mcp.installCmdCopied': '安装命令已复制到剪贴板',
'mcp.installCmdFailed': '复制安装命令失败',
'mcp.projectAvailable': '当前可用 MCP',
'mcp.newServer': '新建服务器',
'mcp.newGlobalServer': '新建全局服务器',
'mcp.newProjectServer': '新建项目服务器',
'mcp.serversConfigured': '个服务器已配置',
'mcp.serversAvailable': 'servers available',
'mcp.globalAvailable': '全局可用 MCP',
'mcp.globalServersFrom': '个服务器来自 ~/.claude.json',
'mcp.enterprise': '企业 MCP 服务器',
'mcp.enterpriseManaged': '托管',
'mcp.enterpriseReadOnly': '个服务器(只读)',
@@ -1005,6 +1319,10 @@ const i18n = {
'mcp.noMcpServers': '无 MCP 服务器',
'mcp.add': '添加',
'mcp.addToProject': '添加到项目',
'mcp.installToProject': '安装到项目',
'mcp.installToGlobal': '安装到全局',
'mcp.installToProject': 'Install to project',
'mcp.installToGlobal': 'Install to global',
'mcp.removeFromProject': '从项目移除',
'mcp.removeConfirm': '从此项目移除 MCP 服务器 "{name}"',
'mcp.readOnly': '只读',
@@ -1343,6 +1661,30 @@ const i18n = {
'skills.deleteError': '删除技能失败',
'skills.editNotImplemented': '编辑功能即将推出',
'skills.createNotImplemented': '创建功能即将推出',
'skills.createSkill': '创建技能', 'skills.sourceFolder': '源文件夹', 'skills.sourceFolderPlaceholder': '技能文件夹路径', 'skills.sourceFolderHint': '选择包含有效 SKILL.md 文件的文件夹', 'skills.sourceFolderRequired': '源文件夹路径是必需的', 'skills.customName': '自定义名称', 'skills.customNamePlaceholder': '留空则使用 SKILL.md 中的技能名称', 'skills.customNameHint': '可选:覆盖技能名称', 'skills.validate': '验证', 'skills.import': '导入', 'skills.validating': '验证中...', 'skills.validSkill': '有效技能', 'skills.invalidSkill': '无效技能', 'skills.validateFirst': '请先验证技能文件夹', 'skills.created': '技能 "{name}" 创建成功', 'skills.createError': '创建技能失败', 'skills.validationError': '验证失败', 'skills.enterFolderPath': '输入技能文件夹路径', 'skills.name': '名称',
'skills.createMode': '创建模式',
'skills.importFolder': '导入文件夹',
'skills.importFolderHint': '导入现有技能文件夹',
'skills.cliGenerate': 'CLI生成',
'skills.cliGenerateHint': '使用AI生成',
'skills.generationType': '生成类型',
'skills.fromDescription': '从描述生成',
'skills.fromDescriptionHint': '描述你需要的功能',
'skills.fromTemplate': '从模板生成',
'skills.comingSoon': '即将推出',
'skills.skillName': '技能名称',
'skills.skillNamePlaceholder': '例如:代码审查、测试助手',
'skills.skillNameHint': '为技能选择一个描述性的名称',
'skills.skillNameRequired': '技能名称是必需的',
'skills.descriptionPlaceholder': '描述这个技能应该帮助什么...\n例如帮助审查代码的安全漏洞和最佳实践',
'skills.descriptionRequired': '描述是必需的',
'skills.descriptionGenerateHint': '具体说明技能应该做什么',
'skills.generating': '正在通过 CLI 生成技能...这可能需要几分钟。',
'skills.generated': '技能 "{name}" 生成成功',
'skills.generateError': '生成技能失败',
'skills.generate': '生成',
'skills.cliGenerateInfo': 'AI 将根据你的描述生成完整的技能',
'skills.cliGenerateTimeHint': '生成时间取决于复杂度,可能需要几分钟',
// Rules
'nav.rules': '规则',
@@ -1369,9 +1711,147 @@ const i18n = {
'rules.deleteError': '删除规则失败',
'rules.editNotImplemented': '编辑功能即将推出',
'rules.createNotImplemented': '创建功能即将推出',
'rules.createRule': '创建规则',
'rules.location': '位置',
'rules.fileName': '文件名',
'rules.fileNameHint': '必须以 .md 结尾',
'rules.fileNameRequired': '文件名是必需的',
'rules.fileNameMustEndMd': '文件名必须以 .md 结尾',
'rules.subdirectory': '子目录',
'rules.subdirectoryHint': '可选:将规则组织到子目录中',
'rules.conditionalRule': '条件规则',
'rules.conditionalHint': '仅对特定文件路径应用此规则',
'rules.addPath': '添加路径',
'rules.contentPlaceholder': '以 Markdown 格式输入规则内容...',
'rules.contentHint': '使用 Markdown 为 Claude 编写规则说明',
'rules.contentRequired': '内容是必需的',
'rules.created': '规则 "{name}" 创建成功',
'rules.createError': '创建规则失败',
'rules.createMode': '创建模式',
'rules.manualInput': '手动输入',
'rules.manualInputHint': '直接编写内容',
'rules.cliGenerate': 'CLI生成',
'rules.cliGenerateHint': '通过AI自动生成',
'rules.generationType': '生成类型',
'rules.fromDescription': '从描述生成',
'rules.fromTemplate': '从模板生成',
'rules.fromCodeExtract': '从代码提取',
'rules.description': '描述',
'rules.descriptionPlaceholder': '描述规则目的和说明...',
'rules.descriptionHint': 'AI将根据您的描述生成规则内容',
'rules.descriptionRequired': '描述是必需的',
'rules.extractScope': '分析范围',
'rules.extractScopeHint': '要分析的文件模式例如src/**/*.ts',
'rules.extractScopeRequired': '分析范围是必需的',
'rules.extractFocus': '关注领域',
'rules.extractFocusHint': '以逗号分隔的关注方面(例如:命名规范, 错误处理)',
'rules.cliGenerating': '正在通过 CLI 生成规则(可能需要几分钟)...',
// CLAUDE.md Manager
'nav.claudeManager': 'CLAUDE.md',
'title.claudeManager': 'CLAUDE.md 管理器',
'claudeManager.title': 'CLAUDE.md 文件',
'claudeManager.files': '个文件',
'claudeManager.userLevel': '用户级',
'claudeManager.projectLevel': '项目级',
'claudeManager.moduleLevel': '模块级',
'claudeManager.noFile': '无 CLAUDE.md 文件',
'claudeManager.noModules': '无模块 CLAUDE.md 文件',
'claudeManager.selectFile': '选择文件以查看',
'claudeManager.noMetadata': '选择文件以查看元数据',
'claudeManager.fileInfo': '文件信息',
'claudeManager.level': '级别',
'claudeManager.level_user': '用户级 (~/.claude/)',
'claudeManager.level_project': '项目级 (.claude/)',
'claudeManager.level_module': '模块级',
'claudeManager.path': '路径',
'claudeManager.size': '大小',
'claudeManager.modified': '修改时间',
'claudeManager.statistics': '统计信息',
'claudeManager.lines': '行数',
'claudeManager.words': '字数',
'claudeManager.characters': '字符数',
'claudeManager.actions': '操作',
'claudeManager.loadError': '加载 CLAUDE.md 文件失败',
'claudeManager.refreshed': '文件刷新成功',
'claudeManager.unsavedChanges': '您有未保存的更改。是否放弃?',
'claudeManager.saved': '文件保存成功',
'claudeManager.saveError': '文件保存失败',
// CLI Sync (used in claude-manager.js)
'claude.cliSync': 'CLI 自动同步',
'claude.tool': '工具',
'claude.mode': '模式',
'claude.syncButton': '使用 CLI 同步',
'claude.syncing': '正在使用 {tool} 分析...',
'claude.syncSuccess': '{file} 同步成功',
'claude.syncError': '同步失败:{error}',
'claude.modeUpdate': '更新(智能合并)',
'claude.modeGenerate': '生成(完全替换)',
'claude.modeAppend': '追加',
'claude.searchPlaceholder': '搜索文件...',
'claude.viewModeClaude': '仅 CLAUDE.md',
'claude.viewModeAll': '所有文件',
'claude.createFile': '创建文件',
'claude.createDialogTitle': '创建 CLAUDE.md 文件',
'claude.selectLevel': '层级',
'claude.levelUser': '用户级 (~/.claude/)',
'claude.levelProject': '项目级 (.claude/)',
'claude.levelModule': '模块级(自定义路径)',
'claude.modulePath': '模块路径',
'claude.selectTemplate': '模板',
'claude.templateDefault': '默认',
'claude.templateMinimal': '最小化',
'claude.templateComprehensive': '完整',
'claude.deleteFile': '删除文件',
'claude.deleteConfirm': '确定要删除 {file} 吗?',
'claude.deleteWarning': '此操作无法撤销。',
'claude.copyContent': '复制内容',
'claude.contentCopied': '内容已复制到剪贴板',
'claude.copyError': '复制内容失败',
'claude.modulePathRequired': '模块路径为必填项',
'claude.fileCreated': '文件创建成功',
'claude.createFileError': '文件创建失败',
'claude.fileDeleted': '文件删除成功',
'claude.deleteFileError': '文件删除失败',
'claude.loadAllFilesError': '加载所有文件失败',
'claude.unsupportedFileType': '不支持的文件类型',
'claude.loadFileError': '加载文件失败',
// Duplicate keys for compatibility
'nav.claudeManager': 'CLAUDE.md',
'title.claudeManager': 'CLAUDE.md Manager',
'claudeManager.title': 'CLAUDE.md Files',
'claudeManager.files': 'files',
'claudeManager.userLevel': 'User Level',
'claudeManager.projectLevel': 'Project Level',
'claudeManager.moduleLevel': 'Module Level',
'claudeManager.noFile': 'No CLAUDE.md file',
'claudeManager.noModules': 'No module CLAUDE.md files',
'claudeManager.selectFile': 'Select a file to view',
'claudeManager.noMetadata': 'Select a file to see metadata',
'claudeManager.fileInfo': 'File Information',
'claudeManager.level': 'Level',
'claudeManager.level_user': 'User (~/.claude/)',
'claudeManager.level_project': 'Project (.claude/)',
'claudeManager.level_module': 'Module',
'claudeManager.path': 'Path',
'claudeManager.size': 'Size',
'claudeManager.modified': 'Modified',
'claudeManager.statistics': 'Statistics',
'claudeManager.lines': 'Lines',
'claudeManager.words': 'Words',
'claudeManager.characters': 'Characters',
'claudeManager.actions': 'Actions',
'claudeManager.loadError': 'Failed to load CLAUDE.md files',
'claudeManager.refreshed': 'Files refreshed successfully',
'claudeManager.unsavedChanges': 'You have unsaved changes. Discard them?',
'claudeManager.saved': 'File saved successfully',
'claudeManager.saveError': 'Failed to save file',
// Common
'common.cancel': '取消',
'common.optional': '(可选)',
'common.create': '创建',
'common.save': '保存',
'common.delete': '删除',
@@ -1386,6 +1866,10 @@ const i18n = {
'common.remove': '移除',
'common.removeFromRecent': '从最近中移除',
'common.noDescription': '无描述',
'common.saving': '保存中...',
'common.saveFailed': '保存失败',
'common.unknownError': '未知错误',
'common.exception': '异常',
}
};

View File

@@ -0,0 +1,764 @@
// CLAUDE.md Manager View
// Three-column layout: File Tree | Viewer/Editor | Metadata & Actions
// ========== State Management ==========
var claudeFilesData = {
user: { main: null },
project: { main: null },
modules: [],
summary: { totalFiles: 0, totalSize: 0 }
};
var selectedFile = null;
var isEditMode = false;
var isDirty = false;
var fileTreeExpanded = {
user: true,
project: true,
modules: {}
};
var searchQuery = '';
// ========== Main Render Function ==========
async function renderClaudeManager() {
var container = document.getElementById('mainContent');
if (!container) return;
// Hide stats grid and search for claude-manager view
var statsGrid = document.getElementById('statsGrid');
var searchInput = document.getElementById('searchInput');
if (statsGrid) statsGrid.style.display = 'none';
if (searchInput) searchInput.parentElement.style.display = 'none';
// Show loading state
container.innerHTML = '<div class="claude-manager-view loading">' +
'<div class="loading-spinner"><i data-lucide="loader-2" class="w-8 h-8 animate-spin"></i></div>' +
'<p>' + t('common.loading') + '</p>' +
'</div>';
// Load data
await loadClaudeFiles();
// Render layout
container.innerHTML = '<div class="claude-manager-view">' +
'<div class="claude-manager-header">' +
'<div class="claude-manager-header-left">' +
'<h2><i data-lucide="file-code" class="w-5 h-5"></i> ' + t('claudeManager.title') + '</h2>' +
'<span class="file-count-badge">' + claudeFilesData.summary.totalFiles + ' ' + t('claudeManager.files') + '</span>' +
'</div>' +
'<div class="claude-manager-header-right">' +
'<button class="btn btn-sm btn-primary" onclick="showCreateFileDialog()">' +
'<i data-lucide="file-plus" class="w-4 h-4"></i> ' + t('claude.createFile') +
'</button>' +
'<button class="btn btn-sm btn-secondary" onclick="refreshClaudeFiles()">' +
'<i data-lucide="refresh-cw" class="w-4 h-4"></i> ' + t('common.refresh') +
'</button>' +
'</div>' +
'</div>' +
'<div class="claude-manager-columns">' +
'<div class="claude-manager-column left" id="claude-file-tree"></div>' +
'<div class="claude-manager-column center" id="claude-file-viewer"></div>' +
'<div class="claude-manager-column right" id="claude-file-metadata"></div>' +
'</div>' +
'</div>';
// Render each column
renderFileTree();
renderFileViewer();
renderFileMetadata();
// Initialize Lucide icons
if (window.lucide) lucide.createIcons();
}
// ========== Data Loading ==========
async function loadClaudeFiles() {
try {
var res = await fetch('/api/memory/claude/scan?path=' + encodeURIComponent(projectPath || ''));
if (!res.ok) throw new Error('Failed to load CLAUDE.md files');
claudeFilesData = await res.json();
updateClaudeBadge(); // Update navigation badge
} catch (error) {
console.error('Error loading CLAUDE.md files:', error);
addGlobalNotification('error', t('claudeManager.loadError'), null, 'CLAUDE.md');
}
}
async function refreshClaudeFiles() {
await loadClaudeFiles();
await renderClaudeManager();
addGlobalNotification('success', t('claudeManager.refreshed'), null, 'CLAUDE.md');
}
// ========== File Tree Rendering ==========
function renderFileTree() {
var container = document.getElementById('claude-file-tree');
if (!container) return;
var html = '<div class="file-tree">' +
// Search Box
'<div class="file-tree-search">' +
'<input type="text" id="fileSearchInput" placeholder="' + t('claude.searchPlaceholder') + '" ' +
'value="' + escapeHtml(searchQuery) + '" oninput="filterFileTree(this.value)">' +
'<i data-lucide="search" class="w-4 h-4"></i>' +
'</div>' +
renderClaudeFilesTree() +
'</div>'; // end file-tree
container.innerHTML = html;
if (window.lucide) lucide.createIcons();
}
function renderClaudeFilesTree() {
var html = '<div class="file-tree-section">' +
'<div class="file-tree-header" onclick="toggleTreeSection(\'user\')">' +
'<i data-lucide="' + (fileTreeExpanded.user ? 'chevron-down' : 'chevron-right') + '" class="w-4 h-4"></i>' +
'<i data-lucide="user" class="w-4 h-4 text-orange-500"></i>' +
'<span>' + t('claudeManager.userLevel') + '</span>' +
'<span class="file-count">' + (claudeFilesData.user.main ? 1 : 0) + '</span>' +
'</div>';
if (fileTreeExpanded.user) {
// User CLAUDE.md (only main file, no rules)
if (claudeFilesData.user.main) {
html += renderFileTreeItem(claudeFilesData.user.main, 1);
} else {
html += '<div class="file-tree-item empty" style="padding-left: 1.5rem;">' +
'<i data-lucide="file-x" class="w-4 h-4"></i>' +
'<span>' + t('claudeManager.noFile') + '</span>' +
'</div>';
}
}
html += '</div>'; // end user section
// Project section
html += '<div class="file-tree-section">' +
'<div class="file-tree-header" onclick="toggleTreeSection(\'project\')">' +
'<i data-lucide="' + (fileTreeExpanded.project ? 'chevron-down' : 'chevron-right') + '" class="w-4 h-4"></i>' +
'<i data-lucide="folder" class="w-4 h-4 text-green-500"></i>' +
'<span>' + t('claudeManager.projectLevel') + '</span>' +
'<span class="file-count">' + (claudeFilesData.project.main ? 1 : 0) + '</span>' +
'</div>';
if (fileTreeExpanded.project) {
// Project CLAUDE.md (only main file, no rules)
if (claudeFilesData.project.main) {
html += renderFileTreeItem(claudeFilesData.project.main, 1);
} else {
html += '<div class="file-tree-item empty" style="padding-left: 1.5rem;">' +
'<i data-lucide="file-x" class="w-4 h-4"></i>' +
'<span>' + t('claudeManager.noFile') + '</span>' +
'</div>';
}
}
html += '</div>'; // end project section
// Modules section
html += '<div class="file-tree-section">' +
'<div class="file-tree-header">' +
'<i data-lucide="package" class="w-4 h-4 text-blue-500"></i>' +
'<span>' + t('claudeManager.moduleLevel') + '</span>' +
'<span class="file-count">' + claudeFilesData.modules.length + '</span>' +
'</div>';
if (claudeFilesData.modules.length > 0) {
claudeFilesData.modules.forEach(function (file) {
html += renderFileTreeItem(file, 1);
});
} else {
html += '<div class="file-tree-item empty" style="padding-left: 1.5rem;">' +
'<i data-lucide="file-x" class="w-4 h-4"></i>' +
'<span>' + t('claudeManager.noModules') + '</span>' +
'</div>';
}
html += '</div>'; // end modules section
return html;
}
function renderFileTreeItem(file, indentLevel) {
var isSelected = selectedFile && selectedFile.id === file.id;
var indentPx = indentLevel * 1.5;
var safeId = file.id.replace(/'/g, "&apos;");
return '<div class="file-tree-item' + (isSelected ? ' selected' : '') + '" ' +
'onclick="selectClaudeFile(\'' + safeId + '\')" ' +
'style="padding-left: ' + indentPx + 'rem;">' +
'<i data-lucide="file-text" class="w-4 h-4"></i>' +
'<span class="file-name">' + escapeHtml(file.name) + '</span>' +
(file.parentDirectory ? '<span class="file-path-hint">' + escapeHtml(file.parentDirectory) + '</span>' : '') +
'</div>';
}
function toggleTreeSection(section) {
fileTreeExpanded[section] = !fileTreeExpanded[section];
renderFileTree();
}
async function selectClaudeFile(fileId) {
// Find file in data (only main CLAUDE.md files, no rules)
var allFiles = [
claudeFilesData.user.main,
claudeFilesData.project.main,
...claudeFilesData.modules
].filter(function (f) { return f !== null; });
selectedFile = allFiles.find(function (f) { return f.id === fileId; }) || null;
if (selectedFile) {
// Load full content if not already loaded
if (!selectedFile.content) {
try {
var res = await fetch('/api/memory/claude/file?path=' + encodeURIComponent(selectedFile.path));
if (res.ok) {
var data = await res.json();
selectedFile.content = data.content;
selectedFile.stats = data.stats;
}
} catch (error) {
console.error('Error loading file content:', error);
}
}
}
renderFileTree();
renderFileViewer();
renderFileMetadata();
}
// ========== File Viewer Rendering ==========
function renderFileViewer() {
var container = document.getElementById('claude-file-viewer');
if (!container) return;
if (!selectedFile) {
container.innerHTML = '<div class="empty-state">' +
'<i data-lucide="file-search" class="w-12 h-12 opacity-20"></i>' +
'<p>' + t('claudeManager.selectFile') + '</p>' +
'</div>';
if (window.lucide) lucide.createIcons();
return;
}
container.innerHTML = '<div class="file-viewer">' +
'<div class="file-viewer-header">' +
'<h3>' + escapeHtml(selectedFile.name) + '</h3>' +
'<div class="file-viewer-actions">' +
'<button class="btn btn-sm btn-secondary" onclick="copyFileContent()" title="' + t('claude.copyContent') + '">' +
'<i data-lucide="copy" class="w-4 h-4"></i>' +
'</button>' +
'<button class="btn btn-sm btn-secondary" onclick="toggleEditMode()" title="' + t('common.edit') + '">' +
'<i data-lucide="' + (isEditMode ? 'eye' : 'edit-2') + '" class="w-4 h-4"></i>' +
'</button>' +
'</div>' +
'</div>' +
'<div class="file-viewer-content">' +
(isEditMode ? renderEditor() : renderMarkdownContent(selectedFile.content || '')) +
'</div>' +
'</div>';
if (window.lucide) lucide.createIcons();
}
function renderMarkdownContent(content) {
// Check if marked.js is available for enhanced rendering
if (typeof marked !== 'undefined') {
try {
marked.setOptions({
gfm: true,
breaks: true,
tables: true,
smartLists: true,
highlight: function(code, lang) {
// Check if highlight.js or Prism is available
if (typeof hljs !== 'undefined' && lang) {
try {
return hljs.highlight(code, { language: lang }).value;
} catch (e) {
return escapeHtml(code);
}
} else if (typeof Prism !== 'undefined' && lang && Prism.languages[lang]) {
return Prism.highlight(code, Prism.languages[lang], lang);
}
return escapeHtml(code);
}
});
return '<div class="markdown-content">' + marked.parse(content) + '</div>';
} catch (e) {
console.error('Error rendering markdown with marked.js:', e);
}
}
// Fallback: Enhanced basic rendering
var html = escapeHtml(content);
// Headers
html = html
.replace(/^# (.*$)/gim, '<h1>$1</h1>')
.replace(/^## (.*$)/gim, '<h2>$1</h2>')
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
.replace(/^#### (.*$)/gim, '<h4>$1</h4>');
// Inline formatting
html = html
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>')
.replace(/`([^`]+)`/g, '<code>$1</code>');
// Links
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
// Task lists
html = html
.replace(/- \[ \] (.+)$/gim, '<li class="task-list-item"><input type="checkbox" disabled> $1</li>')
.replace(/- \[x\] (.+)$/gim, '<li class="task-list-item"><input type="checkbox" disabled checked> $1</li>');
// Lists
html = html.replace(/^- (.+)$/gim, '<li>$1</li>');
html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
// Code blocks
html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, function(match, lang, code) {
return '<pre><code class="language-' + (lang || 'plaintext') + '">' + code + '</code></pre>';
});
// Line breaks
html = html.replace(/\n/g, '<br>');
return '<div class="markdown-content">' + html + '</div>';
}
function renderEditor() {
return '<textarea id="claudeFileEditor" class="file-editor" ' +
'oninput="markDirty()">' +
escapeHtml(selectedFile.content || '') +
'</textarea>';
}
function toggleEditMode() {
if (isEditMode && isDirty) {
if (!confirm(t('claudeManager.unsavedChanges'))) {
return;
}
}
isEditMode = !isEditMode;
isDirty = false;
renderFileViewer();
}
function markDirty() {
isDirty = true;
}
async function saveClaudeFile() {
if (!selectedFile || !isEditMode) return;
var editor = document.getElementById('claudeFileEditor');
if (!editor) return;
var newContent = editor.value;
try {
var res = await fetch('/api/memory/claude/file', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
path: selectedFile.path,
content: newContent,
createBackup: true
})
});
if (!res.ok) throw new Error('Failed to save file');
selectedFile.content = newContent;
selectedFile.stats = calculateFileStats(newContent);
isDirty = false;
addGlobalNotification('success', t('claudeManager.saved'), null, 'CLAUDE.md');
renderFileMetadata();
} catch (error) {
console.error('Error saving file:', error);
addGlobalNotification('error', t('claudeManager.saveError'), null, 'CLAUDE.md');
}
}
function calculateFileStats(content) {
var lines = content.split('\n').length;
var words = content.split(/\s+/).filter(function (w) { return w.length > 0; }).length;
var characters = content.length;
return { lines: lines, words: words, characters: characters };
}
// ========== File Metadata Rendering ==========
function renderFileMetadata() {
var container = document.getElementById('claude-file-metadata');
if (!container) return;
if (!selectedFile) {
container.innerHTML = '<div class="empty-state">' +
'<i data-lucide="info" class="w-8 h-8 opacity-20"></i>' +
'<p>' + t('claudeManager.noMetadata') + '</p>' +
'</div>';
if (window.lucide) lucide.createIcons();
return;
}
var html = '<div class="file-metadata">' +
'<div class="metadata-section">' +
'<h4>' + t('claudeManager.fileInfo') + '</h4>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.level') + '</span>' +
'<span class="value">' + t('claudeManager.level_' + selectedFile.level) + '</span>' +
'</div>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.path') + '</span>' +
'<span class="value path">' + escapeHtml(selectedFile.relativePath) + '</span>' +
'</div>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.size') + '</span>' +
'<span class="value">' + formatFileSize(selectedFile.size) + '</span>' +
'</div>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.modified') + '</span>' +
'<span class="value">' + formatDate(selectedFile.lastModified) + '</span>' +
'</div>' +
'</div>';
if (selectedFile.stats) {
html += '<div class="metadata-section">' +
'<h4>' + t('claudeManager.statistics') + '</h4>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.lines') + '</span>' +
'<span class="value">' + selectedFile.stats.lines + '</span>' +
'</div>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.words') + '</span>' +
'<span class="value">' + selectedFile.stats.words + '</span>' +
'</div>' +
'<div class="metadata-item">' +
'<span class="label">' + t('claudeManager.characters') + '</span>' +
'<span class="value">' + selectedFile.stats.characters + '</span>' +
'</div>' +
'</div>';
}
html += '<div class="metadata-section">' +
'<h4>' + t('claudeManager.actions') + '</h4>';
if (isEditMode) {
html += '<button class="btn btn-sm btn-primary full-width" onclick="saveClaudeFile()"' +
(isDirty ? '' : ' disabled') + '>' +
'<i data-lucide="save" class="w-4 h-4"></i> ' + t('common.save') +
'</button>';
html += '<button class="btn btn-sm btn-secondary full-width" onclick="toggleEditMode()">' +
'<i data-lucide="x" class="w-4 h-4"></i> ' + t('common.cancel') +
'</button>';
} else {
html += '<button class="btn btn-sm btn-secondary full-width" onclick="toggleEditMode()">' +
'<i data-lucide="edit-2" class="w-4 h-4"></i> ' + t('common.edit') +
'</button>';
}
// Delete button (only for CLAUDE.md files, not in edit mode)
if (!isEditMode && selectedFile.level !== 'file') {
html += '<button class="btn btn-sm btn-danger full-width" onclick="confirmDeleteFile()">' +
'<i data-lucide="trash-2" class="w-4 h-4"></i> ' + t('claude.deleteFile') +
'</button>';
}
html += '</div>'; // end actions section
// CLI Sync Panel
html += '<div class="metadata-section cli-sync-panel">' +
'<div class="panel-header">' +
'<i data-lucide="sparkles" class="w-4 h-4"></i>' +
'<span>' + (t('claude.cliSync') || 'CLI Auto-Sync') + '</span>' +
'</div>' +
'<div class="sync-config">' +
'<label>' + (t('claude.tool') || 'Tool') + '</label>' +
'<select id="cliToolSelect" class="sync-select">' +
'<option value="gemini">Gemini</option>' +
'<option value="qwen">Qwen</option>' +
'</select>' +
'<label>' + (t('claude.mode') || 'Mode') + '</label>' +
'<select id="cliModeSelect" class="sync-select">' +
'<option value="update">' + (t('claude.modeUpdate') || 'Update (Smart Merge)') + '</option>' +
'<option value="generate">' + (t('claude.modeGenerate') || 'Generate (Full Replace)') + '</option>' +
'<option value="append">' + (t('claude.modeAppend') || 'Append') + '</option>' +
'</select>' +
'</div>' +
'<button class="btn btn-sm btn-primary full-width sync-button" onclick="syncFileWithCLI()" id="cliSyncButton">' +
'<i data-lucide="refresh-cw" class="w-4 h-4"></i> ' +
(t('claude.syncButton') || 'Sync with CLI') +
'</button>' +
'<div id="syncProgress" class="sync-progress" style="display:none;">' +
'<i data-lucide="loader" class="w-4 h-4"></i>' +
'<span id="syncProgressText">' + (t('claude.syncing') || 'Analyzing...') + '</span>' +
'</div>' +
'</div>'; // end cli-sync-panel
html += '</div>'; // end file-metadata
container.innerHTML = html;
if (window.lucide) lucide.createIcons();
}
// ========== CLI Sync Functions ==========
async function syncFileWithCLI() {
if (!selectedFile) return;
var tool = document.getElementById('cliToolSelect').value;
var mode = document.getElementById('cliModeSelect').value;
// Show progress
showSyncProgress(true, tool);
// Disable sync button
var syncButton = document.getElementById('cliSyncButton');
if (syncButton) syncButton.disabled = true;
try {
var response = await fetch('/api/memory/claude/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
level: selectedFile.level,
path: selectedFile.level === 'module' ? selectedFile.path.replace(/CLAUDE\.md$/, '').replace(/\/$/, '') : undefined,
tool: tool,
mode: mode
})
});
var result = await response.json();
if (result.success) {
// Reload file content
var fileData = await loadFileContent(selectedFile.path);
if (fileData) {
selectedFile = fileData;
renderFileViewer();
renderFileMetadata();
}
showClaudeNotification('success', (t('claude.syncSuccess') || 'Synced successfully').replace('{file}', selectedFile.name));
} else {
showClaudeNotification('error', (t('claude.syncError') || 'Sync failed').replace('{error}', result.error || 'Unknown error'));
}
} catch (error) {
console.error('CLI sync error:', error);
showClaudeNotification('error', (t('claude.syncError') || 'Sync failed').replace('{error}', error.message));
} finally {
showSyncProgress(false);
if (syncButton) syncButton.disabled = false;
}
}
function showSyncProgress(show, tool) {
var progressEl = document.getElementById('syncProgress');
var progressText = document.getElementById('syncProgressText');
if (!progressEl) return;
if (show) {
progressEl.style.display = 'flex';
if (progressText) {
var text = (t('claude.syncing') || 'Analyzing with {tool}...').replace('{tool}', tool || 'CLI');
progressText.textContent = text;
}
if (window.lucide) lucide.createIcons();
} else {
progressEl.style.display = 'none';
}
}
async function loadFileContent(filePath) {
try {
var res = await fetch('/api/memory/claude/file?path=' + encodeURIComponent(filePath));
if (!res.ok) return null;
return await res.json();
} catch (error) {
console.error('Error loading file content:', error);
return null;
}
}
function showClaudeNotification(type, message) {
// Use global notification system if available
if (typeof addGlobalNotification === 'function') {
addGlobalNotification(type, message, null, 'CLAUDE.md');
} else {
// Fallback to simple alert
alert(message);
}
}
// ========== Search Functions ==========
function filterFileTree(query) {
searchQuery = query.toLowerCase();
renderFileTree();
// Add keyboard shortcut handler
if (query && !window.claudeSearchKeyboardHandlerAdded) {
document.addEventListener('keydown', handleSearchKeyboard);
window.claudeSearchKeyboardHandlerAdded = true;
}
}
function handleSearchKeyboard(e) {
// Ctrl+F or Cmd+F
if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
e.preventDefault();
var searchInput = document.getElementById('fileSearchInput');
if (searchInput) {
searchInput.focus();
searchInput.select();
}
}
}
// ========== File Creation Functions ==========
function showCreateFileDialog() {
var dialog = '<div class="modal-overlay" onclick="closeCreateDialog()">' +
'<div class="create-dialog" onclick="event.stopPropagation()">' +
'<h3>' + t('claude.createDialogTitle') + '</h3>' +
'<div class="dialog-form">' +
'<label>' + t('claude.selectLevel') + '</label>' +
'<select id="createLevel" onchange="toggleModulePathInput(this.value)">' +
'<option value="user">' + t('claude.levelUser') + '</option>' +
'<option value="project">' + t('claude.levelProject') + '</option>' +
'<option value="module">' + t('claude.levelModule') + '</option>' +
'</select>' +
'<label id="modulePathLabel" style="display:none;">' + t('claude.modulePath') + '</label>' +
'<input id="modulePath" type="text" style="display:none;" placeholder="e.g., src/components">' +
'<label>' + t('claude.selectTemplate') + '</label>' +
'<select id="createTemplate">' +
'<option value="default">' + t('claude.templateDefault') + '</option>' +
'<option value="minimal">' + t('claude.templateMinimal') + '</option>' +
'<option value="comprehensive">' + t('claude.templateComprehensive') + '</option>' +
'</select>' +
'</div>' +
'<div class="dialog-buttons">' +
'<button onclick="closeCreateDialog()" class="btn btn-sm btn-secondary">' + t('common.cancel') + '</button>' +
'<button onclick="createNewFile()" class="btn btn-sm btn-primary">' + t('claude.createFile') + '</button>' +
'</div>' +
'</div>' +
'</div>';
document.body.insertAdjacentHTML('beforeend', dialog);
if (window.lucide) lucide.createIcons();
}
function closeCreateDialog() {
var overlay = document.querySelector('.modal-overlay');
if (overlay) overlay.remove();
}
function toggleModulePathInput(level) {
var pathLabel = document.getElementById('modulePathLabel');
var pathInput = document.getElementById('modulePath');
if (level === 'module') {
pathLabel.style.display = 'block';
pathInput.style.display = 'block';
} else {
pathLabel.style.display = 'none';
pathInput.style.display = 'none';
}
}
async function createNewFile() {
var level = document.getElementById('createLevel').value;
var template = document.getElementById('createTemplate').value;
var modulePath = document.getElementById('modulePath').value;
if (level === 'module' && !modulePath) {
addGlobalNotification('error', t('claude.modulePathRequired') || 'Module path is required', null, 'CLAUDE.md');
return;
}
try {
var res = await fetch('/api/memory/claude/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
level: level,
path: modulePath || undefined,
template: template
})
});
if (!res.ok) throw new Error('Failed to create file');
var result = await res.json();
closeCreateDialog();
addGlobalNotification('success', t('claude.fileCreated') || 'File created successfully', null, 'CLAUDE.md');
// Refresh file tree
await refreshClaudeFiles();
} catch (error) {
console.error('Error creating file:', error);
addGlobalNotification('error', t('claude.createFileError') || 'Failed to create file', null, 'CLAUDE.md');
}
}
// ========== File Deletion Functions ==========
async function confirmDeleteFile() {
if (!selectedFile) return;
var confirmed = confirm(
(t('claude.deleteConfirm') || 'Are you sure you want to delete {file}?').replace('{file}', selectedFile.name) + '\n\n' +
'Path: ' + selectedFile.path + '\n\n' +
(t('claude.deleteWarning') || 'This action cannot be undone.')
);
if (!confirmed) return;
try {
var res = await fetch('/api/memory/claude/file?path=' + encodeURIComponent(selectedFile.path) + '&confirm=true', {
method: 'DELETE'
});
if (!res.ok) throw new Error('Failed to delete file');
addGlobalNotification('success', t('claude.fileDeleted') || 'File deleted successfully', null, 'CLAUDE.md');
selectedFile = null;
// Refresh file tree
await refreshClaudeFiles();
} catch (error) {
console.error('Error deleting file:', error);
addGlobalNotification('error', t('claude.deleteFileError') || 'Failed to delete file', null, 'CLAUDE.md');
}
}
// ========== Copy Content Function ==========
function copyFileContent() {
if (!selectedFile || !selectedFile.content) return;
navigator.clipboard.writeText(selectedFile.content).then(function() {
addGlobalNotification('success', t('claude.contentCopied') || 'Content copied to clipboard', null, 'CLAUDE.md');
}).catch(function(error) {
console.error('Error copying content:', error);
addGlobalNotification('error', t('claude.copyError') || 'Failed to copy content', null, 'CLAUDE.md');
});
}
// ========== Utility Functions ==========
// Note: escapeHtml and formatDate are imported from utils.js
function formatFileSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
// Update navigation badge with total file count
function updateClaudeBadge() {
var badge = document.getElementById('badgeClaude');
if (badge && claudeFilesData && claudeFilesData.summary) {
var total = claudeFilesData.summary.totalFiles;
badge.textContent = total;
}
}

View File

@@ -207,32 +207,14 @@ function initToolConfigModalEvents(tool, currentConfig, models) {
// Install/Uninstall
var installBtn = document.getElementById('installBtn');
if (installBtn) {
installBtn.onclick = async function() {
installBtn.onclick = function() {
var status = cliToolStatus[tool] || {};
var endpoint = status.available ? '/api/cli/uninstall' : '/api/cli/install';
var action = status.available ? 'uninstalling' : 'installing';
showRefreshToast(tool.charAt(0).toUpperCase() + tool.slice(1) + ' ' + action + '...', 'info');
closeModal();
try {
var response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tool: tool })
});
var result = await response.json();
if (result.success) {
showRefreshToast(result.message || (tool + ' ' + (status.available ? 'uninstalled' : 'installed')), 'success');
await loadCliToolStatus();
renderToolsSection();
if (window.lucide) lucide.createIcons();
} else {
showRefreshToast(result.error || 'Operation failed', 'error');
}
} catch (err) {
showRefreshToast('Failed: ' + err.message, 'error');
if (status.available) {
openCliUninstallWizard(tool);
} else {
openCliInstallWizard(tool);
}
};
}
@@ -384,20 +366,22 @@ function renderToolsSection() {
}).join('');
// CodexLens item
var codexLensHtml = '<div class="tool-item ' + (codexLensStatus.ready ? 'available' : 'unavailable') + '">' +
var codexLensHtml = '<div class="tool-item clickable ' + (codexLensStatus.ready ? 'available' : 'unavailable') + '" onclick="showCodexLensConfigModal()">' +
'<div class="tool-item-left">' +
'<span class="tool-status-dot ' + (codexLensStatus.ready ? 'status-available' : 'status-unavailable') + '"></span>' +
'<div class="tool-item-info">' +
'<div class="tool-item-name">CodexLens <span class="tool-type-badge">Index</span></div>' +
'<div class="tool-item-name">CodexLens <span class="tool-type-badge">Index</span>' +
'<i data-lucide="settings" class="w-3 h-3 tool-config-icon"></i></div>' +
'<div class="tool-item-desc">' + (codexLensStatus.ready ? t('cli.codexLensDesc') : t('cli.codexLensDescFull')) + '</div>' +
'</div>' +
'</div>' +
'<div class="tool-item-right">' +
(codexLensStatus.ready
? '<span class="tool-status-text success"><i data-lucide="check-circle" class="w-3.5 h-3.5"></i> v' + (codexLensStatus.version || 'installed') + '</span>' +
'<button class="btn-sm btn-outline" onclick="initCodexLensIndex()"><i data-lucide="database" class="w-3 h-3"></i> ' + t('cli.initIndex') + '</button>'
'<button class="btn-sm btn-outline" onclick="event.stopPropagation(); initCodexLensIndex()"><i data-lucide="database" class="w-3 h-3"></i> ' + t('cli.initIndex') + '</button>' +
'<button class="btn-sm btn-outline btn-danger" onclick="event.stopPropagation(); uninstallCodexLens()"><i data-lucide="trash-2" class="w-3 h-3"></i> ' + t('cli.uninstall') + '</button>'
: '<span class="tool-status-text muted"><i data-lucide="circle-dashed" class="w-3.5 h-3.5"></i> ' + t('cli.notInstalled') + '</span>' +
'<button class="btn-sm btn-primary" onclick="installCodexLens()"><i data-lucide="download" class="w-3 h-3"></i> ' + t('cli.install') + '</button>') +
'<button class="btn-sm btn-primary" onclick="event.stopPropagation(); installCodexLens()"><i data-lucide="download" class="w-3 h-3"></i> ' + t('cli.install') + '</button>') +
'</div>' +
'</div>';
@@ -1203,3 +1187,607 @@ function handleCliExecutionError(payload) {
currentCliExecution = null;
}
// ========== CLI Tool Install/Uninstall Wizards ==========
function openCliInstallWizard(toolName) {
var toolDescriptions = {
gemini: 'Google AI for code analysis and generation',
qwen: 'Alibaba AI assistant for coding',
codex: 'OpenAI code generation and understanding',
claude: 'Anthropic AI assistant'
};
var toolPackages = {
gemini: '@google/gemini-cli',
qwen: '@qwen-code/qwen-code',
codex: '@openai/codex',
claude: '@anthropic-ai/claude-code'
};
var modal = document.createElement('div');
modal.id = 'cliInstallModal';
modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50';
modal.innerHTML =
'<div class="bg-card rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden">' +
'<div class="p-6">' +
'<div class="flex items-center gap-3 mb-4">' +
'<div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">' +
'<i data-lucide="download" class="w-5 h-5 text-primary"></i>' +
'</div>' +
'<div>' +
'<h3 class="text-lg font-semibold">Install ' + toolName.charAt(0).toUpperCase() + toolName.slice(1) + '</h3>' +
'<p class="text-sm text-muted-foreground">' + (toolDescriptions[toolName] || 'CLI tool') + '</p>' +
'</div>' +
'</div>' +
'<div class="space-y-4">' +
'<div class="bg-muted/50 rounded-lg p-4">' +
'<h4 class="font-medium mb-2">What will be installed:</h4>' +
'<ul class="text-sm space-y-2 text-muted-foreground">' +
'<li class="flex items-start gap-2">' +
'<i data-lucide="check" class="w-4 h-4 text-success mt-0.5"></i>' +
'<span><strong>NPM Package:</strong> <code class="bg-muted px-1 rounded">' + (toolPackages[toolName] || toolName) + '</code></span>' +
'</li>' +
'<li class="flex items-start gap-2">' +
'<i data-lucide="check" class="w-4 h-4 text-success mt-0.5"></i>' +
'<span><strong>Global installation</strong> - Available system-wide</span>' +
'</li>' +
'<li class="flex items-start gap-2">' +
'<i data-lucide="check" class="w-4 h-4 text-success mt-0.5"></i>' +
'<span><strong>CLI commands</strong> - Accessible from terminal</span>' +
'</li>' +
'</ul>' +
'</div>' +
'<div class="bg-primary/5 border border-primary/20 rounded-lg p-3">' +
'<div class="flex items-start gap-2">' +
'<i data-lucide="info" class="w-4 h-4 text-primary mt-0.5"></i>' +
'<div class="text-sm text-muted-foreground">' +
'<p class="font-medium text-foreground">Installation Method</p>' +
'<p class="mt-1">Uses <code class="bg-muted px-1 rounded">npm install -g</code></p>' +
'<p class="mt-1">First installation may take 1-2 minutes depending on network speed.</p>' +
'</div>' +
'</div>' +
'</div>' +
'<div id="cliInstallProgress" class="hidden">' +
'<div class="flex items-center gap-3">' +
'<div class="animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full"></div>' +
'<span class="text-sm" id="cliInstallStatus">Starting installation...</span>' +
'</div>' +
'<div class="mt-2 h-2 bg-muted rounded-full overflow-hidden">' +
'<div id="cliInstallProgressBar" class="h-full bg-primary transition-all duration-300" style="width: 0%"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="border-t border-border p-4 flex justify-end gap-3 bg-muted/30">' +
'<button class="btn-outline px-4 py-2" onclick="closeCliInstallWizard()">Cancel</button>' +
'<button id="cliInstallBtn" class="btn-primary px-4 py-2" onclick="startCliInstall(\'' + toolName + '\')">' +
'<i data-lucide="download" class="w-4 h-4 mr-2"></i>' +
'Install Now' +
'</button>' +
'</div>' +
'</div>';
document.body.appendChild(modal);
if (window.lucide) {
lucide.createIcons();
}
}
function closeCliInstallWizard() {
var modal = document.getElementById('cliInstallModal');
if (modal) {
modal.remove();
}
}
async function startCliInstall(toolName) {
var progressDiv = document.getElementById('cliInstallProgress');
var installBtn = document.getElementById('cliInstallBtn');
var statusText = document.getElementById('cliInstallStatus');
var progressBar = document.getElementById('cliInstallProgressBar');
progressDiv.classList.remove('hidden');
installBtn.disabled = true;
installBtn.innerHTML = '<span class="animate-pulse">Installing...</span>';
var stages = [
{ progress: 20, text: 'Connecting to NPM registry...' },
{ progress: 40, text: 'Downloading package...' },
{ progress: 60, text: 'Installing dependencies...' },
{ progress: 80, text: 'Setting up CLI commands...' },
{ progress: 95, text: 'Finalizing installation...' }
];
var currentStage = 0;
var progressInterval = setInterval(function() {
if (currentStage < stages.length) {
statusText.textContent = stages[currentStage].text;
progressBar.style.width = stages[currentStage].progress + '%';
currentStage++;
}
}, 1000);
try {
var response = await fetch('/api/cli/install', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tool: toolName })
});
clearInterval(progressInterval);
var result = await response.json();
if (result.success) {
progressBar.style.width = '100%';
statusText.textContent = 'Installation complete!';
setTimeout(function() {
closeCliInstallWizard();
showRefreshToast(toolName + ' installed successfully!', 'success');
loadCliToolStatus().then(function() {
renderToolsSection();
if (window.lucide) lucide.createIcons();
});
}, 1000);
} else {
statusText.textContent = 'Error: ' + result.error;
progressBar.classList.add('bg-destructive');
installBtn.disabled = false;
installBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
} catch (err) {
clearInterval(progressInterval);
statusText.textContent = 'Error: ' + err.message;
progressBar.classList.add('bg-destructive');
installBtn.disabled = false;
installBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
}
function openCliUninstallWizard(toolName) {
var modal = document.createElement('div');
modal.id = 'cliUninstallModal';
modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50';
modal.innerHTML =
'<div class="bg-card rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden">' +
'<div class="p-6">' +
'<div class="flex items-center gap-3 mb-4">' +
'<div class="w-10 h-10 rounded-full bg-destructive/10 flex items-center justify-center">' +
'<i data-lucide="trash-2" class="w-5 h-5 text-destructive"></i>' +
'</div>' +
'<div>' +
'<h3 class="text-lg font-semibold">Uninstall ' + toolName.charAt(0).toUpperCase() + toolName.slice(1) + '</h3>' +
'<p class="text-sm text-muted-foreground">Remove CLI tool from system</p>' +
'</div>' +
'</div>' +
'<div class="space-y-4">' +
'<div class="bg-destructive/5 border border-destructive/20 rounded-lg p-4">' +
'<h4 class="font-medium text-destructive mb-2">What will be removed:</h4>' +
'<ul class="text-sm space-y-2 text-muted-foreground">' +
'<li class="flex items-start gap-2">' +
'<i data-lucide="x" class="w-4 h-4 text-destructive mt-0.5"></i>' +
'<span>Global NPM package</span>' +
'</li>' +
'<li class="flex items-start gap-2">' +
'<i data-lucide="x" class="w-4 h-4 text-destructive mt-0.5"></i>' +
'<span>CLI commands and executables</span>' +
'</li>' +
'<li class="flex items-start gap-2">' +
'<i data-lucide="x" class="w-4 h-4 text-destructive mt-0.5"></i>' +
'<span>Tool configuration (if any)</span>' +
'</li>' +
'</ul>' +
'</div>' +
'<div class="bg-warning/10 border border-warning/20 rounded-lg p-3">' +
'<div class="flex items-start gap-2">' +
'<i data-lucide="alert-triangle" class="w-4 h-4 text-warning mt-0.5"></i>' +
'<div class="text-sm">' +
'<p class="font-medium text-warning">Note</p>' +
'<p class="text-muted-foreground">You can reinstall this tool anytime from the CLI Manager.</p>' +
'</div>' +
'</div>' +
'</div>' +
'<div id="cliUninstallProgress" class="hidden">' +
'<div class="flex items-center gap-3">' +
'<div class="animate-spin w-5 h-5 border-2 border-destructive border-t-transparent rounded-full"></div>' +
'<span class="text-sm" id="cliUninstallStatus">Removing package...</span>' +
'</div>' +
'<div class="mt-2 h-2 bg-muted rounded-full overflow-hidden">' +
'<div id="cliUninstallProgressBar" class="h-full bg-destructive transition-all duration-300" style="width: 0%"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="border-t border-border p-4 flex justify-end gap-3 bg-muted/30">' +
'<button class="btn-outline px-4 py-2" onclick="closeCliUninstallWizard()">Cancel</button>' +
'<button id="cliUninstallBtn" class="btn-destructive px-4 py-2" onclick="startCliUninstall(\'' + toolName + '\')">' +
'<i data-lucide="trash-2" class="w-4 h-4 mr-2"></i>' +
'Uninstall' +
'</button>' +
'</div>' +
'</div>';
document.body.appendChild(modal);
if (window.lucide) {
lucide.createIcons();
}
}
function closeCliUninstallWizard() {
var modal = document.getElementById('cliUninstallModal');
if (modal) {
modal.remove();
}
}
async function startCliUninstall(toolName) {
var progressDiv = document.getElementById('cliUninstallProgress');
var uninstallBtn = document.getElementById('cliUninstallBtn');
var statusText = document.getElementById('cliUninstallStatus');
var progressBar = document.getElementById('cliUninstallProgressBar');
progressDiv.classList.remove('hidden');
uninstallBtn.disabled = true;
uninstallBtn.innerHTML = '<span class="animate-pulse">Uninstalling...</span>';
var stages = [
{ progress: 33, text: 'Removing package files...' },
{ progress: 66, text: 'Cleaning up dependencies...' },
{ progress: 90, text: 'Finalizing removal...' }
];
var currentStage = 0;
var progressInterval = setInterval(function() {
if (currentStage < stages.length) {
statusText.textContent = stages[currentStage].text;
progressBar.style.width = stages[currentStage].progress + '%';
currentStage++;
}
}, 500);
try {
var response = await fetch('/api/cli/uninstall', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tool: toolName })
});
clearInterval(progressInterval);
var result = await response.json();
if (result.success) {
progressBar.style.width = '100%';
statusText.textContent = 'Uninstallation complete!';
setTimeout(function() {
closeCliUninstallWizard();
showRefreshToast(toolName + ' uninstalled successfully!', 'success');
loadCliToolStatus().then(function() {
renderToolsSection();
if (window.lucide) lucide.createIcons();
});
}, 1000);
} else {
statusText.textContent = 'Error: ' + result.error;
progressBar.classList.remove('bg-destructive');
progressBar.classList.add('bg-destructive');
uninstallBtn.disabled = false;
uninstallBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
} catch (err) {
clearInterval(progressInterval);
statusText.textContent = 'Error: ' + err.message;
progressBar.classList.remove('bg-destructive');
progressBar.classList.add('bg-destructive');
uninstallBtn.disabled = false;
uninstallBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> Retry';
if (window.lucide) lucide.createIcons();
}
}
// ========== CodexLens Configuration Modal ==========
async function showCodexLensConfigModal() {
var loadingContent = '<div class="text-center py-8">' +
'<div class="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full mx-auto mb-4"></div>' +
'<p class="text-muted-foreground">' + t('codexlens.loadingConfig') + '</p>' +
'</div>';
showModal(t('codexlens.config'), loadingContent, { size: 'md' });
try {
// Fetch current configuration
var response = await fetch('/api/codexlens/config');
var config = await response.json();
var content = buildCodexLensConfigContent(config);
showModal('CodexLens Configuration', content, { size: 'md' });
setTimeout(function() {
initCodexLensConfigEvents(config);
if (window.lucide) lucide.createIcons();
}, 100);
} catch (err) {
var errorContent = '<div class="bg-destructive/10 border border-destructive/20 rounded-lg p-4">' +
'<div class="flex items-start gap-2">' +
'<i data-lucide="alert-circle" class="w-5 h-5 text-destructive mt-0.5"></i>' +
'<div>' +
'<p class="font-medium text-destructive">Failed to load configuration</p>' +
'<p class="text-sm text-muted-foreground mt-1">' + err.message + '</p>' +
'</div>' +
'</div>' +
'</div>';
showModal('CodexLens Configuration', errorContent, { size: 'md' });
}
}
function buildCodexLensConfigContent(config) {
var status = codexLensStatus || {};
var isInstalled = status.ready;
var indexDir = config.index_dir || '~/.codexlens/indexes';
var currentWorkspace = config.current_workspace || 'None';
var indexCount = config.index_count || 0;
return '<div class="tool-config-modal">' +
// Status Section
'<div class="tool-config-section">' +
'<h4>' + t('codexlens.status') + '</h4>' +
'<div class="tool-config-badges">' +
'<span class="badge ' + (isInstalled ? 'badge-success' : 'badge-muted') + '">' +
'<i data-lucide="' + (isInstalled ? 'check-circle' : 'circle-dashed') + '" class="w-3 h-3"></i> ' +
(isInstalled ? t('codexlens.installed') : t('codexlens.notInstalled')) +
'</span>' +
'<span class="badge badge-primary">' +
'<i data-lucide="database" class="w-3 h-3"></i> ' + indexCount + ' ' + t('codexlens.indexes') +
'</span>' +
'</div>' +
(currentWorkspace !== 'None'
? '<div class="mt-3 p-3 bg-muted/30 rounded-lg">' +
'<p class="text-sm text-muted-foreground mb-1">' + t('codexlens.currentWorkspace') + ':</p>' +
'<p class="text-sm font-mono break-all">' + escapeHtml(currentWorkspace) + '</p>' +
'</div>'
: '') +
'</div>' +
// Index Storage Path Section
'<div class="tool-config-section">' +
'<h4>' + t('codexlens.indexStoragePath') + ' <span class="text-muted">(' + t('codexlens.whereIndexesStored') + ')</span></h4>' +
'<div class="space-y-3">' +
'<div class="bg-muted/30 rounded-lg p-3">' +
'<p class="text-sm text-muted-foreground mb-2">' + t('codexlens.currentPath') + ':</p>' +
'<p class="text-sm font-mono break-all bg-background px-2 py-1 rounded border border-border">' +
escapeHtml(indexDir) +
'</p>' +
'</div>' +
'<div>' +
'<label class="text-sm font-medium mb-2 block">' + t('codexlens.newStoragePath') + ':</label>' +
'<input type="text" id="indexDirInput" class="tool-config-input w-full" ' +
'placeholder="' + t('codexlens.pathPlaceholder') + '" ' +
'value="' + escapeHtml(indexDir) + '" />' +
'<p class="text-xs text-muted-foreground mt-2">' +
'<i data-lucide="info" class="w-3 h-3 inline"></i> ' +
t('codexlens.pathInfo') +
'</p>' +
'</div>' +
'<div class="bg-warning/10 border border-warning/20 rounded-lg p-3">' +
'<div class="flex items-start gap-2">' +
'<i data-lucide="alert-triangle" class="w-4 h-4 text-warning mt-0.5"></i>' +
'<div class="text-sm">' +
'<p class="font-medium text-warning">' + t('codexlens.migrationRequired') + '</p>' +
'<p class="text-muted-foreground mt-1">' + t('codexlens.migrationWarning') + '</p>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
// Actions Section
'<div class="tool-config-section">' +
'<h4>' + t('codexlens.actions') + '</h4>' +
'<div class="tool-config-actions">' +
(isInstalled
? '<button class="btn-sm btn-outline" onclick="event.stopPropagation(); initCodexLensIndex()">' +
'<i data-lucide="database" class="w-3 h-3"></i> ' + t('codexlens.initializeIndex') +
'</button>' +
'<button class="btn-sm btn-outline" onclick="event.stopPropagation(); cleanCodexLensIndexes()">' +
'<i data-lucide="trash" class="w-3 h-3"></i> ' + t('codexlens.cleanAllIndexes') +
'</button>' +
'<button class="btn-sm btn-outline btn-danger" onclick="event.stopPropagation(); uninstallCodexLens()">' +
'<i data-lucide="trash-2" class="w-3 h-3"></i> ' + t('cli.uninstall') +
'</button>'
: '<button class="btn-sm btn-primary" onclick="event.stopPropagation(); installCodexLens()">' +
'<i data-lucide="download" class="w-3 h-3"></i> ' + t('codexlens.installCodexLens') +
'</button>') +
'</div>' +
'</div>' +
// Test Search Section
(isInstalled
? '<div class="tool-config-section">' +
'<h4>' + t('codexlens.testSearch') + ' <span class="text-muted">(' + t('codexlens.testFunctionality') + ')</span></h4>' +
'<div class="space-y-3">' +
'<div class="flex gap-2">' +
'<select id="searchTypeSelect" class="tool-config-select flex-1">' +
'<option value="search">' + t('codexlens.textSearch') + '</option>' +
'<option value="search_files">' + t('codexlens.fileSearch') + '</option>' +
'<option value="symbol">' + t('codexlens.symbolSearch') + '</option>' +
'</select>' +
'</div>' +
'<div>' +
'<input type="text" id="searchQueryInput" class="tool-config-input w-full" ' +
'placeholder="' + t('codexlens.searchPlaceholder') + '" />' +
'</div>' +
'<div>' +
'<button class="btn-sm btn-primary w-full" id="runSearchBtn">' +
'<i data-lucide="search" class="w-3 h-3"></i> ' + t('codexlens.runSearch') +
'</button>' +
'</div>' +
'<div id="searchResults" class="hidden">' +
'<div class="bg-muted/30 rounded-lg p-3 max-h-64 overflow-y-auto">' +
'<div class="flex items-center justify-between mb-2">' +
'<p class="text-sm font-medium">' + t('codexlens.results') + ':</p>' +
'<span id="searchResultCount" class="text-xs text-muted-foreground"></span>' +
'</div>' +
'<pre id="searchResultContent" class="text-xs font-mono whitespace-pre-wrap break-all"></pre>' +
'</div>' +
'</div>' +
'</div>' +
'</div>'
: '') +
// Footer
'<div class="tool-config-footer">' +
'<button class="btn btn-outline" onclick="closeModal()">' + t('common.cancel') + '</button>' +
'<button class="btn btn-primary" id="saveCodexLensConfigBtn">' +
'<i data-lucide="save" class="w-3.5 h-3.5"></i> ' + t('codexlens.saveConfig') +
'</button>' +
'</div>' +
'</div>';
}
function initCodexLensConfigEvents(currentConfig) {
var saveBtn = document.getElementById('saveCodexLensConfigBtn');
if (saveBtn) {
saveBtn.onclick = async function() {
var indexDirInput = document.getElementById('indexDirInput');
var newIndexDir = indexDirInput ? indexDirInput.value.trim() : '';
if (!newIndexDir) {
showRefreshToast(t('codexlens.pathEmpty'), 'error');
return;
}
if (newIndexDir === currentConfig.index_dir) {
closeModal();
return;
}
saveBtn.disabled = true;
saveBtn.innerHTML = '<span class="animate-pulse">' + t('common.saving') + '</span>';
try {
var response = await fetch('/api/codexlens/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ index_dir: newIndexDir })
});
var result = await response.json();
if (result.success) {
showRefreshToast(t('codexlens.configSaved'), 'success');
closeModal();
// Refresh CodexLens status
if (typeof loadCodexLensStatus === 'function') {
await loadCodexLensStatus();
renderToolsSection();
if (window.lucide) lucide.createIcons();
}
} else {
showRefreshToast(t('common.saveFailed') + ': ' + result.error, 'error');
saveBtn.disabled = false;
saveBtn.innerHTML = '<i data-lucide="save" class="w-3.5 h-3.5"></i> ' + t('codexlens.saveConfig');
if (window.lucide) lucide.createIcons();
}
} catch (err) {
showRefreshToast(t('common.error') + ': ' + err.message, 'error');
saveBtn.disabled = false;
saveBtn.innerHTML = '<i data-lucide="save" class="w-3.5 h-3.5"></i> ' + t('codexlens.saveConfig');
if (window.lucide) lucide.createIcons();
}
};
}
// Test Search Button
var runSearchBtn = document.getElementById('runSearchBtn');
if (runSearchBtn) {
runSearchBtn.onclick = async function() {
var searchType = document.getElementById('searchTypeSelect').value;
var query = document.getElementById('searchQueryInput').value.trim();
var resultsDiv = document.getElementById('searchResults');
var resultCount = document.getElementById('searchResultCount');
var resultContent = document.getElementById('searchResultContent');
if (!query) {
showRefreshToast(t('codexlens.enterQuery'), 'warning');
return;
}
runSearchBtn.disabled = true;
runSearchBtn.innerHTML = '<span class="animate-pulse">' + t('codexlens.searching') + '</span>';
resultsDiv.classList.add('hidden');
try {
var endpoint = '/api/codexlens/' + searchType;
var params = new URLSearchParams({ query: query, limit: '20' });
var response = await fetch(endpoint + '?' + params.toString());
var result = await response.json();
console.log('[CodexLens Test] Search result:', result);
if (result.success) {
var results = result.results || result.files || [];
resultCount.textContent = results.length + ' ' + t('codexlens.resultsCount');
resultContent.textContent = JSON.stringify(results, null, 2);
resultsDiv.classList.remove('hidden');
showRefreshToast(t('codexlens.searchCompleted') + ': ' + results.length + ' ' + t('codexlens.resultsCount'), 'success');
} else {
resultContent.textContent = t('common.error') + ': ' + (result.error || t('common.unknownError'));
resultsDiv.classList.remove('hidden');
showRefreshToast(t('codexlens.searchFailed') + ': ' + result.error, 'error');
}
runSearchBtn.disabled = false;
runSearchBtn.innerHTML = '<i data-lucide="search" class="w-3 h-3"></i> ' + t('codexlens.runSearch');
if (window.lucide) lucide.createIcons();
} catch (err) {
console.error('[CodexLens Test] Error:', err);
resultContent.textContent = t('common.exception') + ': ' + err.message;
resultsDiv.classList.remove('hidden');
showRefreshToast(t('common.error') + ': ' + err.message, 'error');
runSearchBtn.disabled = false;
runSearchBtn.innerHTML = '<i data-lucide="search" class="w-3 h-3"></i> ' + t('codexlens.runSearch');
if (window.lucide) lucide.createIcons();
}
};
}
}
async function cleanCodexLensIndexes() {
if (!confirm(t('codexlens.cleanConfirm'))) {
return;
}
try {
showRefreshToast(t('codexlens.cleaning'), 'info');
var response = await fetch('/api/codexlens/clean', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ all: true })
});
var result = await response.json();
if (result.success) {
showRefreshToast(t('codexlens.cleanSuccess'), 'success');
// Refresh status
if (typeof loadCodexLensStatus === 'function') {
await loadCodexLensStatus();
renderToolsSection();
if (window.lucide) lucide.createIcons();
}
} else {
showRefreshToast(t('codexlens.cleanFailed') + ': ' + result.error, 'error');
}
} catch (err) {
showRefreshToast(t('common.error') + ': ' + err.message, 'error');
}
}

View File

@@ -47,18 +47,71 @@ async function renderMcpManager() {
const projectData = mcpAllProjects[currentPath] || {};
const projectServers = projectData.mcpServers || {};
const disabledServers = projectData.disabledMcpServers || [];
const hasMcpJson = projectData.hasMcpJson || false;
const mcpJsonPath = projectData.mcpJsonPath || null;
// Get all available servers from all projects
const allAvailableServers = getAllAvailableMcpServers();
// Separate current project servers and available servers
const currentProjectServerNames = Object.keys(projectServers);
// Separate servers by category:
// 1. Project Available = Global + Project-specific (servers available to current project)
// 2. Global Management = Global servers that can be managed
// 3. Other Projects = Servers from other projects (can install to project or global)
// Separate enterprise, user, and other project servers
const enterpriseServerEntries = Object.entries(mcpEnterpriseServers || {})
.filter(([name]) => !currentProjectServerNames.includes(name));
const userServerEntries = Object.entries(mcpUserServers || {})
.filter(([name]) => !currentProjectServerNames.includes(name) && !(mcpEnterpriseServers || {})[name]);
const currentProjectServerNames = Object.keys(projectServers);
const globalServerNames = Object.keys(mcpUserServers || {});
const enterpriseServerNames = Object.keys(mcpEnterpriseServers || {});
// Project Available MCP: servers available to current project
// This includes: Enterprise (highest priority) + Global + Project-specific
const projectAvailableEntries = [];
// Add enterprise servers first (highest priority)
for (const [name, config] of Object.entries(mcpEnterpriseServers || {})) {
projectAvailableEntries.push({
name,
config,
source: 'enterprise',
canRemove: false,
canToggle: false
});
}
// Add global servers
for (const [name, config] of Object.entries(mcpUserServers || {})) {
if (!enterpriseServerNames.includes(name)) {
projectAvailableEntries.push({
name,
config,
source: 'global',
canRemove: false, // Can't remove from project view, must go to global management
canToggle: true,
isEnabled: !disabledServers.includes(name)
});
}
}
// Add project-specific servers
for (const [name, config] of Object.entries(projectServers)) {
if (!enterpriseServerNames.includes(name) && !globalServerNames.includes(name)) {
projectAvailableEntries.push({
name,
config,
source: 'project',
canRemove: true,
canToggle: true,
isEnabled: !disabledServers.includes(name)
});
}
}
// Global Management: user global servers (for management)
const globalManagementEntries = Object.entries(mcpUserServers || {});
// Enterprise servers (for display only, read-only)
const enterpriseServerEntries = Object.entries(mcpEnterpriseServers || {});
// Other Projects: servers from other projects (not in current project, not global)
const otherProjectServers = Object.entries(allAvailableServers)
.filter(([name, info]) => !currentProjectServerNames.includes(name) && !info.isGlobal);
// Check if CCW Tools is already installed
@@ -126,20 +179,31 @@ async function renderMcpManager() {
</div>
</div>
<!-- Current Project MCP Servers -->
<!-- Project Available MCP Servers -->
<div class="mcp-section mb-6">
<div class="flex items-center justify-between mb-4">
<div class="flex items-center gap-3">
<h3 class="text-lg font-semibold text-foreground">${t('mcp.currentProject')}</h3>
<h3 class="text-lg font-semibold text-foreground">${t('mcp.projectAvailable')}</h3>
<button class="px-3 py-1.5 text-sm bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity flex items-center gap-1"
onclick="openMcpCreateModal()">
<span>+</span> ${t('mcp.newServer')}
onclick="openMcpCreateModal('project')">
<span>+</span> ${t('mcp.newProjectServer')}
</button>
${hasMcpJson ? `
<span class="inline-flex items-center gap-1.5 px-2 py-1 text-xs bg-success/10 text-success rounded-md border border-success/20">
<i data-lucide="file-check" class="w-3.5 h-3.5"></i>
.mcp.json
</span>
` : `
<span class="inline-flex items-center gap-1.5 px-2 py-1 text-xs bg-muted text-muted-foreground rounded-md border border-border" title="New servers will create .mcp.json">
<i data-lucide="file-plus" class="w-3.5 h-3.5"></i>
Will use .mcp.json
</span>
`}
</div>
<span class="text-sm text-muted-foreground">${currentProjectServerNames.length} ${t('mcp.serversConfigured')}</span>
<span class="text-sm text-muted-foreground">${projectAvailableEntries.length} ${t('mcp.serversAvailable')}</span>
</div>
${currentProjectServerNames.length === 0 ? `
${projectAvailableEntries.length === 0 ? `
<div class="mcp-empty-state bg-card border border-border rounded-lg p-6 text-center">
<div class="text-muted-foreground mb-3"><i data-lucide="plug" class="w-10 h-10 mx-auto"></i></div>
<p class="text-muted-foreground">${t('empty.noMcpServers')}</p>
@@ -147,53 +211,43 @@ async function renderMcpManager() {
</div>
` : `
<div class="mcp-server-grid grid gap-3">
${currentProjectServerNames.map(serverName => {
const serverConfig = projectServers[serverName];
const isEnabled = !disabledServers.includes(serverName);
return renderMcpServerCard(serverName, serverConfig, isEnabled, true);
${projectAvailableEntries.map(entry => {
return renderProjectAvailableServerCard(entry);
}).join('')}
</div>
`}
</div>
<!-- Enterprise MCP Servers (Managed) -->
${enterpriseServerEntries.length > 0 ? `
<div class="mcp-section mb-6">
<div class="flex items-center justify-between mb-4">
<!-- Global Available MCP Servers -->
<div class="mcp-section mb-6">
<div class="flex items-center justify-between mb-4">
<div class="flex items-center gap-3">
<div class="flex items-center gap-2">
<i data-lucide="building-2" class="w-5 h-5"></i>
<h3 class="text-lg font-semibold text-foreground">Enterprise MCP Servers</h3>
<span class="text-xs px-2 py-0.5 bg-warning/20 text-warning rounded-full">Managed</span>
<i data-lucide="globe" class="w-5 h-5 text-success"></i>
<h3 class="text-lg font-semibold text-foreground">${t('mcp.globalAvailable')}</h3>
</div>
<span class="text-sm text-muted-foreground">${enterpriseServerEntries.length} servers (read-only)</span>
<button class="px-3 py-1.5 text-sm bg-success text-success-foreground rounded-lg hover:opacity-90 transition-opacity flex items-center gap-1"
onclick="openMcpCreateModal('global')">
<span>+</span> ${t('mcp.newGlobalServer')}
</button>
</div>
<span class="text-sm text-muted-foreground">${globalManagementEntries.length} ${t('mcp.globalServersFrom')}</span>
</div>
${globalManagementEntries.length === 0 ? `
<div class="mcp-empty-state bg-card border border-border rounded-lg p-6 text-center">
<div class="text-muted-foreground mb-3"><i data-lucide="globe" class="w-10 h-10 mx-auto"></i></div>
<p class="text-muted-foreground">${t('empty.noGlobalMcpServers')}</p>
<p class="text-sm text-muted-foreground mt-1">${t('empty.globalServersHint')}</p>
</div>
` : `
<div class="mcp-server-grid grid gap-3">
${enterpriseServerEntries.map(([serverName, serverConfig]) => {
return renderEnterpriseServerCard(serverName, serverConfig);
${globalManagementEntries.map(([serverName, serverConfig]) => {
return renderGlobalManagementCard(serverName, serverConfig);
}).join('')}
</div>
</div>
` : ''}
<!-- User MCP Servers -->
${userServerEntries.length > 0 ? `
<div class="mcp-section mb-6">
<div class="flex items-center justify-between mb-4">
<div class="flex items-center gap-2">
<i data-lucide="user" class="w-5 h-5"></i>
<h3 class="text-lg font-semibold text-foreground">User MCP Servers</h3>
</div>
<span class="text-sm text-muted-foreground">${userServerEntries.length} servers from ~/.claude.json</span>
</div>
<div class="mcp-server-grid grid gap-3">
${userServerEntries.map(([serverName, serverConfig]) => {
return renderGlobalServerCard(serverName, serverConfig, 'user');
}).join('')}
</div>
</div>
` : ''}
`}
</div>
<!-- Available MCP Servers from Other Projects -->
<div class="mcp-section">
@@ -238,6 +292,7 @@ async function renderMcpManager() {
const serverNames = Object.keys(servers);
const isCurrentProject = path === currentPath;
const enabledCount = serverNames.filter(s => !projectDisabled.includes(s)).length;
const projectHasMcpJson = config.hasMcpJson || false;
return `
<tr class="border-b border-border last:border-b-0 ${isCurrentProject ? 'bg-primary/5' : 'hover:bg-hover/50'}">
@@ -245,9 +300,10 @@ async function renderMcpManager() {
<div class="flex items-center gap-2 min-w-0">
<span class="shrink-0">${isCurrentProject ? '<i data-lucide="map-pin" class="w-4 h-4 text-primary"></i>' : '<i data-lucide="folder" class="w-4 h-4"></i>'}</span>
<div class="min-w-0">
<div class="font-medium text-foreground truncate text-sm" title="${escapeHtml(path)}">
${escapeHtml(path.split('\\').pop() || path)}
${isCurrentProject ? `<span class="ml-2 text-xs text-primary font-medium">${t('mcp.current')}</span>` : ''}
<div class="font-medium text-foreground truncate text-sm flex items-center gap-2" title="${escapeHtml(path)}">
<span class="truncate">${escapeHtml(path.split('\\').pop() || path)}</span>
${isCurrentProject ? `<span class="text-xs text-primary font-medium shrink-0">${t('mcp.current')}</span>` : ''}
${projectHasMcpJson ? `<span class="shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 text-xs bg-success/10 text-success rounded" title=".mcp.json detected"><i data-lucide="file-check" class="w-3 h-3"></i></span>` : ''}
</div>
<div class="text-xs text-muted-foreground truncate">${escapeHtml(path)}</div>
</div>
@@ -291,25 +347,40 @@ async function renderMcpManager() {
if (typeof lucide !== 'undefined') lucide.createIcons();
}
function renderMcpServerCard(serverName, serverConfig, isEnabled, isInCurrentProject) {
const command = serverConfig.command || 'N/A';
const args = serverConfig.args || [];
const hasEnv = serverConfig.env && Object.keys(serverConfig.env).length > 0;
// Render card for Project Available MCP (current project can use)
function renderProjectAvailableServerCard(entry) {
const { name, config, source, canRemove, canToggle, isEnabled } = entry;
const command = config.command || 'N/A';
const args = config.args || [];
const hasEnv = config.env && Object.keys(config.env).length > 0;
// Source badge
let sourceBadge = '';
if (source === 'enterprise') {
sourceBadge = '<span class="text-xs px-2 py-0.5 bg-warning/20 text-warning rounded-full">Enterprise</span>';
} else if (source === 'global') {
sourceBadge = '<span class="text-xs px-2 py-0.5 bg-success/10 text-success rounded-full">Global</span>';
} else if (source === 'project') {
sourceBadge = '<span class="text-xs px-2 py-0.5 bg-primary/10 text-primary rounded-full">Project</span>';
}
return `
<div class="mcp-server-card bg-card border border-border rounded-lg p-4 hover:shadow-md transition-all ${isEnabled ? '' : 'opacity-60'}">
<div class="mcp-server-card bg-card border border-border rounded-lg p-4 hover:shadow-md transition-all ${canToggle && !isEnabled ? 'opacity-60' : ''}">
<div class="flex items-start justify-between mb-3">
<div class="flex items-center gap-2">
<span>${isEnabled ? '<i data-lucide="check-circle" class="w-5 h-5 text-success"></i>' : '<i data-lucide="x-circle" class="w-5 h-5 text-destructive"></i>'}</span>
<h4 class="font-semibold text-foreground">${escapeHtml(serverName)}</h4>
<span>${canToggle && isEnabled ? '<i data-lucide="check-circle" class="w-5 h-5 text-success"></i>' : '<i data-lucide="circle" class="w-5 h-5 text-muted-foreground"></i>'}</span>
<h4 class="font-semibold text-foreground">${escapeHtml(name)}</h4>
${sourceBadge}
</div>
<label class="mcp-toggle relative inline-flex items-center cursor-pointer">
<input type="checkbox" class="sr-only peer"
${isEnabled ? 'checked' : ''}
data-server-name="${escapeHtml(serverName)}"
data-action="toggle">
<div class="w-9 h-5 bg-hover peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-success"></div>
</label>
${canToggle ? `
<label class="mcp-toggle relative inline-flex items-center cursor-pointer">
<input type="checkbox" class="sr-only peer"
${isEnabled ? 'checked' : ''}
data-server-name="${escapeHtml(name)}"
data-action="toggle">
<div class="w-9 h-5 bg-hover peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-success"></div>
</label>
` : ''}
</div>
<div class="mcp-server-details text-sm space-y-1">
@@ -326,20 +397,85 @@ function renderMcpServerCard(serverName, serverConfig, isEnabled, isInCurrentPro
${hasEnv ? `
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">env</span>
<span class="text-xs">${Object.keys(serverConfig.env).length} variables</span>
<span class="text-xs">${Object.keys(config.env).length} variables</span>
</div>
` : ''}
</div>
${isInCurrentProject ? `
<div class="mt-3 pt-3 border-t border-border">
<div class="mt-3 pt-3 border-t border-border flex items-center justify-between">
<button class="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1"
data-server-name="${escapeHtml(name)}"
data-server-config="${escapeHtml(JSON.stringify(config))}"
data-scope="${source === 'global' ? 'global' : 'project'}"
data-action="copy-install-cmd">
<i data-lucide="copy" class="w-3 h-3"></i>
${t('mcp.copyInstallCmd')}
</button>
${canRemove ? `
<button class="text-xs text-destructive hover:text-destructive/80 transition-colors"
data-server-name="${escapeHtml(serverName)}"
data-server-name="${escapeHtml(name)}"
data-action="remove">
${t('mcp.removeFromProject')}
</button>
` : ''}
</div>
</div>
`;
}
// Render card for Global Management (manage global servers)
function renderGlobalManagementCard(serverName, serverConfig) {
const command = serverConfig.command || serverConfig.url || 'N/A';
const args = serverConfig.args || [];
const hasEnv = serverConfig.env && Object.keys(serverConfig.env).length > 0;
const serverType = serverConfig.type || 'stdio';
return `
<div class="mcp-server-card mcp-server-global bg-card border border-success/30 rounded-lg p-4 hover:shadow-md transition-all">
<div class="flex items-start justify-between mb-3">
<div class="flex items-center gap-2">
<i data-lucide="globe" class="w-5 h-5 text-success"></i>
<h4 class="font-semibold text-foreground">${escapeHtml(serverName)}</h4>
</div>
` : ''}
</div>
<div class="mcp-server-details text-sm space-y-1">
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">${serverType === 'stdio' ? 'cmd' : 'url'}</span>
<span class="truncate" title="${escapeHtml(command)}">${escapeHtml(command)}</span>
</div>
${args.length > 0 ? `
<div class="flex items-start gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded shrink-0">args</span>
<span class="text-xs font-mono truncate" title="${escapeHtml(args.join(' '))}">${escapeHtml(args.slice(0, 3).join(' '))}${args.length > 3 ? '...' : ''}</span>
</div>
` : ''}
${hasEnv ? `
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">env</span>
<span class="text-xs">${Object.keys(serverConfig.env).length} variables</span>
</div>
` : ''}
<div class="flex items-center gap-2 text-muted-foreground mt-1">
<span class="text-xs italic">${t('mcp.availableToAll')}</span>
</div>
</div>
<div class="mt-3 pt-3 border-t border-border flex items-center justify-between">
<button class="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1"
data-server-name="${escapeHtml(serverName)}"
data-server-config="${escapeHtml(JSON.stringify(serverConfig))}"
data-scope="global"
data-action="copy-install-cmd">
<i data-lucide="copy" class="w-3 h-3"></i>
${t('mcp.copyInstallCmd')}
</button>
<button class="text-xs text-destructive hover:text-destructive/80 transition-colors"
data-server-name="${escapeHtml(serverName)}"
data-action="remove-global">
${t('mcp.removeGlobal')}
</button>
</div>
</div>
`;
}
@@ -373,13 +509,26 @@ function renderAvailableServerCard(serverName, serverInfo) {
</span>
` : ''}
</div>
<button class="px-3 py-1 text-xs bg-primary text-primary-foreground rounded hover:opacity-90 transition-opacity"
data-server-name="${escapeHtml(originalName)}"
data-server-key="${escapeHtml(serverName)}"
data-server-config='${JSON.stringify(serverConfig).replace(/'/g, "&#39;")}'
data-action="add">
${t('mcp.add')}
</button>
<div class="flex gap-2">
<button class="px-3 py-1 text-xs bg-primary text-primary-foreground rounded hover:opacity-90 transition-opacity"
data-server-name="${escapeHtml(originalName)}"
data-server-key="${escapeHtml(serverName)}"
data-server-config='${JSON.stringify(serverConfig).replace(/'/g, "&#39;")}'
data-scope="project"
data-action="add-from-other"
title="${t('mcp.installToProject')}">
<i data-lucide="folder-plus" class="w-3.5 h-3.5 inline"></i>
</button>
<button class="px-3 py-1 text-xs bg-success text-success-foreground rounded hover:opacity-90 transition-opacity"
data-server-name="${escapeHtml(originalName)}"
data-server-key="${escapeHtml(serverName)}"
data-server-config='${JSON.stringify(serverConfig).replace(/'/g, "&#39;")}'
data-scope="global"
data-action="add-from-other"
title="${t('mcp.installToGlobal')}">
<i data-lucide="globe" class="w-3.5 h-3.5 inline"></i>
</button>
</div>
</div>
<div class="mcp-server-details text-sm space-y-1">
@@ -398,101 +547,21 @@ function renderAvailableServerCard(serverName, serverInfo) {
${sourceProjectName ? `<span class="text-xs text-muted-foreground/70">• from ${escapeHtml(sourceProjectName)}</span>` : ''}
</div>
</div>
</div>
`;
}
function renderGlobalServerCard(serverName, serverConfig, source = 'user') {
const command = serverConfig.command || serverConfig.url || 'N/A';
const args = serverConfig.args || [];
const hasEnv = serverConfig.env && Object.keys(serverConfig.env).length > 0;
const serverType = serverConfig.type || 'stdio';
return `
<div class="mcp-server-card mcp-server-global bg-card border border-primary/30 rounded-lg p-4 hover:shadow-md transition-all">
<div class="flex items-start justify-between mb-3">
<div class="flex items-center gap-2">
<i data-lucide="user" class="w-5 h-5"></i>
<h4 class="font-semibold text-foreground">${escapeHtml(serverName)}</h4>
<span class="text-xs px-2 py-0.5 bg-primary/10 text-primary rounded-full">User</span>
</div>
<button class="px-3 py-1 text-xs bg-primary text-primary-foreground rounded hover:opacity-90 transition-opacity"
data-server-name="${escapeHtml(serverName)}"
data-server-config='${JSON.stringify(serverConfig).replace(/'/g, "&#39;")}'
data-action="add">
${t('mcp.addToProject')}
<div class="mt-3 pt-3 border-t border-border">
<button class="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1"
data-server-name="${escapeHtml(originalName)}"
data-server-config="${escapeHtml(JSON.stringify(serverConfig))}"
data-scope="project"
data-action="copy-install-cmd">
<i data-lucide="copy" class="w-3 h-3"></i>
${t('mcp.copyInstallCmd')}
</button>
</div>
<div class="mcp-server-details text-sm space-y-1">
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">${serverType === 'stdio' ? 'cmd' : 'url'}</span>
<span class="truncate" title="${escapeHtml(command)}">${escapeHtml(command)}</span>
</div>
${args.length > 0 ? `
<div class="flex items-start gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded shrink-0">args</span>
<span class="text-xs font-mono truncate" title="${escapeHtml(args.join(' '))}">${escapeHtml(args.slice(0, 3).join(' '))}${args.length > 3 ? '...' : ''}</span>
</div>
` : ''}
${hasEnv ? `
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">env</span>
<span class="text-xs">${Object.keys(serverConfig.env).length} variables</span>
</div>
` : ''}
<div class="flex items-center gap-2 text-muted-foreground mt-1">
<span class="text-xs italic">Available to all projects from ~/.claude.json</span>
</div>
</div>
</div>
`;
}
function renderEnterpriseServerCard(serverName, serverConfig) {
const command = serverConfig.command || serverConfig.url || 'N/A';
const args = serverConfig.args || [];
const hasEnv = serverConfig.env && Object.keys(serverConfig.env).length > 0;
const serverType = serverConfig.type || 'stdio';
return `
<div class="mcp-server-card mcp-server-enterprise bg-card border border-warning/30 rounded-lg p-4 hover:shadow-md transition-all">
<div class="flex items-start justify-between mb-3">
<div class="flex items-center gap-2">
<i data-lucide="building-2" class="w-5 h-5"></i>
<h4 class="font-semibold text-foreground">${escapeHtml(serverName)}</h4>
<span class="text-xs px-2 py-0.5 bg-warning/20 text-warning rounded-full">Enterprise</span>
<i data-lucide="lock" class="w-3 h-3 text-muted-foreground"></i>
</div>
<span class="px-3 py-1 text-xs bg-muted text-muted-foreground rounded cursor-not-allowed">
Read-only
</span>
</div>
<div class="mcp-server-details text-sm space-y-1">
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">${serverType === 'stdio' ? 'cmd' : 'url'}</span>
<span class="truncate" title="${escapeHtml(command)}">${escapeHtml(command)}</span>
</div>
${args.length > 0 ? `
<div class="flex items-start gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded shrink-0">args</span>
<span class="text-xs font-mono truncate" title="${escapeHtml(args.join(' '))}">${escapeHtml(args.slice(0, 3).join(' '))}${args.length > 3 ? '...' : ''}</span>
</div>
` : ''}
${hasEnv ? `
<div class="flex items-center gap-2 text-muted-foreground">
<span class="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">env</span>
<span class="text-xs">${Object.keys(serverConfig.env).length} variables</span>
</div>
` : ''}
<div class="flex items-center gap-2 text-muted-foreground mt-1">
<span class="text-xs italic">Managed by organization (highest priority)</span>
</div>
</div>
</div>
`;
}
function attachMcpEventListeners() {
// Toggle switches
@@ -504,16 +573,22 @@ function attachMcpEventListeners() {
});
});
// Add buttons - use btn.dataset instead of e.target.dataset for event bubbling safety
document.querySelectorAll('.mcp-server-card button[data-action="add"]').forEach(btn => {
// Add from other projects (with scope selection)
document.querySelectorAll('.mcp-server-card button[data-action="add-from-other"]').forEach(btn => {
btn.addEventListener('click', async (e) => {
const serverName = btn.dataset.serverName;
const serverConfig = JSON.parse(btn.dataset.serverConfig);
await copyMcpServerToProject(serverName, serverConfig);
const scope = btn.dataset.scope; // 'project' or 'global'
if (scope === 'global') {
await addGlobalMcpServer(serverName, serverConfig);
} else {
await copyMcpServerToProject(serverName, serverConfig);
}
});
});
// Remove buttons - use btn.dataset instead of e.target.dataset for event bubbling safety
// Remove buttons (project-level)
document.querySelectorAll('.mcp-server-card button[data-action="remove"]').forEach(btn => {
btn.addEventListener('click', async (e) => {
const serverName = btn.dataset.serverName;
@@ -522,4 +597,24 @@ function attachMcpEventListeners() {
}
});
});
// Remove buttons (global-level)
document.querySelectorAll('.mcp-server-card button[data-action="remove-global"]').forEach(btn => {
btn.addEventListener('click', async (e) => {
const serverName = btn.dataset.serverName;
if (confirm(t('mcp.removeGlobalConfirm', { name: serverName }))) {
await removeGlobalMcpServer(serverName);
}
});
});
// Copy install command buttons
document.querySelectorAll('.mcp-server-card button[data-action="copy-install-cmd"]').forEach(btn => {
btn.addEventListener('click', async (e) => {
const serverName = btn.dataset.serverName;
const serverConfig = JSON.parse(btn.dataset.serverConfig);
const scope = btn.dataset.scope || 'project';
await copyMcpInstallCommand(serverName, serverConfig, scope);
});
});
}

View File

@@ -335,9 +335,482 @@ function editRule(ruleName, location) {
}
}
// ========== Create Rule Modal ==========
var ruleCreateState = {
location: 'project',
fileName: '',
subdirectory: '',
isConditional: false,
paths: [''],
content: '',
mode: 'input',
generationType: 'description',
description: '',
extractScope: '',
extractFocus: ''
};
function openRuleCreateModal() {
// Open create modal (to be implemented with modal)
if (window.showToast) {
showToast(t('rules.createNotImplemented'), 'info');
// Reset state
ruleCreateState = {
location: 'project',
fileName: '',
subdirectory: '',
isConditional: false,
paths: [''],
content: '',
mode: 'input',
generationType: 'description',
description: '',
extractScope: '',
extractFocus: ''
};
// Create modal HTML
const modalHtml = `
<div class="modal-overlay fixed inset-0 bg-black/50 z-50 flex items-center justify-center" onclick="closeRuleCreateModal(event)">
<div class="modal-dialog bg-card rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] mx-4 flex flex-col" onclick="event.stopPropagation()">
<!-- Header -->
<div class="flex items-center justify-between px-6 py-4 border-b border-border">
<h3 class="text-lg font-semibold text-foreground">${t('rules.createRule')}</h3>
<button class="w-8 h-8 flex items-center justify-center text-xl text-muted-foreground hover:text-foreground hover:bg-hover rounded"
onclick="closeRuleCreateModal()">&times;</button>
</div>
<!-- Body -->
<div class="flex-1 overflow-y-auto p-6 space-y-5">
<!-- Location Selection -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.location')}</label>
<div class="grid grid-cols-2 gap-3">
<button class="location-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${ruleCreateState.location === 'project' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="selectRuleLocation('project')">
<div class="flex items-center gap-2">
<i data-lucide="folder" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('rules.projectRules')}</div>
<div class="text-xs text-muted-foreground">.claude/rules/</div>
</div>
</div>
</button>
<button class="location-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${ruleCreateState.location === 'user' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="selectRuleLocation('user')">
<div class="flex items-center gap-2">
<i data-lucide="user" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('rules.userRules')}</div>
<div class="text-xs text-muted-foreground">~/.claude/rules/</div>
</div>
</div>
</button>
</div>
</div>
<!-- Mode Selection -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.createMode')}</label>
<div class="grid grid-cols-2 gap-3">
<button class="mode-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${ruleCreateState.mode === 'input' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="switchRuleCreateMode('input')">
<div class="flex items-center gap-2">
<i data-lucide="edit" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('rules.manualInput')}</div>
<div class="text-xs text-muted-foreground">${t('rules.manualInputHint')}</div>
</div>
</div>
</button>
<button class="mode-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${ruleCreateState.mode === 'cli-generate' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="switchRuleCreateMode('cli-generate')">
<div class="flex items-center gap-2">
<i data-lucide="sparkles" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('rules.cliGenerate')}</div>
<div class="text-xs text-muted-foreground">${t('rules.cliGenerateHint')}</div>
</div>
</div>
</button>
</div>
</div>
<!-- File Name -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.fileName')}</label>
<input type="text" id="ruleFileName"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="my-rule.md"
value="${ruleCreateState.fileName}">
<p class="text-xs text-muted-foreground mt-1">${t('rules.fileNameHint')}</p>
</div>
<!-- Subdirectory -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.subdirectory')} <span class="text-muted-foreground">${t('common.optional')}</span></label>
<input type="text" id="ruleSubdirectory"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="category/subcategory"
value="${ruleCreateState.subdirectory}">
<p class="text-xs text-muted-foreground mt-1">${t('rules.subdirectoryHint')}</p>
</div>
<!-- CLI Generation Type (CLI mode only) -->
<div id="ruleGenerationTypeSection" style="display: ${ruleCreateState.mode === 'cli-generate' ? 'block' : 'none'}">
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.generationType')}</label>
<div class="flex gap-3">
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" name="ruleGenType" value="description"
class="w-4 h-4 text-primary bg-background border-border focus:ring-2 focus:ring-primary"
${ruleCreateState.generationType === 'description' ? 'checked' : ''}
onchange="switchRuleGenerationType('description')">
<span class="text-sm">${t('rules.fromDescription')}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" name="ruleGenType" value="extract"
class="w-4 h-4 text-primary bg-background border-border focus:ring-2 focus:ring-primary"
${ruleCreateState.generationType === 'extract' ? 'checked' : ''}
onchange="switchRuleGenerationType('extract')">
<span class="text-sm">${t('rules.fromCodeExtract')}</span>
</label>
</div>
</div>
<!-- Description Input (CLI mode, description type) -->
<div id="ruleDescriptionSection" style="display: ${ruleCreateState.mode === 'cli-generate' && ruleCreateState.generationType === 'description' ? 'block' : 'none'}">
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.description')}</label>
<textarea id="ruleDescription"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
rows="4"
placeholder="${t('rules.descriptionPlaceholder')}">${ruleCreateState.description}</textarea>
<p class="text-xs text-muted-foreground mt-1">${t('rules.descriptionHint')}</p>
</div>
<!-- Code Extract Options (CLI mode, extract type) -->
<div id="ruleExtractSection" style="display: ${ruleCreateState.mode === 'cli-generate' && ruleCreateState.generationType === 'extract' ? 'block' : 'none'}">
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.extractScope')}</label>
<input type="text" id="ruleExtractScope"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary font-mono"
placeholder="src/**/*.ts"
value="${ruleCreateState.extractScope}">
<p class="text-xs text-muted-foreground mt-1">${t('rules.extractScopeHint')}</p>
</div>
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.extractFocus')}</label>
<input type="text" id="ruleExtractFocus"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="naming, error-handling, state-management"
value="${ruleCreateState.extractFocus}">
<p class="text-xs text-muted-foreground mt-1">${t('rules.extractFocusHint')}</p>
</div>
</div>
</div>
<!-- Conditional Rule Toggle (Manual mode only) -->
<div id="ruleConditionalSection" style="display: ${ruleCreateState.mode === 'input' ? 'block' : 'none'}">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" id="ruleConditional"
class="w-4 h-4 text-primary bg-background border-border rounded focus:ring-2 focus:ring-primary"
${ruleCreateState.isConditional ? 'checked' : ''}
onchange="toggleRuleConditional()">
<span class="text-sm font-medium text-foreground">${t('rules.conditionalRule')}</span>
</label>
<p class="text-xs text-muted-foreground mt-1 ml-6">${t('rules.conditionalHint')}</p>
</div>
<!-- Path Conditions -->
<div id="rulePathsContainer" style="display: ${ruleCreateState.isConditional ? 'block' : 'none'}">
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.pathConditions')}</label>
<div id="rulePathsList" class="space-y-2">
${ruleCreateState.paths.map((path, index) => `
<div class="flex gap-2">
<input type="text" class="rule-path-input flex-1 px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="src/**/*.ts"
value="${path}"
data-index="${index}">
${index > 0 ? `
<button class="px-3 py-2 text-destructive hover:bg-destructive/10 rounded-lg transition-colors"
onclick="removeRulePath(${index})">
<i data-lucide="x" class="w-4 h-4"></i>
</button>
` : ''}
</div>
`).join('')}
</div>
<button class="mt-2 px-3 py-1.5 text-sm text-primary hover:bg-primary/10 rounded-lg transition-colors flex items-center gap-1"
onclick="addRulePath()">
<i data-lucide="plus" class="w-4 h-4"></i>
${t('rules.addPath')}
</button>
</div>
<!-- Content (Manual mode only) -->
<div id="ruleContentSection" style="display: ${ruleCreateState.mode === 'input' ? 'block' : 'none'}">
<label class="block text-sm font-medium text-foreground mb-2">${t('rules.content')}</label>
<textarea id="ruleContent"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary font-mono"
rows="10"
placeholder="${t('rules.contentPlaceholder')}">${ruleCreateState.content}</textarea>
<p class="text-xs text-muted-foreground mt-1">${t('rules.contentHint')}</p>
</div>
</div>
<!-- Footer -->
<div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
<button class="px-4 py-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
onclick="closeRuleCreateModal()">
${t('common.cancel')}
</button>
<button class="px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity"
onclick="createRule()">
${t('rules.create')}
</button>
</div>
</div>
</div>
`;
// Add to DOM
const modalContainer = document.createElement('div');
modalContainer.id = 'ruleCreateModal';
modalContainer.innerHTML = modalHtml;
document.body.appendChild(modalContainer);
// Initialize Lucide icons
if (typeof lucide !== 'undefined') lucide.createIcons();
}
function closeRuleCreateModal(event) {
if (event && event.target !== event.currentTarget) return;
const modal = document.getElementById('ruleCreateModal');
if (modal) modal.remove();
}
function selectRuleLocation(location) {
ruleCreateState.location = location;
// Re-render modal
closeRuleCreateModal();
openRuleCreateModal();
}
function toggleRuleConditional() {
ruleCreateState.isConditional = !ruleCreateState.isConditional;
const pathsContainer = document.getElementById('rulePathsContainer');
if (pathsContainer) {
pathsContainer.style.display = ruleCreateState.isConditional ? 'block' : 'none';
}
}
function addRulePath() {
ruleCreateState.paths.push('');
// Re-render paths list
const pathsList = document.getElementById('rulePathsList');
if (pathsList) {
const index = ruleCreateState.paths.length - 1;
const pathHtml = `
<div class="flex gap-2">
<input type="text" class="rule-path-input flex-1 px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="src/**/*.ts"
value=""
data-index="${index}">
<button class="px-3 py-2 text-destructive hover:bg-destructive/10 rounded-lg transition-colors"
onclick="removeRulePath(${index})">
<i data-lucide="x" class="w-4 h-4"></i>
</button>
</div>
`;
pathsList.insertAdjacentHTML('beforeend', pathHtml);
if (typeof lucide !== 'undefined') lucide.createIcons();
}
}
function removeRulePath(index) {
ruleCreateState.paths.splice(index, 1);
// Re-render paths list
closeRuleCreateModal();
openRuleCreateModal();
}
function switchRuleCreateMode(mode) {
ruleCreateState.mode = mode;
// Toggle visibility of sections
const generationTypeSection = document.getElementById('ruleGenerationTypeSection');
const descriptionSection = document.getElementById('ruleDescriptionSection');
const extractSection = document.getElementById('ruleExtractSection');
const conditionalSection = document.getElementById('ruleConditionalSection');
const contentSection = document.getElementById('ruleContentSection');
if (mode === 'cli-generate') {
if (generationTypeSection) generationTypeSection.style.display = 'block';
if (conditionalSection) conditionalSection.style.display = 'none';
if (contentSection) contentSection.style.display = 'none';
// Show appropriate generation section
if (ruleCreateState.generationType === 'description') {
if (descriptionSection) descriptionSection.style.display = 'block';
if (extractSection) extractSection.style.display = 'none';
} else {
if (descriptionSection) descriptionSection.style.display = 'none';
if (extractSection) extractSection.style.display = 'block';
}
} else {
if (generationTypeSection) generationTypeSection.style.display = 'none';
if (descriptionSection) descriptionSection.style.display = 'none';
if (extractSection) extractSection.style.display = 'none';
if (conditionalSection) conditionalSection.style.display = 'block';
if (contentSection) contentSection.style.display = 'block';
}
// Re-render modal to update button states
closeRuleCreateModal();
openRuleCreateModal();
}
function switchRuleGenerationType(type) {
ruleCreateState.generationType = type;
// Toggle visibility of generation sections
const descriptionSection = document.getElementById('ruleDescriptionSection');
const extractSection = document.getElementById('ruleExtractSection');
if (type === 'description') {
if (descriptionSection) descriptionSection.style.display = 'block';
if (extractSection) extractSection.style.display = 'none';
} else if (type === 'extract') {
if (descriptionSection) descriptionSection.style.display = 'none';
if (extractSection) extractSection.style.display = 'block';
}
}
async function createRule() {
const fileNameInput = document.getElementById('ruleFileName');
const subdirectoryInput = document.getElementById('ruleSubdirectory');
const contentInput = document.getElementById('ruleContent');
const pathInputs = document.querySelectorAll('.rule-path-input');
const descriptionInput = document.getElementById('ruleDescription');
const extractScopeInput = document.getElementById('ruleExtractScope');
const extractFocusInput = document.getElementById('ruleExtractFocus');
const fileName = fileNameInput ? fileNameInput.value.trim() : ruleCreateState.fileName;
const subdirectory = subdirectoryInput ? subdirectoryInput.value.trim() : ruleCreateState.subdirectory;
// Validate file name
if (!fileName) {
if (window.showToast) {
showToast(t('rules.fileNameRequired'), 'error');
}
return;
}
if (!fileName.endsWith('.md')) {
if (window.showToast) {
showToast(t('rules.fileNameMustEndMd'), 'error');
}
return;
}
// Prepare request based on mode
let requestBody;
if (ruleCreateState.mode === 'cli-generate') {
// CLI generation mode
const description = descriptionInput ? descriptionInput.value.trim() : ruleCreateState.description;
const extractScope = extractScopeInput ? extractScopeInput.value.trim() : ruleCreateState.extractScope;
const extractFocus = extractFocusInput ? extractFocusInput.value.trim() : ruleCreateState.extractFocus;
// Validate based on generation type
if (ruleCreateState.generationType === 'description' && !description) {
if (window.showToast) {
showToast(t('rules.descriptionRequired'), 'error');
}
return;
}
if (ruleCreateState.generationType === 'extract' && !extractScope) {
if (window.showToast) {
showToast(t('rules.extractScopeRequired'), 'error');
}
return;
}
requestBody = {
mode: 'cli-generate',
fileName,
location: ruleCreateState.location,
subdirectory: subdirectory || undefined,
projectPath,
generationType: ruleCreateState.generationType,
description: ruleCreateState.generationType === 'description' ? description : undefined,
extractScope: ruleCreateState.generationType === 'extract' ? extractScope : undefined,
extractFocus: ruleCreateState.generationType === 'extract' ? extractFocus : undefined
};
// Show progress message
if (window.showToast) {
showToast(t('rules.cliGenerating'), 'info');
}
} else {
// Manual input mode
const content = contentInput ? contentInput.value.trim() : ruleCreateState.content;
// Collect paths from inputs
const paths = [];
if (ruleCreateState.isConditional && pathInputs) {
pathInputs.forEach(input => {
const path = input.value.trim();
if (path) paths.push(path);
});
}
// Validate content
if (!content) {
if (window.showToast) {
showToast(t('rules.contentRequired'), 'error');
}
return;
}
requestBody = {
mode: 'input',
fileName,
content,
paths: paths.length > 0 ? paths : undefined,
location: ruleCreateState.location,
subdirectory: subdirectory || undefined,
projectPath
};
}
try {
const response = await fetch('/api/rules/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to create rule');
}
const result = await response.json();
// Close modal
closeRuleCreateModal();
// Reload rules data
await loadRulesData();
renderRulesView();
// Show success message
if (window.showToast) {
showToast(t('rules.created', { name: result.fileName }), 'success');
}
} catch (err) {
console.error('Failed to create rule:', err);
if (window.showToast) {
showToast(err.message || t('rules.createError'), 'error');
}
}
}

View File

@@ -337,9 +337,471 @@ function editSkill(skillName, location) {
}
}
// ========== Create Skill Modal ==========
var skillCreateState = {
mode: 'import', // 'import' or 'cli-generate'
location: 'project',
sourcePath: '',
customName: '',
validationResult: null,
// CLI Generate mode fields
generationType: 'description', // 'description' or 'template'
description: '',
skillName: ''
};
function openSkillCreateModal() {
// Open create modal (to be implemented with modal)
if (window.showToast) {
showToast(t('skills.createNotImplemented'), 'info');
// Reset state
skillCreateState = {
mode: 'import',
location: 'project',
sourcePath: '',
customName: '',
validationResult: null,
generationType: 'description',
description: '',
skillName: ''
};
// Create modal HTML
const modalHtml = `
<div class="modal-overlay fixed inset-0 bg-black/50 z-50 flex items-center justify-center" onclick="closeSkillCreateModal(event)">
<div class="modal-dialog bg-card rounded-lg shadow-lg w-full max-w-2xl mx-4" onclick="event.stopPropagation()">
<!-- Header -->
<div class="flex items-center justify-between px-6 py-4 border-b border-border">
<h3 class="text-lg font-semibold text-foreground">${t('skills.createSkill')}</h3>
<button class="w-8 h-8 flex items-center justify-center text-xl text-muted-foreground hover:text-foreground hover:bg-hover rounded"
onclick="closeSkillCreateModal()">&times;</button>
</div>
<!-- Body -->
<div class="p-6 space-y-5">
<!-- Location Selection -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.location')}</label>
<div class="grid grid-cols-2 gap-3">
<button class="location-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${skillCreateState.location === 'project' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="selectSkillLocation('project')">
<div class="flex items-center gap-2">
<i data-lucide="folder" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('skills.projectSkills')}</div>
<div class="text-xs text-muted-foreground">.claude/skills/</div>
</div>
</div>
</button>
<button class="location-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${skillCreateState.location === 'user' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="selectSkillLocation('user')">
<div class="flex items-center gap-2">
<i data-lucide="user" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('skills.userSkills')}</div>
<div class="text-xs text-muted-foreground">~/.claude/skills/</div>
</div>
</div>
</button>
</div>
</div>
<!-- Mode Selection -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.createMode')}</label>
<div class="grid grid-cols-2 gap-3">
<button class="mode-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${skillCreateState.mode === 'import' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="switchSkillCreateMode('import')">
<div class="flex items-center gap-2">
<i data-lucide="folder-input" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('skills.importFolder')}</div>
<div class="text-xs text-muted-foreground">${t('skills.importFolderHint')}</div>
</div>
</div>
</button>
<button class="mode-btn px-4 py-3 text-left border-2 rounded-lg transition-all ${skillCreateState.mode === 'cli-generate' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="switchSkillCreateMode('cli-generate')">
<div class="flex items-center gap-2">
<i data-lucide="sparkles" class="w-5 h-5"></i>
<div>
<div class="font-medium">${t('skills.cliGenerate')}</div>
<div class="text-xs text-muted-foreground">${t('skills.cliGenerateHint')}</div>
</div>
</div>
</button>
</div>
</div>
<!-- Import Mode Content -->
<div id="skillImportMode" style="display: ${skillCreateState.mode === 'import' ? 'block' : 'none'}">
<!-- Source Folder Path -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.sourceFolder')}</label>
<div class="flex gap-2">
<input type="text" id="skillSourcePath"
class="flex-1 px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="${t('skills.sourceFolderPlaceholder')}"
value="${skillCreateState.sourcePath}">
<button class="px-4 py-2 bg-primary/10 text-primary rounded-lg hover:bg-primary/20 transition-colors text-sm"
onclick="browseSkillFolder()">
<i data-lucide="folder-open" class="w-4 h-4"></i>
</button>
</div>
<p class="text-xs text-muted-foreground mt-1">${t('skills.sourceFolderHint')}</p>
</div>
<!-- Custom Name -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.customName')} <span class="text-muted-foreground">${t('common.optional')}</span></label>
<input type="text" id="skillCustomName"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="${t('skills.customNamePlaceholder')}"
value="${skillCreateState.customName}">
<p class="text-xs text-muted-foreground mt-1">${t('skills.customNameHint')}</p>
</div>
<!-- Validation Result -->
<div id="skillValidationResult"></div>
</div>
<!-- CLI Generate Mode Content -->
<div id="skillCliGenerateMode" style="display: ${skillCreateState.mode === 'cli-generate' ? 'block' : 'none'}">
<!-- Skill Name (Required for CLI Generate) -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.skillName')} <span class="text-destructive">*</span></label>
<input type="text" id="skillGenerateName"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="${t('skills.skillNamePlaceholder')}"
value="${skillCreateState.skillName}">
<p class="text-xs text-muted-foreground mt-1">${t('skills.skillNameHint')}</p>
</div>
<!-- Generation Type Selection -->
<div>
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.generationType')}</label>
<div class="flex gap-3">
<button class="flex-1 px-4 py-3 text-left border-2 rounded-lg transition-all ${skillCreateState.generationType === 'description' ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}"
onclick="switchSkillGenerationType('description')">
<div class="flex items-center gap-2">
<i data-lucide="file-text" class="w-5 h-5"></i>
<div>
<div class="font-medium text-sm">${t('skills.fromDescription')}</div>
<div class="text-xs text-muted-foreground">${t('skills.fromDescriptionHint')}</div>
</div>
</div>
</button>
<button class="flex-1 px-4 py-3 text-left border-2 rounded-lg transition-all opacity-50 cursor-not-allowed"
disabled>
<div class="flex items-center gap-2">
<i data-lucide="layout-template" class="w-5 h-5"></i>
<div>
<div class="font-medium text-sm">${t('skills.fromTemplate')}</div>
<div class="text-xs text-muted-foreground">${t('skills.comingSoon')}</div>
</div>
</div>
</button>
</div>
</div>
<!-- Description Text Area (for 'description' type) -->
<div id="skillDescriptionArea" style="display: ${skillCreateState.generationType === 'description' ? 'block' : 'none'}">
<label class="block text-sm font-medium text-foreground mb-2">${t('skills.descriptionLabel')} <span class="text-destructive">*</span></label>
<textarea id="skillDescription"
class="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="${t('skills.descriptionPlaceholder')}"
rows="6">${skillCreateState.description}</textarea>
<p class="text-xs text-muted-foreground mt-1">${t('skills.descriptionGenerateHint')}</p>
</div>
<!-- CLI Generate Info -->
<div class="p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg">
<div class="flex items-start gap-2">
<i data-lucide="info" class="w-4 h-4 text-blue-600 mt-0.5"></i>
<div class="text-sm text-blue-600">
<p class="font-medium">${t('skills.cliGenerateInfo')}</p>
<p class="text-xs mt-1">${t('skills.cliGenerateTimeHint')}</p>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
<button class="px-4 py-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
onclick="closeSkillCreateModal()">
${t('common.cancel')}
</button>
${skillCreateState.mode === 'import' ? `
<button class="px-4 py-2 text-sm bg-primary/10 text-primary rounded-lg hover:bg-primary/20 transition-colors"
onclick="validateSkillImport()">
${t('skills.validate')}
</button>
<button class="px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity"
onclick="createSkill()">
${t('skills.import')}
</button>
` : `
<button class="px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity flex items-center gap-2"
onclick="createSkill()">
<i data-lucide="sparkles" class="w-4 h-4"></i>
${t('skills.generate')}
</button>
`}
</div>
</div>
</div>
`;
// Add to DOM
const modalContainer = document.createElement('div');
modalContainer.id = 'skillCreateModal';
modalContainer.innerHTML = modalHtml;
document.body.appendChild(modalContainer);
// Initialize Lucide icons
if (typeof lucide !== 'undefined') lucide.createIcons();
}
function closeSkillCreateModal(event) {
if (event && event.target !== event.currentTarget) return;
const modal = document.getElementById('skillCreateModal');
if (modal) modal.remove();
}
function selectSkillLocation(location) {
skillCreateState.location = location;
// Re-render modal
closeSkillCreateModal();
openSkillCreateModal();
}
function switchSkillCreateMode(mode) {
skillCreateState.mode = mode;
// Re-render modal
closeSkillCreateModal();
openSkillCreateModal();
}
function switchSkillGenerationType(type) {
skillCreateState.generationType = type;
// Re-render modal
closeSkillCreateModal();
openSkillCreateModal();
}
function browseSkillFolder() {
// Use browser prompt for now (Phase 3 will implement file browser)
const path = prompt(t('skills.enterFolderPath'), skillCreateState.sourcePath);
if (path !== null) {
skillCreateState.sourcePath = path;
document.getElementById('skillSourcePath').value = path;
}
}
async function validateSkillImport() {
const sourcePathInput = document.getElementById('skillSourcePath');
const sourcePath = sourcePathInput ? sourcePathInput.value.trim() : skillCreateState.sourcePath;
if (!sourcePath) {
showValidationResult({ valid: false, errors: [t('skills.sourceFolderRequired')], skillInfo: null });
return;
}
skillCreateState.sourcePath = sourcePath;
// Show loading state
showValidationResult({ loading: true });
try {
const response = await fetch('/api/skills/validate-import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sourcePath })
});
if (!response.ok) throw new Error('Validation request failed');
const result = await response.json();
skillCreateState.validationResult = result;
showValidationResult(result);
} catch (err) {
console.error('Failed to validate skill:', err);
showValidationResult({ valid: false, errors: [t('skills.validationError')], skillInfo: null });
}
}
function showValidationResult(result) {
const container = document.getElementById('skillValidationResult');
if (!container) return;
if (result.loading) {
container.innerHTML = `
<div class="flex items-center gap-2 p-3 bg-muted/50 rounded-lg">
<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>
<span class="text-sm text-muted-foreground">${t('skills.validating')}</span>
</div>
`;
if (typeof lucide !== 'undefined') lucide.createIcons();
return;
}
if (result.valid) {
container.innerHTML = `
<div class="p-4 bg-green-500/10 border border-green-500/20 rounded-lg">
<div class="flex items-center gap-2 text-green-600 mb-2">
<i data-lucide="check-circle" class="w-5 h-5"></i>
<span class="font-medium">${t('skills.validSkill')}</span>
</div>
<div class="space-y-1 text-sm">
<div><span class="text-muted-foreground">${t('skills.name')}:</span> <span class="font-medium">${escapeHtml(result.skillInfo.name)}</span></div>
<div><span class="text-muted-foreground">${t('skills.description')}:</span> <span>${escapeHtml(result.skillInfo.description)}</span></div>
${result.skillInfo.version ? `<div><span class="text-muted-foreground">${t('skills.version')}:</span> <span>${escapeHtml(result.skillInfo.version)}</span></div>` : ''}
${result.skillInfo.supportingFiles && result.skillInfo.supportingFiles.length > 0 ? `<div><span class="text-muted-foreground">${t('skills.supportingFiles')}:</span> <span>${result.skillInfo.supportingFiles.length} ${t('skills.files')}</span></div>` : ''}
</div>
</div>
`;
} else {
container.innerHTML = `
<div class="p-4 bg-destructive/10 border border-destructive/20 rounded-lg">
<div class="flex items-center gap-2 text-destructive mb-2">
<i data-lucide="x-circle" class="w-5 h-5"></i>
<span class="font-medium">${t('skills.invalidSkill')}</span>
</div>
<ul class="space-y-1 text-sm">
${result.errors.map(error => `<li class="text-destructive">• ${escapeHtml(error)}</li>`).join('')}
</ul>
</div>
`;
}
if (typeof lucide !== 'undefined') lucide.createIcons();
}
async function createSkill() {
if (skillCreateState.mode === 'import') {
// Import Mode Logic
const sourcePathInput = document.getElementById('skillSourcePath');
const customNameInput = document.getElementById('skillCustomName');
const sourcePath = sourcePathInput ? sourcePathInput.value.trim() : skillCreateState.sourcePath;
const customName = customNameInput ? customNameInput.value.trim() : skillCreateState.customName;
if (!sourcePath) {
if (window.showToast) {
showToast(t('skills.sourceFolderRequired'), 'error');
}
return;
}
// Validate first if not already validated
if (!skillCreateState.validationResult || !skillCreateState.validationResult.valid) {
if (window.showToast) {
showToast(t('skills.validateFirst'), 'error');
}
return;
}
try {
const response = await fetch('/api/skills/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
mode: 'import',
location: skillCreateState.location,
sourcePath,
skillName: customName || undefined,
projectPath
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to create skill');
}
const result = await response.json();
// Close modal
closeSkillCreateModal();
// Reload skills data
await loadSkillsData();
renderSkillsView();
// Show success message
if (window.showToast) {
showToast(t('skills.created', { name: result.skillName }), 'success');
}
} catch (err) {
console.error('Failed to create skill:', err);
if (window.showToast) {
showToast(err.message || t('skills.createError'), 'error');
}
}
} else if (skillCreateState.mode === 'cli-generate') {
// CLI Generate Mode Logic
const skillNameInput = document.getElementById('skillGenerateName');
const descriptionInput = document.getElementById('skillDescription');
const skillName = skillNameInput ? skillNameInput.value.trim() : skillCreateState.skillName;
const description = descriptionInput ? descriptionInput.value.trim() : skillCreateState.description;
// Validation
if (!skillName) {
if (window.showToast) {
showToast(t('skills.skillNameRequired'), 'error');
}
return;
}
if (skillCreateState.generationType === 'description' && !description) {
if (window.showToast) {
showToast(t('skills.descriptionRequired'), 'error');
}
return;
}
try {
// Show generating progress toast
if (window.showToast) {
showToast(t('skills.generating'), 'info');
}
const response = await fetch('/api/skills/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
mode: 'cli-generate',
location: skillCreateState.location,
generationType: skillCreateState.generationType,
skillName,
description: skillCreateState.generationType === 'description' ? description : undefined,
projectPath
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to generate skill');
}
const result = await response.json();
// Close modal
closeSkillCreateModal();
// Reload skills data
await loadSkillsData();
renderSkillsView();
// Show success message
if (window.showToast) {
showToast(t('skills.generated', { name: result.skillName }), 'success');
}
} catch (err) {
console.error('Failed to generate skill:', err);
if (window.showToast) {
showToast(err.message || t('skills.generateError'), 'error');
}
}
}
}

View File

@@ -434,6 +434,11 @@
<span class="nav-text flex-1" data-i18n="nav.rules">Rules</span>
<span class="badge px-2 py-0.5 text-xs font-semibold rounded-full bg-hover text-muted-foreground" id="badgeRules">0</span>
</li>
<li class="nav-item flex items-center gap-2 mx-2 px-3 py-2.5 text-sm text-muted-foreground hover:bg-hover hover:text-foreground rounded cursor-pointer transition-colors" data-view="claude-manager" data-tooltip="CLAUDE.md Manager">
<i data-lucide="file-code" class="nav-icon"></i>
<span class="nav-text flex-1" data-i18n="nav.claudeManager">CLAUDE.md</span>
<span class="badge px-2 py-0.5 text-xs font-semibold rounded-full bg-hover text-muted-foreground" id="badgeClaude">0</span>
</li>
</ul>
</div>
@@ -592,6 +597,14 @@
<input type="text" id="mcpServerName" data-i18n-placeholder="mcp.serverNamePlaceholder" placeholder="e.g., my-mcp-server"
class="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20">
</div>
<div class="form-group">
<label class="block text-sm font-medium text-foreground mb-1"><span data-i18n="mcp.scope">Scope</span> <span class="text-destructive">*</span></label>
<select id="mcpServerScope" class="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20">
<option value="project" data-i18n="mcp.scopeProject">Project - Only this project</option>
<option value="global" data-i18n="mcp.scopeGlobal">Global - All projects (~/. claude.json)</option>
</select>
<p class="text-xs text-muted-foreground mt-1">Choose where to save this MCP server configuration</p>
</div>
<div class="form-group">
<label class="block text-sm font-medium text-foreground mb-1"><span data-i18n="mcp.command">Command</span> <span class="text-destructive">*</span></label>
<input type="text" id="mcpServerCommand" data-i18n-placeholder="mcp.commandPlaceholder" placeholder="e.g., npx, uvx, node, python"