Add CodeNomad-inspired tool rendering system
Phase 1 of enhancement plan: - Created tool-renderers.js with 13+ specialized tool renderers - Created tool-rendering.css for context-specific tool styling - Integrated into index.html with cache bust (v1769083100000) Supported tools: - bash, edit, write, read (file operations) - websearch, webfetch (web operations) - task, todowrite (agent operations) - grep, glob, list, patch (utilities) Each tool gets specialized rendering showing the most relevant information in a user-friendly format. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
568
public/claude-ide/tool-renderers.js
Normal file
568
public/claude-ide/tool-renderers.js
Normal file
@@ -0,0 +1,568 @@
|
||||
/**
|
||||
* Tool Call Renderers - Specialized rendering per tool type
|
||||
* Inspired by CodeNomad's tool rendering system
|
||||
* https://github.com/NeuralNomadsAI/CodeNomad
|
||||
*
|
||||
* Each tool type gets specialized rendering to show the most relevant information
|
||||
* in a user-friendly, context-specific way.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
// ============================================================
|
||||
// Tool Renderer Registry
|
||||
// ============================================================
|
||||
|
||||
class ToolRendererRegistry {
|
||||
constructor() {
|
||||
this.renderers = new Map();
|
||||
this.registerDefaultRenderers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a tool renderer
|
||||
* @param {string} toolName - Name of the tool
|
||||
* @param {Object} renderer - Renderer object with getAction, getTitle, renderBody
|
||||
*/
|
||||
register(toolName, renderer) {
|
||||
this.renderers.set(toolName, renderer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get renderer for a tool
|
||||
* @param {string} toolName - Name of the tool
|
||||
* @returns {Object} - Renderer object
|
||||
*/
|
||||
get(toolName) {
|
||||
return this.renderers.get(toolName) || this.renderers.get('default');
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all default tool renderers
|
||||
*/
|
||||
registerDefaultRenderers() {
|
||||
// Bash/Shell Commands
|
||||
this.register('bash', {
|
||||
icon: '⚡',
|
||||
getAction: (input) => 'Writing command...',
|
||||
getTitle: (input, output, metadata) => {
|
||||
const desc = input.description || input.command || '';
|
||||
const timeout = input.timeout ? `· ${input.timeout}ms` : '';
|
||||
return desc ? `Shell ${desc} ${timeout}`.trim() : 'Shell';
|
||||
},
|
||||
renderBody: (input, output, metadata) => {
|
||||
const command = input.command ? `$ ${escapeHtml(input.command)}` : '';
|
||||
const out = metadata.output || output || '';
|
||||
const exitCode = metadata.exitCode !== undefined ? `Exit: ${metadata.exitCode}` : '';
|
||||
|
||||
return `
|
||||
<div class="tool-bash">
|
||||
${command ? `<div class="bash-command">${command}</div>` : ''}
|
||||
${out ? `<div class="bash-output">${formatAnsiOutput(escapeHtml(out))}</div>` : ''}
|
||||
${exitCode ? `<div class="bash-exit">${exitCode}</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// File Edit
|
||||
this.register('edit', {
|
||||
icon: '✏️',
|
||||
getAction: () => 'Preparing edit...',
|
||||
getTitle: (input) => {
|
||||
const file = input.filePath?.split('/').pop() || 'file';
|
||||
return `Edit ${file}`;
|
||||
},
|
||||
renderBody: (input, output, metadata) => {
|
||||
const diff = metadata.diff || output;
|
||||
const filePath = input.filePath || 'unknown';
|
||||
|
||||
if (diff) {
|
||||
return `
|
||||
<div class="tool-edit">
|
||||
<div class="edit-file">Modified: ${escapeHtml(filePath)}</div>
|
||||
<div class="edit-diff">${formatDiff(diff)}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const stats = metadata.stats || {};
|
||||
const statsText = stats.added || stats.removed ?
|
||||
`${stats.added || 0} additions, ${stats.removed || 0} deletions` : '';
|
||||
|
||||
return `
|
||||
<div class="tool-edit">
|
||||
<div class="edit-file">Modified: ${escapeHtml(filePath)}</div>
|
||||
${statsText ? `<div class="edit-stats">${statsText}</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// File Write
|
||||
this.register('write', {
|
||||
icon: '📝',
|
||||
getAction: () => 'Writing file...',
|
||||
getTitle: (input) => {
|
||||
const file = input.filePath?.split('/').pop() || 'file';
|
||||
return `Write ${file}`;
|
||||
},
|
||||
renderBody: (input, output) => {
|
||||
const filePath = input.filePath || 'unknown';
|
||||
const content = output || '';
|
||||
const lines = content.split('\n').length;
|
||||
const size = new Blob([content]).size;
|
||||
|
||||
return `
|
||||
<div class="tool-write">
|
||||
<div class="write-file">Created: ${escapeHtml(filePath)}</div>
|
||||
<div class="write-stats">${lines} lines (${formatBytes(size)})</div>
|
||||
${content ? `<div class="write-preview"><pre>${escapeHtml(content.split('\n').slice(0, 6).join('\n'))}${lines > 6 ? '\n...' : ''}</pre></div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// File Read
|
||||
this.register('read', {
|
||||
icon: '📖',
|
||||
getAction: () => 'Reading file...',
|
||||
getTitle: (input) => {
|
||||
const file = input.filePath?.split('/').pop() || 'file';
|
||||
return `Read ${file}`;
|
||||
},
|
||||
renderBody: (input, output, metadata) => {
|
||||
const preview = metadata.preview || output || '';
|
||||
const filePath = input.filePath || 'unknown';
|
||||
|
||||
if (preview) {
|
||||
const lines = preview.split('\n').slice(0, 6).join('\n');
|
||||
const totalLines = preview.split('\n').length;
|
||||
|
||||
return `
|
||||
<div class="tool-read">
|
||||
<div class="read-file">Read: ${escapeHtml(filePath)}</div>
|
||||
<div class="read-preview"><pre>${escapeHtml(lines)}${totalLines > 6 ? '\n...' : ''}</pre></div>
|
||||
<div class="read-stats">${totalLines} lines total</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="tool-read">
|
||||
<div class="read-file">Read: ${escapeHtml(filePath)}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Web Search
|
||||
this.register('websearch', {
|
||||
icon: '🔍',
|
||||
getAction: () => 'Searching...',
|
||||
getTitle: (input) => {
|
||||
const query = input.query?.substring(0, 50) || '';
|
||||
return query ? `Search: ${query}...` : 'Search';
|
||||
},
|
||||
renderBody: (input, output) => {
|
||||
if (Array.isArray(output)) {
|
||||
return `
|
||||
<div class="tool-search-results">
|
||||
${output.map(result => `
|
||||
<div class="search-result">
|
||||
<a href="${escapeHtml(result.url || '')}" target="_blank" rel="noopener">${escapeHtml(result.title || '')}</a>
|
||||
<div class="result-snippet">${escapeHtml(result.snippet || result.description || '')}</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Fallback for string output
|
||||
if (typeof output === 'string') {
|
||||
return `<div class="tool-search-results"><pre>${escapeHtml(output.substring(0, 500))}</pre></div>`;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
// WebFetch
|
||||
this.register('webfetch', {
|
||||
icon: '🌐',
|
||||
getAction: () => 'Fetching...',
|
||||
getTitle: (input) => {
|
||||
const url = input.url?.substring(0, 50) || '';
|
||||
return url ? `Fetch ${url}...` : 'Fetch';
|
||||
},
|
||||
renderBody: (input, output, metadata) => {
|
||||
const url = input.url || '';
|
||||
const content = output || '';
|
||||
const preview = content.substring(0, 300);
|
||||
|
||||
return `
|
||||
<div class="tool-fetch">
|
||||
<div class="fetch-url"><a href="${escapeHtml(url)}" target="_blank" rel="noopener">${escapeHtml(url)}</a></div>
|
||||
<div class="fetch-preview"><pre>${escapeHtml(preview)}${content.length > 300 ? '...' : ''}</pre></div>
|
||||
${content.length > 300 ? `<div class="fetch-stats">${content.length} characters</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Task/Agent Delegation
|
||||
this.register('task', {
|
||||
icon: '🤖',
|
||||
getAction: () => 'Delegating...',
|
||||
getTitle: (input) => {
|
||||
const type = input.subagent_type || 'agent';
|
||||
const desc = input.description?.substring(0, 40) || '';
|
||||
return desc ? `Task[${type}] ${desc}...` : `Task[${type}]`;
|
||||
},
|
||||
renderBody: (input, output, metadata) => {
|
||||
const summary = metadata.summary || [];
|
||||
const result = output;
|
||||
|
||||
if (summary.length > 0) {
|
||||
return `
|
||||
<div class="tool-task-summary">
|
||||
${summary.map(item => `
|
||||
<div class="task-item">
|
||||
<span class="task-icon">${getToolIcon(item.tool)}</span>
|
||||
<span class="task-desc">${escapeHtml(item.description || item.tool)}</span>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
if (result && typeof result === 'string') {
|
||||
return `<div class="tool-task-result"><pre>${escapeHtml(result.substring(0, 500))}</pre></div>`;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
// Todo/Plan Management
|
||||
this.register('todowrite', {
|
||||
icon: '📋',
|
||||
getAction: (input) => {
|
||||
const todos = input.todos || [];
|
||||
const allPending = todos.every(t => t.status === 'pending');
|
||||
const allCompleted = todos.every(t => t.status === 'completed');
|
||||
if (allPending) return 'Creating plan...';
|
||||
if (allCompleted) return 'Completing plan...';
|
||||
return 'Updating plan...';
|
||||
},
|
||||
getTitle: (input) => {
|
||||
const todos = input.todos || [];
|
||||
const completed = todos.filter(t => t.status === 'completed').length;
|
||||
const total = todos.length;
|
||||
return `Plan (${completed}/${total})`;
|
||||
},
|
||||
renderBody: (input) => {
|
||||
const todos = input.todos || [];
|
||||
return `
|
||||
<div class="tool-todos">
|
||||
${todos.map(todo => `
|
||||
<div class="todo-item todo-${todo.status}">
|
||||
<span class="todo-checkbox">
|
||||
${todo.status === 'completed' ? '☑' :
|
||||
todo.status === 'in_progress' ? '☐' : '☐'}
|
||||
</span>
|
||||
<span class="todo-text">${escapeHtml(todo.content)}</span>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Grep - Content Search
|
||||
this.register('grep', {
|
||||
icon: '🔎',
|
||||
getAction: () => 'Searching...',
|
||||
getTitle: (input) => {
|
||||
const pattern = input.pattern?.substring(0, 40) || '';
|
||||
return pattern ? `Grep "${pattern}"` : 'Grep';
|
||||
},
|
||||
renderBody: (input, output) => {
|
||||
if (Array.isArray(output)) {
|
||||
return `
|
||||
<div class="tool-grep-results">
|
||||
${output.slice(0, 20).map(match => `
|
||||
<div class="grep-match">
|
||||
<div class="grep-file">${escapeHtml(match.path || match.file || '')}</div>
|
||||
<div class="grep-line">Line ${match.line || '?'}: ${escapeHtml(match.text || match.content || '').substring(0, 100)}</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
${output.length > 20 ? `<div class="grep-stats">+${output.length - 20} more matches</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
// Glob - File Pattern Matching
|
||||
this.register('glob', {
|
||||
icon: '📁',
|
||||
getAction: () => 'Searching files...',
|
||||
getTitle: (input) => {
|
||||
const pattern = input.pattern?.substring(0, 50) || '';
|
||||
return pattern ? `Glob ${pattern}` : 'Glob';
|
||||
},
|
||||
renderBody: (input, output) => {
|
||||
const files = output || [];
|
||||
const count = files.length;
|
||||
|
||||
if (count > 0) {
|
||||
return `
|
||||
<div class="tool-glob-results">
|
||||
<div class="glob-stats">${count} file${count !== 1 ? 's' : ''} found</div>
|
||||
<div class="glob-files">
|
||||
${files.slice(0, 15).map(f => `<div class="glob-file">${escapeHtml(f)}</div>`).join('')}
|
||||
</div>
|
||||
${count > 15 ? `<div class="glob-more">+${count - 15} more files</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return '<div class="tool-empty">No files found</div>';
|
||||
}
|
||||
});
|
||||
|
||||
// List - Directory Listing
|
||||
this.register('list', {
|
||||
icon: '📂',
|
||||
getAction: () => 'Listing directory...',
|
||||
getTitle: (input) => {
|
||||
const path = input.path || '';
|
||||
return `List ${path.split('/').pop() || 'directory'}`;
|
||||
},
|
||||
renderBody: (input, output) => {
|
||||
const entries = output?.entries || [];
|
||||
return `
|
||||
<div class="tool-list-results">
|
||||
${entries.slice(0, 20).map(entry => `
|
||||
<div class="list-entry">
|
||||
<span class="entry-icon">${entry.type === 'directory' ? '📁' : '📄'}</span>
|
||||
<span class="entry-name">${escapeHtml(entry.name)}</span>
|
||||
</div>
|
||||
`).join('')}
|
||||
${entries.length > 20 ? `<div class="list-more">+${entries.length - 20} more entries</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Patch - Apply Patch
|
||||
this.register('patch', {
|
||||
icon: '🔧',
|
||||
getAction: () => 'Applying patch...',
|
||||
getTitle: () => 'Patch',
|
||||
renderBody: (input, output) => {
|
||||
return `
|
||||
<div class="tool-patch">
|
||||
<div class="patch-applied">Patch applied successfully</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Default fallback for unknown tools
|
||||
this.register('default', {
|
||||
icon: '🔧',
|
||||
getAction: () => 'Processing...',
|
||||
getTitle: (input, toolName) => {
|
||||
return capitalize(toolName || 'tool');
|
||||
},
|
||||
renderBody: (input, output) => {
|
||||
if (typeof output === 'string' && output) {
|
||||
const preview = output.split('\n').slice(0, 10).join('\n');
|
||||
return `<div class="tool-default"><pre>${escapeHtml(preview)}</pre></div>`;
|
||||
}
|
||||
if (output && typeof output === 'object') {
|
||||
return `<div class="tool-default"><pre>${escapeHtml(JSON.stringify(output, null, 2).substring(0, 500))}</pre></div>`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helper Functions
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Escape HTML to prevent XSS
|
||||
*/
|
||||
function escapeHtml(text) {
|
||||
if (text === null || text === undefined) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capitalize first letter
|
||||
*/
|
||||
function capitalize(str) {
|
||||
if (!str) return '';
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format bytes to human readable size
|
||||
*/
|
||||
function formatBytes(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
/**
|
||||
* Format ANSI escape sequences for terminal output
|
||||
*/
|
||||
function formatAnsiOutput(text) {
|
||||
// Simple ANSI to HTML conversion
|
||||
// Remove ANSI codes for now (can be enhanced with proper library)
|
||||
return text
|
||||
.replace(/\x1b\[[0-9;]*m/g, '') // Remove ANSI color codes
|
||||
.replace(/\x1b\[[0-9;]*K/g, ''); // Remove ANSI erase codes
|
||||
}
|
||||
|
||||
/**
|
||||
* Format unified diff for display
|
||||
*/
|
||||
function formatDiff(diff) {
|
||||
if (!diff) return '';
|
||||
|
||||
const lines = diff.split('\n');
|
||||
let html = '';
|
||||
|
||||
for (const line of lines) {
|
||||
let className = 'diff-line';
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
className += ' diff-add';
|
||||
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
className += ' diff-remove';
|
||||
} else if (line.startsWith('@@')) {
|
||||
className += ' diff-hunk';
|
||||
}
|
||||
|
||||
html += `<div class="${className}">${escapeHtml(line)}</div>`;
|
||||
}
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get icon for tool type
|
||||
*/
|
||||
function getToolIcon(toolName) {
|
||||
const icons = {
|
||||
'bash': '⚡',
|
||||
'edit': '✏️',
|
||||
'write': '📝',
|
||||
'read': '📖',
|
||||
'websearch': '🔍',
|
||||
'webfetch': '🌐',
|
||||
'task': '🤖',
|
||||
'todowrite': '📋',
|
||||
'grep': '🔎',
|
||||
'glob': '📁',
|
||||
'list': '📂'
|
||||
};
|
||||
return icons[toolName] || '🔧';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get status icon for tool state
|
||||
*/
|
||||
function getStatusIcon(status) {
|
||||
const icons = {
|
||||
'pending': '⏳',
|
||||
'running': '⚡',
|
||||
'completed': '✓',
|
||||
'error': '✗'
|
||||
};
|
||||
return icons[status] || '⏳';
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Public API
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Render a tool call with specialized renderer
|
||||
* @param {Object} toolCall - Tool call object
|
||||
* @param {string} status - Tool status (pending, running, completed, error)
|
||||
* @returns {string} - HTML string
|
||||
*/
|
||||
function renderToolCall(toolCall, status = 'pending') {
|
||||
const registry = window.toolRendererRegistry;
|
||||
if (!registry) return '';
|
||||
|
||||
const renderer = registry.get(toolCall.name);
|
||||
const input = toolCall.input || {};
|
||||
const output = toolCall.output;
|
||||
const metadata = toolCall.metadata || {};
|
||||
const toolId = toolCall.id || `tool-${Date.now()}`;
|
||||
|
||||
const icon = renderer.icon;
|
||||
const action = status === 'pending'
|
||||
? renderer.getAction(input)
|
||||
: renderer.getTitle(input, output, metadata);
|
||||
|
||||
const body = status !== 'pending'
|
||||
? renderer.renderBody(input, output, metadata)
|
||||
: '';
|
||||
|
||||
return `
|
||||
<div class="tool-call tool-status-${status}" data-tool-id="${toolId}" data-tool-name="${escapeHtml(toolCall.name || '')}">
|
||||
<button class="tool-header" onclick="window.toggleToolCall('${toolId}')">
|
||||
<span class="tool-expand">▶</span>
|
||||
<span class="tool-icon">${icon}</span>
|
||||
<span class="tool-action">${escapeHtml(action)}</span>
|
||||
<span class="tool-status">${getStatusIcon(status)}</span>
|
||||
</button>
|
||||
<div class="tool-body" id="tool-body-${toolId}" style="display: ${status !== 'pending' ? 'block' : 'none'};">
|
||||
${body}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle tool call expand/collapse
|
||||
*/
|
||||
function toggleToolCall(toolId) {
|
||||
const body = document.getElementById(`tool-body-${toolId}`);
|
||||
const header = body?.previousElementSibling;
|
||||
const expand = header?.querySelector('.tool-expand');
|
||||
|
||||
if (body && header && expand) {
|
||||
const isCollapsed = body.style.display === 'none';
|
||||
body.style.display = isCollapsed ? 'block' : 'none';
|
||||
expand.textContent = isCollapsed ? '▼' : '▶';
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Initialize
|
||||
// ============================================================
|
||||
|
||||
// Create global registry
|
||||
window.toolRendererRegistry = new ToolRendererRegistry();
|
||||
|
||||
// Export functions
|
||||
window.renderToolCall = renderToolCall;
|
||||
window.toggleToolCall = toggleToolCall;
|
||||
|
||||
console.log('[ToolRenderers] Tool renderer registry initialized with ' +
|
||||
window.toolRendererRegistry.renderers.size + ' renderers');
|
||||
Reference in New Issue
Block a user