modified: CLAUDE.md
modified: templates/chat.html new file: test_code_execution.html
This commit is contained in:
parent
2811dad67b
commit
4f3dd882ba
3 changed files with 390 additions and 2 deletions
47
CLAUDE.md
47
CLAUDE.md
|
|
@ -28,3 +28,50 @@
|
|||
## Makefile Best Practices
|
||||
- Avoid variable substitutions - don't be afraid to be unDRY in the Makefile so engineers can copy and paste
|
||||
- Use tabs not spaces, and for fuck sake be happy about it
|
||||
|
||||
## Running OpenCompletion
|
||||
|
||||
### Environment Setup
|
||||
- Use `vars.sh` to set up environment variables
|
||||
- Required: MODEL_ENDPOINT_x and MODEL_API_KEY_x variables for AI models
|
||||
- Run with: `source vars.sh && python app.py`
|
||||
|
||||
### Makefile Commands
|
||||
- `make venv` - Create virtual environment and install dependencies
|
||||
- `make init-db` - Initialize database tables
|
||||
- `make test` - Run all tests
|
||||
- `make dev-setup` - Install development dependencies
|
||||
|
||||
## OpenCompletion Architecture
|
||||
|
||||
### Frontend Structure
|
||||
- Main chat interface is in `templates/chat.html`
|
||||
- Base template with CSS is in `templates/base.html`
|
||||
- JavaScript code is inline in chat.html for real-time chat functionality
|
||||
- Uses Socket.IO for WebSocket communication
|
||||
- Uses marked.js for Markdown rendering and DOMPurify for XSS protection
|
||||
- Code blocks are rendered with highlight.js for syntax highlighting
|
||||
|
||||
### Code Block Rendering
|
||||
- Code blocks are processed in messages after markdown conversion
|
||||
- Copy buttons are added via `addCopyButtonToCodeBlock()` function (line 1176 in chat.html)
|
||||
- Code blocks support:
|
||||
- Syntax highlighting via highlight.js
|
||||
- Line numbers via `addLineNumbers()` function
|
||||
- Truncation for long code blocks via `truncateCodeBlock()` function
|
||||
- Copy functionality that preserves full content even when truncated
|
||||
|
||||
### Message Processing Flow
|
||||
1. Messages received via Socket.IO events (chat_message, message_chunk for streaming)
|
||||
2. Markdown converted to HTML using marked.js
|
||||
3. HTML sanitized with DOMPurify
|
||||
4. Code blocks enhanced with copy buttons, syntax highlighting, and line numbers
|
||||
|
||||
### Code Execution Integration (New)
|
||||
- Integration with unfirecracker-code-executor service on cammy.foxhop.net
|
||||
- Service supports 38 working languages with auto-detection
|
||||
- Endpoints:
|
||||
- `/execute` - Execute code with specified language
|
||||
- `/run` - Auto-detect language and execute
|
||||
- Add play button next to copy button for code blocks
|
||||
- Display execution results inline below code blocks
|
||||
|
|
|
|||
|
|
@ -85,6 +85,7 @@
|
|||
// Constants
|
||||
const API_KEY = "dummy-api-key";
|
||||
const TTS_API_URL = "https://speech.ai.unturf.com/v1/audio/speech";
|
||||
const CODE_EXEC_URL = "https://cammy-black.foxhop.net"; // Code execution service URL (served via Caddy)
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
let username = urlParams.get("username") || "guest"; // Default to "guest" if no username in URL
|
||||
|
||||
|
|
@ -1177,6 +1178,13 @@ function addCopyButtonToCodeBlock(block) {
|
|||
// Check if the full content is stored in a data attribute, otherwise use textContent
|
||||
const contentToCopy = block.dataset.fullContent || block.textContent;
|
||||
|
||||
// Create a container for the buttons
|
||||
const buttonContainer = document.createElement('div');
|
||||
buttonContainer.classList.add('code-block-button-container');
|
||||
buttonContainer.style.display = 'flex';
|
||||
buttonContainer.style.gap = '8px';
|
||||
buttonContainer.style.marginBottom = '8px';
|
||||
|
||||
// Create a button to copy the code block's content
|
||||
const copyButton = document.createElement('button');
|
||||
copyButton.textContent = 'Copy';
|
||||
|
|
@ -1194,8 +1202,142 @@ function addCopyButtonToCodeBlock(block) {
|
|||
});
|
||||
};
|
||||
|
||||
// Insert the button before the code block
|
||||
block.parentNode.insertBefore(copyButton, block);
|
||||
// Create a button to execute the code block's content
|
||||
const playButton = document.createElement('button');
|
||||
playButton.textContent = '▶ Run';
|
||||
playButton.classList.add('play-button');
|
||||
playButton.onclick = function() {
|
||||
executeCodeBlock(contentToCopy, block, playButton);
|
||||
};
|
||||
|
||||
// Add buttons to container
|
||||
buttonContainer.appendChild(copyButton);
|
||||
buttonContainer.appendChild(playButton);
|
||||
|
||||
// Insert the button container before the code block
|
||||
block.parentNode.insertBefore(buttonContainer, block);
|
||||
}
|
||||
|
||||
// Function to execute code block content
|
||||
async function executeCodeBlock(code, blockElement, playButton) {
|
||||
// Update button state
|
||||
playButton.textContent = 'Running...';
|
||||
playButton.disabled = true;
|
||||
|
||||
// Check if we already have a results container
|
||||
let resultsContainer = blockElement.parentNode.querySelector('.code-execution-results');
|
||||
if (!resultsContainer) {
|
||||
// Create results container
|
||||
resultsContainer = document.createElement('div');
|
||||
resultsContainer.classList.add('code-execution-results');
|
||||
resultsContainer.style.marginTop = '10px';
|
||||
resultsContainer.style.padding = '10px';
|
||||
resultsContainer.style.backgroundColor = '#f0f0f0';
|
||||
resultsContainer.style.borderRadius = '5px';
|
||||
resultsContainer.style.fontFamily = 'monospace';
|
||||
resultsContainer.style.fontSize = '14px';
|
||||
resultsContainer.style.whiteSpace = 'pre-wrap';
|
||||
resultsContainer.style.wordWrap = 'break-word';
|
||||
|
||||
// Insert after the code block
|
||||
blockElement.parentNode.insertBefore(resultsContainer, blockElement.nextSibling);
|
||||
}
|
||||
|
||||
// Clear previous results
|
||||
resultsContainer.innerHTML = '<div style="color: #666;">Executing code...</div>';
|
||||
|
||||
try {
|
||||
// Try to detect language from the code block's class
|
||||
let language = null;
|
||||
const classes = blockElement.className.split(' ');
|
||||
for (const cls of classes) {
|
||||
if (cls.startsWith('language-')) {
|
||||
language = cls.replace('language-', '');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If no language specified (no class on code block), default to Python
|
||||
if (!language) {
|
||||
language = 'python';
|
||||
}
|
||||
|
||||
// Use /execute endpoint with specified or default language
|
||||
const response = await fetch(`${CODE_EXEC_URL}/execute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
language: language,
|
||||
code: code
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Format and display results
|
||||
let outputHtml = '';
|
||||
|
||||
// Handle nested response structure - check if stdout is an object with nested data
|
||||
let actualStdout = result.stdout;
|
||||
let actualStderr = result.stderr;
|
||||
|
||||
// If stdout is an object (nested response), extract the actual stdout/stderr
|
||||
if (typeof result.stdout === 'object' && result.stdout !== null) {
|
||||
actualStdout = result.stdout.stdout || '';
|
||||
actualStderr = result.stdout.stderr || '';
|
||||
}
|
||||
|
||||
// Show language
|
||||
if (result.language) {
|
||||
outputHtml += `<div style="color: #0066cc; margin-bottom: 8px;">Language: ${result.language}</div>`;
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
// Show stdout
|
||||
if (actualStdout) {
|
||||
outputHtml += '<div style="color: #008800; font-weight: bold;">Output:</div>';
|
||||
outputHtml += `<div style="color: #333; margin-left: 10px;">${escapeHtml(actualStdout)}</div>`;
|
||||
}
|
||||
|
||||
// Show stderr if present
|
||||
if (actualStderr) {
|
||||
outputHtml += '<div style="color: #cc0000; font-weight: bold; margin-top: 8px;">Errors/Warnings:</div>';
|
||||
outputHtml += `<div style="color: #cc0000; margin-left: 10px;">${escapeHtml(actualStderr)}</div>`;
|
||||
}
|
||||
|
||||
// If no output at all
|
||||
if (!actualStdout && !actualStderr) {
|
||||
outputHtml += '<div style="color: #666;">(No output produced)</div>';
|
||||
}
|
||||
} else {
|
||||
// Execution failed
|
||||
outputHtml += '<div style="color: #cc0000; font-weight: bold;">Execution Failed:</div>';
|
||||
outputHtml += `<div style="color: #cc0000; margin-left: 10px;">${escapeHtml(result.error || result.stderr || 'Unknown error')}</div>`;
|
||||
}
|
||||
|
||||
resultsContainer.innerHTML = outputHtml;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error executing code:', error);
|
||||
resultsContainer.innerHTML = `<div style="color: #cc0000;">Error: ${escapeHtml(error.message)}</div>`;
|
||||
} finally {
|
||||
// Reset button state
|
||||
playButton.textContent = '▶ Run';
|
||||
playButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to escape HTML
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function addLineNumbers(block) {
|
||||
|
|
|
|||
199
test_code_execution.html
Normal file
199
test_code_execution.html
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Code Execution Test</title>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/default.min.css">
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
.test-container {
|
||||
margin: 20px 0;
|
||||
padding: 20px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
pre {
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
button {
|
||||
margin: 5px;
|
||||
padding: 8px 15px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.code-execution-results {
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
background-color: #f0f0f0;
|
||||
border-radius: 5px;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Code Execution Service Test</h1>
|
||||
|
||||
<div class="test-container">
|
||||
<h2>Test 1: Python (Auto-detect)</h2>
|
||||
<pre><code id="python-code">print("Hello from Python!")
|
||||
for i in range(3):
|
||||
print(f"Count: {i}")</code></pre>
|
||||
<button onclick="testExecution('python-code', null)">▶ Run (Auto-detect)</button>
|
||||
<div id="python-code-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-container">
|
||||
<h2>Test 2: JavaScript (Specified)</h2>
|
||||
<pre><code id="js-code" class="language-javascript">console.log("Hello from JavaScript!");
|
||||
const arr = [1, 2, 3];
|
||||
arr.forEach(n => console.log(`Number: ${n}`));</code></pre>
|
||||
<button onclick="testExecution('js-code', 'javascript')">▶ Run JavaScript</button>
|
||||
<div id="js-code-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-container">
|
||||
<h2>Test 3: Ruby</h2>
|
||||
<pre><code id="ruby-code">puts "Hello from Ruby!"
|
||||
3.times do |i|
|
||||
puts "Iteration #{i}"
|
||||
end</code></pre>
|
||||
<button onclick="testExecution('ruby-code', 'ruby')">▶ Run Ruby</button>
|
||||
<div id="ruby-code-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-container">
|
||||
<h2>Test 4: Go</h2>
|
||||
<pre><code id="go-code" class="language-go">package main
|
||||
import "fmt"
|
||||
func main() {
|
||||
fmt.Println("Hello from Go!")
|
||||
}</code></pre>
|
||||
<button onclick="testExecution('go-code', 'go')">▶ Run Go</button>
|
||||
<div id="go-code-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-container">
|
||||
<h2>Test 5: C++</h2>
|
||||
<pre><code id="cpp-code" class="language-cpp">#include <iostream>
|
||||
using namespace std;
|
||||
int main() {
|
||||
cout << "Hello from C++!" << endl;
|
||||
return 0;
|
||||
}</code></pre>
|
||||
<button onclick="testExecution('cpp-code', 'cpp')">▶ Run C++</button>
|
||||
<div id="cpp-code-result"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const CODE_EXEC_URL = "http://cammy.foxhop.net";
|
||||
|
||||
async function testExecution(codeId, language) {
|
||||
const codeElement = document.getElementById(codeId);
|
||||
const resultElement = document.getElementById(codeId + '-result');
|
||||
const code = codeElement.textContent;
|
||||
|
||||
// Clear previous results
|
||||
resultElement.innerHTML = '<div style="color: #666;">Executing code...</div>';
|
||||
resultElement.className = 'code-execution-results';
|
||||
|
||||
try {
|
||||
let response;
|
||||
if (language) {
|
||||
// Use /execute endpoint with specific language
|
||||
response = await fetch(`${CODE_EXEC_URL}/execute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
language: language,
|
||||
code: code
|
||||
})
|
||||
});
|
||||
} else {
|
||||
// Use /run endpoint for auto-detection
|
||||
response = await fetch(`${CODE_EXEC_URL}/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
body: code
|
||||
});
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
console.log('Result:', result);
|
||||
|
||||
// Format and display results
|
||||
let outputHtml = '';
|
||||
|
||||
// Show detected language if auto-detected
|
||||
if (result.detected_language) {
|
||||
outputHtml += `<div style="color: #0066cc; margin-bottom: 8px;">✓ Detected Language: ${result.detected_language}</div>`;
|
||||
} else if (result.language) {
|
||||
outputHtml += `<div style="color: #0066cc; margin-bottom: 8px;">✓ Language: ${result.language}</div>`;
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
outputHtml += '<div style="color: #008800; font-weight: bold;">✓ Execution Successful</div>';
|
||||
|
||||
// Show stdout
|
||||
if (result.stdout) {
|
||||
outputHtml += '<div style="color: #008800; font-weight: bold; margin-top: 8px;">Output:</div>';
|
||||
outputHtml += `<div style="color: #333; margin-left: 10px;">${escapeHtml(result.stdout)}</div>`;
|
||||
}
|
||||
|
||||
// Show stderr if present
|
||||
if (result.stderr) {
|
||||
outputHtml += '<div style="color: #cc0000; font-weight: bold; margin-top: 8px;">Errors/Warnings:</div>';
|
||||
outputHtml += `<div style="color: #cc0000; margin-left: 10px;">${escapeHtml(result.stderr)}</div>`;
|
||||
}
|
||||
|
||||
// If no output at all
|
||||
if (!result.stdout && !result.stderr) {
|
||||
outputHtml += '<div style="color: #666;">(No output produced)</div>';
|
||||
}
|
||||
} else {
|
||||
// Execution failed
|
||||
outputHtml += '<div style="color: #cc0000; font-weight: bold;">✗ Execution Failed</div>';
|
||||
outputHtml += `<div style="color: #cc0000; margin-left: 10px;">${escapeHtml(result.error || result.stderr || 'Unknown error')}</div>`;
|
||||
}
|
||||
|
||||
resultElement.innerHTML = outputHtml;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error executing code:', error);
|
||||
resultElement.innerHTML = `<div style="color: #cc0000;">✗ Error: ${escapeHtml(error.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// Apply syntax highlighting
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll('pre code').forEach((block) => {
|
||||
hljs.highlightElement(block);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Loading…
Add table
Add a link
Reference in a new issue