feat: OpenCode-style session management implementation
This commit is contained in:
@@ -346,126 +346,390 @@ function refreshSessions() {
|
||||
|
||||
// Sessions
|
||||
async function loadSessions() {
|
||||
const sessionsListEl = document.getElementById('sessions-list');
|
||||
|
||||
try {
|
||||
const res = await fetch('/claude/api/claude/sessions');
|
||||
// Get current project from URL
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const projectPath = urlParams.get('project');
|
||||
|
||||
// Build API URL with project filter
|
||||
let apiUrl = '/claude/api/claude/sessions';
|
||||
if (projectPath) {
|
||||
apiUrl += `?project=${encodeURIComponent(projectPath)}`;
|
||||
console.log('[Sessions] Loading sessions for project:', projectPath);
|
||||
}
|
||||
|
||||
// Show loading state
|
||||
sessionsListEl.innerHTML = '<div class="loading">Loading sessions...</div>';
|
||||
|
||||
const res = await fetch(apiUrl);
|
||||
|
||||
// Handle HTTP errors
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
sessionsListEl.innerHTML = `
|
||||
<div class="error-state">
|
||||
<p>⚠️ Session expired</p>
|
||||
<button class="btn-primary" onclick="location.reload()">Login Again</button>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
const sessionsListEl = document.getElementById('sessions-list');
|
||||
// Handle API errors
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
const allSessions = [
|
||||
...(data.active || []),
|
||||
...(data.historical || [])
|
||||
...(data.active || []).map(s => ({...s, type: 'active'})),
|
||||
...(data.historical || []).map(s => ({...s, type: 'historical'}))
|
||||
];
|
||||
|
||||
if (allSessions.length > 0) {
|
||||
sessionsListEl.innerHTML = allSessions.map(session => `
|
||||
<div class="session-item" onclick="viewSession('${session.id}')">
|
||||
// Sort by last activity (newest first)
|
||||
allSessions.sort((a, b) => {
|
||||
const dateA = new Date(a.lastActivity || a.createdAt || a.created_at);
|
||||
const dateB = new Date(b.lastActivity || b.createdAt || b.created_at);
|
||||
return dateB - dateA;
|
||||
});
|
||||
|
||||
// Empty state
|
||||
if (allSessions.length === 0) {
|
||||
const projectName = projectPath ? projectPath.split('/').pop() : 'this project';
|
||||
sessionsListEl.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">📂</div>
|
||||
<p>No sessions found for <strong>${escapeHtml(projectName)}</strong></p>
|
||||
<button class="btn-primary" onclick="startNewChat()">Create New Session</button>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Render session list
|
||||
sessionsListEl.innerHTML = allSessions.map(session => {
|
||||
const isRunning = session.status === 'running' && session.type === 'active';
|
||||
const relativeTime = getRelativeTime(session);
|
||||
const messageCount = session.messageCount || session.metadata?.messageCount || 0;
|
||||
|
||||
return `
|
||||
<div class="session-item ${session.type}" onclick="viewSessionDetails('${session.id}')">
|
||||
<div class="session-header">
|
||||
<span class="session-id">${session.id.substring(0, 20)}...</span>
|
||||
<span class="session-status ${session.status}">${session.status}</span>
|
||||
<div class="session-info">
|
||||
<span class="session-id">${session.id.substring(0, 12)}...</span>
|
||||
<span class="session-status ${isRunning ? 'running' : 'stopped'}">
|
||||
${isRunning ? '🟢 Running' : '⏸️ ' + (session.type === 'historical' ? 'Historical' : 'Stopped')}
|
||||
</span>
|
||||
</div>
|
||||
<div class="session-time">${relativeTime}</div>
|
||||
</div>
|
||||
<div class="session-meta">
|
||||
${session.workingDir}<br>
|
||||
${new Date(session.createdAt).toLocaleString()}
|
||||
<div class="session-path">📁 ${escapeHtml(session.workingDir)}</div>
|
||||
<div class="session-stats">
|
||||
<span>💬 ${messageCount} messages</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
} else {
|
||||
sessionsListEl.innerHTML = '<p class="placeholder">No sessions</p>';
|
||||
}
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading sessions:', error);
|
||||
console.error('[loadSessions] Error:', error);
|
||||
sessionsListEl.innerHTML = `
|
||||
<div class="error-state">
|
||||
<div class="error-icon">⚠️</div>
|
||||
<p>Failed to load sessions</p>
|
||||
<p class="error-message">${escapeHtml(error.message)}</p>
|
||||
<button class="btn-secondary" onclick="loadSessions()">Try Again</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
async function viewSession(sessionId) {
|
||||
function getRelativeTime(session) {
|
||||
const date = new Date(session.lastActivity || session.createdAt || session.created_at);
|
||||
const now = new Date();
|
||||
const diffMins = Math.floor((now - date) / 60000);
|
||||
|
||||
if (diffMins < 1) return 'Just now';
|
||||
if (diffMins < 60) return `${diffMins}m ago`;
|
||||
if (diffMins < 1440) return `${Math.floor(diffMins/60)}h ago`;
|
||||
return `${Math.floor(diffMins/1440)}d ago`;
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
async function viewSessionDetails(sessionId) {
|
||||
const detailEl = document.getElementById('session-detail');
|
||||
|
||||
try {
|
||||
// Show loading state
|
||||
detailEl.innerHTML = '<div class="loading">Loading session details...</div>';
|
||||
|
||||
const res = await fetch(`/claude/api/claude/sessions/${sessionId}`);
|
||||
|
||||
// Handle 404 - session not found
|
||||
if (res.status === 404) {
|
||||
detailEl.innerHTML = `
|
||||
<div class="error-state">
|
||||
<div class="error-icon">🔍</div>
|
||||
<h3>Session Not Found</h3>
|
||||
<p>The session <code>${escapeHtml(sessionId)}</code> could not be found.</p>
|
||||
<button class="btn-primary" onclick="loadSessions()">Back to Sessions</button>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
if (!data.session) {
|
||||
throw new Error('No session data in response');
|
||||
}
|
||||
|
||||
const session = data.session;
|
||||
const isRunning = session.status === 'running' && session.pid;
|
||||
const messageCount = session.outputBuffer?.length || 0;
|
||||
|
||||
// Render session detail card
|
||||
detailEl.innerHTML = `
|
||||
<div class="session-detail-card">
|
||||
<div class="session-detail-header">
|
||||
<div class="session-title">
|
||||
<h2>Session ${session.id.substring(0, 12)}...</h2>
|
||||
<span class="session-status-badge ${isRunning ? 'running' : 'stopped'}">
|
||||
${isRunning ? '🟢 Running' : '⏸️ Stopped'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="session-detail-actions">
|
||||
<button class="btn-primary" onclick="continueSessionInChat('${session.id}')">
|
||||
💬 Continue in Chat
|
||||
</button>
|
||||
<button class="btn-secondary" onclick="duplicateSession('${session.id}')">
|
||||
📋 Duplicate
|
||||
</button>
|
||||
${isRunning ? `
|
||||
<button class="btn-danger" onclick="terminateSession('${session.id}')">
|
||||
⏹️ Terminate
|
||||
</button>
|
||||
` : ''}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="session-detail-meta">
|
||||
<div class="meta-row">
|
||||
<span class="meta-label">Working Directory:</span>
|
||||
<span class="meta-value">${escapeHtml(session.workingDir)}</span>
|
||||
</div>
|
||||
<div class="meta-row">
|
||||
<span class="meta-label">Created:</span>
|
||||
<span class="meta-value">${new Date(session.createdAt).toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="meta-row">
|
||||
<span class="meta-label">Last Activity:</span>
|
||||
<span class="meta-value">${new Date(session.lastActivity).toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="meta-row">
|
||||
<span class="meta-label">Messages:</span>
|
||||
<span class="meta-value">${messageCount}</span>
|
||||
</div>
|
||||
${session.pid ? `
|
||||
<div class="meta-row">
|
||||
<span class="meta-label">PID:</span>
|
||||
<span class="meta-value">${session.pid}</span>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
|
||||
<div class="session-context">
|
||||
<h3>Token Usage</h3>
|
||||
<div class="context-bar">
|
||||
<div class="context-fill" style="width: ${Math.min(100, (session.context?.totalTokens || 0) / (session.context?.maxTokens || 200000) * 100)}%"></div>
|
||||
</div>
|
||||
<div class="context-stats">
|
||||
<span>${(session.context?.totalTokens || 0).toLocaleString()} / ${(session.context?.maxTokens || 200000).toLocaleString()} tokens</span>
|
||||
<span>${Math.round((session.context?.totalTokens || 0) / (session.context?.maxTokens || 200000) * 100)}% used</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="session-output-preview">
|
||||
<h3>Session Output (${messageCount} entries)</h3>
|
||||
<div class="output-scroll-area">
|
||||
${session.outputBuffer?.slice(0, 50).map(entry => `
|
||||
<div class="output-entry ${entry.type}">
|
||||
<div class="output-header">
|
||||
<span class="output-type">${entry.type}</span>
|
||||
<span class="output-time">${new Date(entry.timestamp).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
<div class="output-content">${escapeHtml(entry.content.substring(0, 500))}${entry.content.length > 500 ? '...' : ''}</div>
|
||||
</div>
|
||||
`).join('') || '<p class="no-output">No output yet</p>'}
|
||||
${session.outputBuffer?.length > 50 ? `<p class="output-truncated">...and ${session.outputBuffer.length - 50} more entries</p>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
currentSession = session;
|
||||
|
||||
} catch (error) {
|
||||
console.error('[viewSessionDetails] Error:', error);
|
||||
detailEl.innerHTML = `
|
||||
<div class="error-state">
|
||||
<div class="error-icon">⚠️</div>
|
||||
<h3>Failed to Load Session</h3>
|
||||
<p class="error-message">${escapeHtml(error.message)}</p>
|
||||
<button class="btn-primary" onclick="loadSessions()">Back to Sessions</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
async function continueSessionInChat(sessionId) {
|
||||
console.log('[Sessions] Continuing session in Chat:', sessionId);
|
||||
|
||||
try {
|
||||
showLoadingOverlay('Loading session...');
|
||||
|
||||
const res = await fetch(`/claude/api/claude/sessions/${sessionId}`);
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (!data.session) {
|
||||
throw new Error('Session not found');
|
||||
}
|
||||
|
||||
const session = data.session;
|
||||
|
||||
// Check if session is runnable
|
||||
if (session.status === 'terminated' || session.status === 'stopped') {
|
||||
hideLoadingOverlay();
|
||||
|
||||
if (confirm('This session has ended. Do you want to create a new session with the same working directory?')) {
|
||||
await duplicateSession(sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Store pending session and switch views
|
||||
window.pendingSessionId = sessionId;
|
||||
window.pendingSessionData = session;
|
||||
|
||||
switchView('chat');
|
||||
|
||||
} catch (error) {
|
||||
console.error('[continueSessionInChat] Error:', error);
|
||||
hideLoadingOverlay();
|
||||
showToast('❌ Failed to load session: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function duplicateSession(sessionId) {
|
||||
try {
|
||||
const res = await fetch(`/claude/api/claude/sessions/${sessionId}`);
|
||||
const data = await res.json();
|
||||
|
||||
currentSession = data.session;
|
||||
if (!data.session) {
|
||||
throw new Error('Session not found');
|
||||
}
|
||||
|
||||
const detailEl = document.getElementById('session-detail');
|
||||
detailEl.innerHTML = `
|
||||
<div class="session-header-info">
|
||||
<h2>${data.session.id}</h2>
|
||||
<p>Status: <span class="session-status ${data.session.status}">${data.session.status}</span></p>
|
||||
<p>PID: ${data.session.pid || 'N/A'}</p>
|
||||
<p>Working Directory: ${data.session.workingDir}</p>
|
||||
<p>Created: ${new Date(data.session.createdAt).toLocaleString()}</p>
|
||||
</div>
|
||||
const workingDir = data.session.workingDir;
|
||||
const projectName = workingDir.split('/').pop();
|
||||
|
||||
<h3>Context Usage</h3>
|
||||
<div class="context-bar">
|
||||
<div class="context-fill" style="width: ${data.session.context.totalTokens / data.session.context.maxTokens * 100}%"></div>
|
||||
</div>
|
||||
<div class="context-stats">
|
||||
<span>${data.session.context.totalTokens.toLocaleString()} tokens</span>
|
||||
<span>${Math.round(data.session.context.totalTokens / data.session.context.maxTokens * 100)}% used</span>
|
||||
</div>
|
||||
showLoadingOverlay('Duplicating session...');
|
||||
|
||||
<h3>Session Output</h3>
|
||||
<div class="session-output" id="session-output">
|
||||
${data.session.outputBuffer.map(entry => `
|
||||
<div class="output-line ${entry.type}">${escapeHtml(entry.content)}</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
|
||||
${data.session.status === 'running' ? `
|
||||
<div class="command-input-container">
|
||||
<input type="text" id="command-input" class="command-input" placeholder="Enter command..." onkeypress="handleCommandKeypress(event)">
|
||||
<button class="btn-primary" onclick="sendCommand()">Send</button>
|
||||
</div>
|
||||
` : ''}
|
||||
`;
|
||||
|
||||
// Switch to sessions view
|
||||
switchView('sessions');
|
||||
} catch (error) {
|
||||
console.error('Error viewing session:', error);
|
||||
alert('Failed to load session');
|
||||
}
|
||||
}
|
||||
|
||||
function handleCommandKeypress(event) {
|
||||
if (event.key === 'Enter') {
|
||||
sendCommand();
|
||||
}
|
||||
}
|
||||
|
||||
async function sendCommand() {
|
||||
const input = document.getElementById('command-input');
|
||||
const command = input.value.trim();
|
||||
|
||||
if (!command || !currentSession) return;
|
||||
|
||||
try {
|
||||
await fetch(`/claude/api/claude/sessions/${currentSession.id}/command`, {
|
||||
const createRes = await fetch('/claude/api/claude/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ command })
|
||||
body: JSON.stringify({
|
||||
workingDir,
|
||||
metadata: {
|
||||
type: 'chat',
|
||||
source: 'web-ide',
|
||||
project: projectName,
|
||||
duplicatedFrom: sessionId
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
input.value = '';
|
||||
if (!createRes.ok) {
|
||||
throw new Error(`HTTP ${createRes.status}`);
|
||||
}
|
||||
|
||||
const createData = await createRes.json();
|
||||
|
||||
hideLoadingOverlay();
|
||||
showToast('✅ Session duplicated!', 'success');
|
||||
|
||||
loadSessions();
|
||||
|
||||
setTimeout(() => {
|
||||
if (confirm('Start chatting in the duplicated session?')) {
|
||||
continueSessionInChat(createData.session.id);
|
||||
}
|
||||
}, 500);
|
||||
|
||||
// Append command to output
|
||||
appendOutput({
|
||||
type: 'command',
|
||||
content: `$ ${command}\n`
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error sending command:', error);
|
||||
alert('Failed to send command');
|
||||
console.error('[duplicateSession] Error:', error);
|
||||
hideLoadingOverlay();
|
||||
showToast('Failed to duplicate session: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function appendOutput(data) {
|
||||
const outputEl = document.getElementById('session-output');
|
||||
if (outputEl) {
|
||||
const line = document.createElement('div');
|
||||
line.className = `output-line ${data.type}`;
|
||||
line.textContent = data.content;
|
||||
outputEl.appendChild(line);
|
||||
outputEl.scrollTop = outputEl.scrollHeight;
|
||||
async function terminateSession(sessionId) {
|
||||
if (!confirm('Are you sure you want to terminate this session?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
showLoadingOverlay('Terminating session...');
|
||||
|
||||
const res = await fetch(`/claude/api/claude/sessions/${sessionId}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
hideLoadingOverlay();
|
||||
showToast('✅ Session terminated', 'success');
|
||||
|
||||
loadSessions();
|
||||
|
||||
if (currentSession && currentSession.id === sessionId) {
|
||||
document.getElementById('session-detail').innerHTML = `
|
||||
<div class="placeholder">
|
||||
<h2>Session Terminated</h2>
|
||||
<p>Select another session from the sidebar</p>
|
||||
</div>
|
||||
`;
|
||||
currentSession = null;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('[terminateSession] Error:', error);
|
||||
hideLoadingOverlay();
|
||||
showToast('Failed to terminate session: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user