mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Use OS shell for ShellTool on Electron
This commit is contained in:
17 files changed
+1334
-32
No files matched your search
@@ -154,7 +154,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_protocol: new NostrReadProtocolTool(),
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
};
|
||||
|
||||
|
||||
+65
-17
@@ -38,13 +38,15 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git);
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath);
|
||||
|
||||
// Add welcome message
|
||||
const isElectron = !!window.electron?.shell;
|
||||
const terminalType = isElectron ? 'Real Terminal (OS Shell)' : 'Virtual Terminal';
|
||||
setLines([{
|
||||
id: Date.now().toString(),
|
||||
type: 'output',
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
content: `Welcome to Shakespeare Terminal (${terminalType})\n${isElectron ? 'Running real shell commands on your OS.' : "Type 'help' to see available commands."}`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git, projectsPath]);
|
||||
@@ -81,7 +83,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
}, []);
|
||||
|
||||
const executeCommand = useCallback(async (command: string) => {
|
||||
if (!shellToolRef.current || !command.trim()) return;
|
||||
if (!command.trim()) return;
|
||||
|
||||
// Add command to history
|
||||
if (command.trim() && !commandHistory.includes(command.trim())) {
|
||||
@@ -95,21 +97,67 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
setIsExecuting(true);
|
||||
|
||||
try {
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else if (command.trim() === 'clear') {
|
||||
// Handle special clear command
|
||||
if (command.trim() === 'clear') {
|
||||
setLines([]);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
setIsExecuting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
// Check if running in Electron - use real shell
|
||||
if (window.electron?.shell) {
|
||||
// Get relative path from projects root
|
||||
// Remove the projectsPath prefix to get the relative path for the OS
|
||||
const projectsPrefix = projectsPath.endsWith('/')
|
||||
? projectsPath
|
||||
: projectsPath + '/';
|
||||
|
||||
const fullCwd = `${projectsPath}/${projectId}`;
|
||||
const relativeCwd = fullCwd.startsWith(projectsPrefix)
|
||||
? fullCwd.substring(projectsPrefix.length)
|
||||
: fullCwd;
|
||||
|
||||
const result = await window.electron.shell.exec(command, relativeCwd);
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
|
||||
if (result.stdout) {
|
||||
output += result.stdout;
|
||||
}
|
||||
|
||||
if (result.stderr) {
|
||||
if (output) output += '\n';
|
||||
output += result.stderr;
|
||||
}
|
||||
|
||||
// Add exit code info for non-zero exits
|
||||
if (result.exitCode !== 0) {
|
||||
if (output) output += '\n';
|
||||
output += `Exit code: ${result.exitCode}`;
|
||||
}
|
||||
|
||||
if (output) {
|
||||
addLine('output', output);
|
||||
}
|
||||
} else {
|
||||
// Use virtual shell (browser mode)
|
||||
if (!shellToolRef.current) return;
|
||||
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -117,7 +165,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory]);
|
||||
}, [addLine, commandHistory, projectId, projectsPath]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ansiToHtml, containsAnsiCodes, stripAnsiCodes } from './ansiToHtml';
|
||||
|
||||
describe('ansiToHtml', () => {
|
||||
it('should convert basic color codes to HTML', () => {
|
||||
const input = '\u001b[31mRed text\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('text-red-500');
|
||||
expect(output).toContain('Red text');
|
||||
});
|
||||
|
||||
it('should handle multiple color codes', () => {
|
||||
const input = '\u001b[31mRed\u001b[0m \u001b[32mGreen\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('text-red-500');
|
||||
expect(output).toContain('text-green-500');
|
||||
});
|
||||
|
||||
it('should return original text if no ANSI codes', () => {
|
||||
const input = 'Plain text';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
it('should handle bold text', () => {
|
||||
const input = '\u001b[1mBold text\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('font-bold');
|
||||
});
|
||||
|
||||
it('should handle background colors', () => {
|
||||
const input = '\u001b[41mRed background\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('bg-red-500');
|
||||
});
|
||||
});
|
||||
|
||||
describe('containsAnsiCodes', () => {
|
||||
it('should detect ANSI codes', () => {
|
||||
expect(containsAnsiCodes('\u001b[31mRed\u001b[0m')).toBe(true);
|
||||
expect(containsAnsiCodes('\u001b[1mBold\u001b[0m')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for plain text', () => {
|
||||
expect(containsAnsiCodes('Plain text')).toBe(false);
|
||||
expect(containsAnsiCodes('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripAnsiCodes', () => {
|
||||
it('should remove basic color codes', () => {
|
||||
const input = '\u001b[31mRed text\u001b[0m';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Red text');
|
||||
});
|
||||
|
||||
it('should remove multiple ANSI codes', () => {
|
||||
const input = '\u001b[31mRed\u001b[0m \u001b[32mGreen\u001b[0m \u001b[1mBold\u001b[0m';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Red Green Bold');
|
||||
});
|
||||
|
||||
it('should remove cursor movement codes', () => {
|
||||
const input = 'Text\u001b[2AMove up\u001b[1BMove down';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('TextMove upMove down');
|
||||
});
|
||||
|
||||
it('should remove clear screen codes', () => {
|
||||
const input = 'Before\u001b[2JAfter';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('BeforeAfter');
|
||||
});
|
||||
|
||||
it('should handle text without ANSI codes', () => {
|
||||
const input = 'Plain text';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
it('should handle empty string', () => {
|
||||
const output = stripAnsiCodes('');
|
||||
expect(output).toBe('');
|
||||
});
|
||||
|
||||
it('should handle npm output with ANSI codes', () => {
|
||||
const input = '\u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('added 142 packages in 3s');
|
||||
});
|
||||
|
||||
it('should handle git status output with ANSI codes', () => {
|
||||
const input = 'On branch \u001b[32mmain\u001b[m\nYour branch is up to date';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('On branch main\nYour branch is up to date');
|
||||
});
|
||||
|
||||
it('should preserve newlines and spaces', () => {
|
||||
const input = '\u001b[31mLine 1\u001b[0m\n\u001b[32mLine 2\u001b[0m\n Indented';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Line 1\nLine 2\n Indented');
|
||||
});
|
||||
});
|
||||
+25
-11
@@ -49,15 +49,15 @@ const styleMap: Record<string, string> = {
|
||||
export function ansiToHtml(text: string): string {
|
||||
// Regular expression to match ANSI escape sequences
|
||||
const ansiRegex = /\u001b\[((?:\d+;)*\d+)m/g;
|
||||
|
||||
|
||||
// Initialize result and current style classes
|
||||
let result = '';
|
||||
let currentClasses: string[] = [];
|
||||
|
||||
|
||||
// Find all matches and their positions
|
||||
const matches: Array<{index: number, length: number, codes: string}> = [];
|
||||
let match;
|
||||
|
||||
|
||||
while ((match = ansiRegex.exec(text)) !== null) {
|
||||
matches.push({
|
||||
index: match.index,
|
||||
@@ -65,15 +65,15 @@ export function ansiToHtml(text: string): string {
|
||||
codes: match[1]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// If no ANSI codes found, return the original text
|
||||
if (matches.length === 0) {
|
||||
return text;
|
||||
}
|
||||
|
||||
|
||||
// Process the text with ANSI codes
|
||||
let lastIndex = 0;
|
||||
|
||||
|
||||
for (const match of matches) {
|
||||
// Add text before this match with current styling
|
||||
if (match.index > lastIndex) {
|
||||
@@ -84,10 +84,10 @@ export function ansiToHtml(text: string): string {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update current classes based on ANSI codes
|
||||
const codes = match.codes.split(';');
|
||||
|
||||
|
||||
for (const code of codes) {
|
||||
if (code === '0') {
|
||||
// Reset all styles
|
||||
@@ -109,11 +109,11 @@ export function ansiToHtml(text: string): string {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update lastIndex to after this match
|
||||
lastIndex = match.index + match.length;
|
||||
}
|
||||
|
||||
|
||||
// Add any remaining text
|
||||
if (lastIndex < text.length) {
|
||||
const textSegment = text.substring(lastIndex);
|
||||
@@ -123,7 +123,7 @@ export function ansiToHtml(text: string): string {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -132,4 +132,18 @@ export function ansiToHtml(text: string): string {
|
||||
*/
|
||||
export function containsAnsiCodes(text: string): boolean {
|
||||
return /\u001b\[(?:\d+;)*\d+m/.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip all ANSI escape sequences from a string
|
||||
* This removes color codes, cursor movements, and other terminal control sequences
|
||||
*/
|
||||
export function stripAnsiCodes(text: string): string {
|
||||
// Remove all ANSI escape sequences
|
||||
// This regex matches:
|
||||
// - Color codes: \u001b[...m
|
||||
// - Cursor movement: \u001b[...H, \u001b[...A, etc.
|
||||
// - Clear screen: \u001b[...J, \u001b[...K
|
||||
// - Other escape sequences
|
||||
return text.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '');
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand } from "../commands/ShellCommand";
|
||||
import { Git } from "../git";
|
||||
import { stripAnsiCodes } from "../ansiToHtml";
|
||||
import {
|
||||
CatCommand,
|
||||
CdCommand,
|
||||
@@ -49,6 +50,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private cwd: string;
|
||||
private git: Git;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
private projectsPath: string;
|
||||
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
|
||||
|
||||
@@ -58,10 +60,11 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
),
|
||||
});
|
||||
|
||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git) {
|
||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects') {
|
||||
this.fs = fs;
|
||||
this.cwd = cwd;
|
||||
this.git = git;
|
||||
this.projectsPath = projectsPath;
|
||||
this.commands = new Map();
|
||||
|
||||
// Register available commands
|
||||
@@ -324,6 +327,11 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
return "Error: Empty command";
|
||||
}
|
||||
|
||||
// Check if running in Electron - if so, use real shell execution
|
||||
if (window.electron?.shell) {
|
||||
return this.executeRealShell(commandStr);
|
||||
}
|
||||
|
||||
// Parse compound commands
|
||||
const commands = this.parseCompoundCommand(commandStr);
|
||||
|
||||
@@ -340,6 +348,56 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
return this.executeCompoundCommands(commands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute command using real shell in Electron
|
||||
*/
|
||||
private async executeRealShell(commandStr: string): Promise<string> {
|
||||
if (!window.electron?.shell) {
|
||||
throw new Error('Real shell execution is only available in Electron');
|
||||
}
|
||||
|
||||
try {
|
||||
// Get relative path from projects root
|
||||
// Remove the projectsPath prefix to get the relative path for the OS
|
||||
const projectsPrefix = this.projectsPath.endsWith('/')
|
||||
? this.projectsPath
|
||||
: this.projectsPath + '/';
|
||||
|
||||
const relativeCwd = this.cwd.startsWith(projectsPrefix)
|
||||
? this.cwd.substring(projectsPrefix.length)
|
||||
: this.cwd;
|
||||
|
||||
const result = await window.electron.shell.exec(commandStr, relativeCwd);
|
||||
|
||||
// Strip ANSI codes from output (color codes, cursor movements, etc.)
|
||||
// This is important for AI consumption and consistent output
|
||||
const cleanStdout = result.stdout ? stripAnsiCodes(result.stdout) : '';
|
||||
const cleanStderr = result.stderr ? stripAnsiCodes(result.stderr) : '';
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
|
||||
if (cleanStdout) {
|
||||
output += cleanStdout;
|
||||
}
|
||||
|
||||
if (cleanStderr) {
|
||||
if (output) output += '\n';
|
||||
output += cleanStderr;
|
||||
}
|
||||
|
||||
// Add exit code info for non-zero exits
|
||||
if (result.exitCode !== 0) {
|
||||
if (output) output += '\n';
|
||||
output += `Exit code: ${result.exitCode}`;
|
||||
}
|
||||
|
||||
return output || '(no output)';
|
||||
} catch (error) {
|
||||
return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a simple command (no compound operators)
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user