From 52f8a996541afcb1971e81bbcb39b51526561616 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 23 Oct 2025 22:51:06 -0500 Subject: [PATCH] Use OS shell for ShellTool on Electron --- AGENTS.md | 13 +- README.md | 1 + electron/ARCHITECTURE.md | 456 ++++++++++++++++++++++++ electron/FEATURES.md | 165 +++++++++ electron/INDEX.md | 30 ++ electron/README.md | 15 +- electron/REAL_TERMINAL.md | 196 ++++++++++ electron/TROUBLESHOOTING.md | 34 ++ electron/electron.d.ts | 22 ++ electron/main.js | 62 ++++ electron/preload.js | 5 + electron/test-terminal.js | 84 +++++ src/components/Shakespeare/ChatPane.tsx | 2 +- src/components/Terminal.tsx | 82 ++++- src/lib/ansiToHtml.test.ts | 103 ++++++ src/lib/ansiToHtml.ts | 36 +- src/lib/tools/ShellTool.ts | 60 +++- 17 files changed, 1334 insertions(+), 32 deletions(-) create mode 100644 electron/ARCHITECTURE.md create mode 100644 electron/FEATURES.md create mode 100644 electron/REAL_TERMINAL.md create mode 100644 electron/test-terminal.js create mode 100644 src/lib/ansiToHtml.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3aa30b40..76b0ca21 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ This architecture allows Shakespeare to provide a full development environment e Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`: -- **ShellTool**: Execute shell commands in the virtual filesystem environment +- **ShellTool**: Execute shell commands (virtual in browser, real OS shell in Electron) - **TextEditorViewTool**: Read file contents and view directory structures - **TextEditorWriteTool**: Create or overwrite files with new content - **TextEditorStrReplaceTool**: Replace strings in files @@ -55,6 +55,7 @@ Shakespeare provides AI agents with specialized tools for project development (n #### Shell Commands +**In Browser Mode:** Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations. **Available Commands:** @@ -63,6 +64,16 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r - **System Commands**: `echo`, `which`, `wc`, `head`, `tail` - **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc. +**In Electron Mode:** +When running in Electron, the ShellTool automatically uses the **real OS terminal** instead of the virtual terminal. This means: +- **All OS commands available**: Not limited to built-in commands +- **Native shell features**: Pipes, redirection, environment variables work natively +- **Package managers**: `npm`, `yarn`, `pnpm` work directly +- **Build tools**: `vite`, `webpack`, `tsc`, etc. available +- **System utilities**: Full access to OS commands + +The ShellTool detects the environment automatically and uses the appropriate execution method. + #### Security AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation: diff --git a/README.md b/README.md index 2cec5545..68075708 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The p Shakespeare can be built and run as a native desktop application using Electron. This provides: - **Local filesystem access** - Projects stored at `~/shakespeare` on your OS +- **Real OS terminal** - Execute any system command, not just built-in commands - **Direct file access** - Use any code editor, Git client, or file manager - **No storage limits** - Only limited by your disk space - **Native window management** and OS integration diff --git a/electron/ARCHITECTURE.md b/electron/ARCHITECTURE.md new file mode 100644 index 00000000..f0ef1f90 --- /dev/null +++ b/electron/ARCHITECTURE.md @@ -0,0 +1,456 @@ +# Electron Architecture + +This document describes the architecture of Shakespeare's Electron implementation, focusing on the real terminal feature. + +## Overview + +Shakespeare's Electron app uses a standard Electron architecture with a main process, renderer process, and preload script for secure IPC communication. + +## Process Architecture + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Electron App │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Main Process │ │ +│ │ (Node.js/Electron) │ │ +│ ├───────────────────────────────────────────────────────────┤ │ +│ │ │ │ +│ │ • File System Operations (fs module) │ │ +│ │ • Shell Execution (child_process.spawn) │ │ +│ │ • IPC Handlers (ipcMain) │ │ +│ │ • Window Management │ │ +│ │ │ │ +│ │ Working Directory: ~/shakespeare │ │ +│ │ │ │ +│ └────────────────────────┬──────────────────────────────────┘ │ +│ │ │ +│ │ IPC Bridge │ +│ │ (contextBridge) │ +│ │ │ +│ ┌────────────────────────┴──────────────────────────────────┐ │ +│ │ Preload Script │ │ +│ │ (Secure IPC Bridge - ESM) │ │ +│ ├───────────────────────────────────────────────────────────┤ │ +│ │ │ │ +│ │ Exposes to Renderer: │ │ +│ │ • window.electron.isElectron │ │ +│ │ • window.electron.platform() │ │ +│ │ • window.electron.version() │ │ +│ │ • window.electron.fs.* │ │ +│ │ • window.electron.shell.exec() ← NEW │ │ +│ │ │ │ +│ └────────────────────────┬──────────────────────────────────┘ │ +│ │ │ +│ │ window.electron API │ +│ │ │ +│ ┌────────────────────────┴──────────────────────────────────┐ │ +│ │ Renderer Process │ │ +│ │ (React/TypeScript) │ │ +│ ├───────────────────────────────────────────────────────────┤ │ +│ │ │ │ +│ │ ┌──────────────────────────────────────────────────┐ │ │ +│ │ │ Terminal Component │ │ │ +│ │ │ • Detects window.electron.shell │ │ │ +│ │ │ • Routes to real shell if available │ │ │ +│ │ │ • Falls back to virtual shell in browser │ │ │ +│ │ └──────────────────────────────────────────────────┘ │ │ +│ │ │ │ +│ │ ┌──────────────────────────────────────────────────┐ │ │ +│ │ │ ShellTool (AI) │ │ │ +│ │ │ • Detects window.electron.shell │ │ │ +│ │ │ • Routes to real shell if available │ │ │ +│ │ │ • Falls back to virtual commands in browser │ │ │ +│ │ └──────────────────────────────────────────────────┘ │ │ +│ │ │ │ +│ │ ┌──────────────────────────────────────────────────┐ │ │ +│ │ │ ElectronFSAdapter │ │ │ +│ │ │ • Implements JSRuntimeFS interface │ │ │ +│ │ │ • Routes to window.electron.fs.* │ │ │ +│ │ └──────────────────────────────────────────────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +## Shell Execution Flow + +### Browser Mode (Virtual Shell) + +``` +User Input: "ls -la" + │ + ▼ +┌────────────────┐ +│ Terminal.tsx │ +└────────┬───────┘ + │ + ▼ +┌────────────────┐ +│ ShellTool │ +│ (Virtual) │ +└────────┬───────┘ + │ + ▼ +┌────────────────┐ +│ LsCommand │ +│ (JavaScript) │ +└────────┬───────┘ + │ + ▼ +┌────────────────┐ +│ LightningFS │ +│ (IndexedDB) │ +└────────┬───────┘ + │ + ▼ + Result +``` + +### Electron Mode (Real Shell) + +``` +User Input: "ls -la" + │ + ▼ +┌────────────────────┐ +│ Terminal.tsx │ +│ (Renderer Process) │ +└─────────┬──────────┘ + │ + │ Detects window.electron.shell + │ + ▼ +┌────────────────────┐ +│ window.electron │ +│ .shell.exec() │ +└─────────┬──────────┘ + │ + │ IPC Call + │ + ▼ +┌────────────────────┐ +│ Preload Script │ +│ (IPC Bridge) │ +└─────────┬──────────┘ + │ + │ Secure IPC + │ + ▼ +┌────────────────────┐ +│ Main Process │ +│ shell:exec │ +│ IPC Handler │ +└─────────┬──────────┘ + │ + ▼ +┌────────────────────┐ +│ child_process │ +│ .spawn() │ +│ /bin/sh or cmd.exe │ +└─────────┬──────────┘ + │ + ▼ +┌────────────────────┐ +│ OS Shell │ +│ (Real Terminal) │ +└─────────┬──────────┘ + │ + ▼ +┌────────────────────┐ +│ ~/shakespeare/ │ +│ (OS Filesystem) │ +└─────────┬──────────┘ + │ + ▼ + Result + { stdout, stderr, exitCode } +``` + +## Filesystem Architecture + +### Browser Mode + +``` +┌─────────────────────────────────────┐ +│ Browser Storage │ +├─────────────────────────────────────┤ +│ │ +│ IndexedDB │ +│ ├── /projects/ │ +│ │ ├── project-1/ │ +│ │ │ ├── package.json │ +│ │ │ └── src/ │ +│ │ └── project-2/ │ +│ ├── /config/ │ +│ └── /tmp/ │ +│ │ +│ Accessed via: │ +│ • LightningFS │ +│ • LightningFSAdapter │ +│ │ +└─────────────────────────────────────┘ +``` + +### Electron Mode + +``` +┌─────────────────────────────────────┐ +│ OS Filesystem │ +├─────────────────────────────────────┤ +│ │ +│ ~/shakespeare/ │ +│ ├── projects/ │ +│ │ ├── project-1/ │ +│ │ │ ├── package.json │ +│ │ │ ├── src/ │ +│ │ │ └── node_modules/ │ +│ │ └── project-2/ │ +│ ├── config/ │ +│ └── tmp/ │ +│ │ +│ Accessed via: │ +│ • Node.js fs module (main) │ +│ • IPC calls (renderer) │ +│ • ElectronFSAdapter │ +│ │ +└─────────────────────────────────────┘ +``` + +## Security Boundaries + +``` +┌─────────────────────────────────────────────────────────┐ +│ Security Layers │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ 1. Context Isolation (PRIMARY BOUNDARY) │ +│ ✓ Renderer cannot access Node.js/Electron APIs │ +│ ✓ Only window.electron is exposed │ +│ │ +│ 2. Preload Script (CONTROLLED BRIDGE) │ +│ ✓ Only specific APIs exposed via contextBridge │ +│ ✓ No direct Node.js access from renderer │ +│ │ +│ 3. IPC Handlers (VALIDATION LAYER) │ +│ ✓ Validate all inputs │ +│ ✓ Path resolution and sanitization │ +│ ✓ Error handling and code preservation │ +│ │ +│ 4. Filesystem Restrictions │ +│ ✓ All operations relative to ~/shakespeare │ +│ ✓ No access outside this directory │ +│ │ +│ 5. Shell Execution │ +│ ✓ Commands run with user's permissions │ +│ ✓ Working directory: ~/shakespeare/projects/{id} │ +│ ✓ No elevation or sudo access │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +## API Surface + +### Exposed to Renderer + +```typescript +interface window.electron { + // Platform info + isElectron: boolean; + platform(): Promise; + version(): Promise; + + // Filesystem API + fs: { + readFile(path: string, encoding?: string): Promise; + writeFile(path: string, data: string | number[], encoding?: string): Promise; + readdir(path: string, withFileTypes?: boolean): Promise; + mkdir(path: string, recursive?: boolean): Promise; + stat(path: string): Promise; + lstat(path: string): Promise; + unlink(path: string): Promise; + rmdir(path: string): Promise; + rename(oldPath: string, newPath: string): Promise; + readlink(path: string): Promise; + symlink(target: string, path: string): Promise; + }; + + // Shell API (NEW) + shell: { + exec(command: string, cwd?: string): Promise<{ + stdout: string; + stderr: string; + exitCode: number; + }>; + }; +} +``` + +## Component Integration + +### Terminal Component + +```typescript +// Automatic detection and routing +const executeCommand = async (command: string) => { + if (window.electron?.shell) { + // Use real OS shell + const result = await window.electron.shell.exec(command, relativeCwd); + // Display result + } else { + // Use virtual shell + const result = await shellTool.execute({ command }); + // Display result + } +}; +``` + +### ShellTool (AI) + +```typescript +// Automatic detection and routing +async execute(args: ShellToolParams): Promise { + if (window.electron?.shell) { + // Use real OS shell + return this.executeRealShell(args.command); + } + + // Use virtual commands + return this.executeVirtualShell(args.command); +} +``` + +## Path Resolution + +### Virtual to OS Path Conversion + +The `projectsPath` is configurable (default: `/projects`), so path conversion respects the configured value: + +``` +VFS Path: {projectsPath}/my-app/src/index.ts + ↓ +Extract: my-app/src/index.ts + ↓ +Resolve: ~/shakespeare/{projectsPath}/my-app/src/index.ts + ↓ +OS Path: /Users/username/shakespeare/projects/my-app/src/index.ts +``` + +### Working Directory + +``` +Project ID: abc123 +VFS CWD: {projectsPath}/abc123 +Relative CWD: abc123 +OS CWD: ~/shakespeare/{projectsPath}/abc123 +Shell CWD: /Users/username/shakespeare/projects/abc123 +``` + +**Note**: The `projectsPath` is configurable via the app settings and defaults to `/projects`. + +## Error Handling + +``` +┌─────────────────────────────────────┐ +│ Error Flow │ +├─────────────────────────────────────┤ +│ │ +│ OS Error (e.g., ENOENT) │ +│ ↓ │ +│ Main Process Handler │ +│ ↓ │ +│ Preserve Error Code │ +│ ↓ │ +│ IPC Serialization │ +│ ↓ │ +│ Preload Script │ +│ ↓ │ +│ Renderer Process │ +│ ↓ │ +│ ElectronFSAdapter.unwrapError() │ +│ ↓ │ +│ Restore Original Error Code │ +│ ↓ │ +│ Application Logic │ +│ │ +└─────────────────────────────────────┘ +``` + +## Performance Considerations + +### Browser Mode +- **Filesystem**: IndexedDB queries (slower for large files) +- **Commands**: JavaScript execution (interpreted) +- **Git**: isomorphic-git (JavaScript implementation) + +### Electron Mode +- **Filesystem**: Native fs module (much faster) +- **Commands**: Native OS shell (compiled binaries) +- **Git**: isomorphic-git (same as browser)* + +\* Future: Could use native Git CLI for even better performance + +## Deployment + +``` +┌─────────────────────────────────────────────────────────┐ +│ Build Process │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ 1. npm run build │ +│ • Vite builds React app → dist/ │ +│ │ +│ 2. npm run electron:build │ +│ • electron-builder packages: │ +│ - Main process (main.js) │ +│ - Preload script (preload.js) │ +│ - Built React app (dist/) │ +│ - Icons and resources │ +│ │ +│ 3. Platform-specific installers created: │ +│ • macOS: .dmg, .app │ +│ • Windows: .exe (NSIS installer) │ +│ • Linux: .AppImage, .deb, .rpm │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +## Future Architecture Enhancements + +### Planned Improvements + +1. **Native Git CLI Integration** + - Replace isomorphic-git with native Git commands + - Faster operations, better compatibility + - Leverage existing Git installations + +2. **Multiple Windows** + - Support multiple project windows + - Shared state management + - Inter-window communication + +3. **Enhanced Terminal** + - Persistent shell sessions + - Terminal tabs and splits + - Custom shell configuration + +4. **Auto-Update** + - electron-updater integration + - Automatic update downloads + - User-controlled update installation + +5. **System Integration** + - System tray icon + - Native menus + - File associations + - Protocol handlers + +## References + +- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security) +- [Context Isolation](https://www.electronjs.org/docs/latest/tutorial/context-isolation) +- [IPC Communication](https://www.electronjs.org/docs/latest/tutorial/ipc) +- [Process Model](https://www.electronjs.org/docs/latest/tutorial/process-model) diff --git a/electron/FEATURES.md b/electron/FEATURES.md new file mode 100644 index 00000000..072c0e5b --- /dev/null +++ b/electron/FEATURES.md @@ -0,0 +1,165 @@ +# Electron Features + +Shakespeare's Electron desktop app provides several powerful features beyond the browser version. + +## Real OS Filesystem + +Projects are stored at `~/shakespeare` on your local filesystem instead of in the browser's IndexedDB. + +**Benefits:** +- Use any code editor (VS Code, Sublime, etc.) +- Use any Git client +- No storage limits (only disk space) +- Easy backup and version control +- Better performance for large projects +- Direct file access with file manager + +**Location:** +``` +~/shakespeare/ +├── projects/ +│ ├── project-1/ +│ ├── project-2/ +│ └── ... +└── ... +``` + +See [FILESYSTEM.md](./FILESYSTEM.md) for details. + +## Real OS Terminal + +The terminal executes real shell commands on your operating system instead of using virtual commands. + +**Benefits:** +- **All OS commands available** - Not limited to ~30 built-in commands +- **Package managers work** - `npm install`, `yarn add`, `pnpm install` +- **Build tools available** - `vite`, `webpack`, `tsc`, `rollup`, etc. +- **System utilities** - `grep`, `sed`, `awk`, `curl`, `wget`, etc. +- **Native shell features** - Pipes, redirection, environment variables +- **Python/Ruby/etc.** - Run scripts in any installed language + +**Examples:** + +```bash +# Install dependencies +$ npm install + +# Run build scripts +$ npm run build + +# Use system commands +$ curl https://api.example.com +$ grep -r "TODO" src/ +$ python scripts/deploy.py + +# Chain commands with pipes +$ cat package.json | grep dependencies +$ ls -la | wc -l +``` + +**AI Integration:** +AI assistants can also execute real OS commands through the ShellTool, making them much more powerful in Electron. + +See [REAL_TERMINAL.md](./REAL_TERMINAL.md) for details. + +## Native Window Management + +- **Resizable windows** with native OS controls +- **Multiple windows** support (planned) +- **Native menus** and keyboard shortcuts +- **System tray integration** (planned) +- **OS notifications** (planned) + +## Offline First + +- **No internet required** for core functionality +- **Local AI models** support (planned) +- **Cached dependencies** for faster builds +- **Git operations** work offline (local commits) + +## Better Performance + +- **Faster file operations** - Direct OS filesystem access +- **Faster builds** - Native Node.js instead of browser environment +- **Lower memory usage** - No browser overhead +- **Faster Git operations** - Native Git commands (planned) + +## Security & Privacy + +- **No cloud storage** - Everything stays on your machine +- **No telemetry** - No data sent to servers +- **Local API keys** - Stored securely on your OS +- **Full control** - You own your data and code + +## Platform Support + +- **macOS** - Native .app bundle +- **Windows** - Native .exe installer +- **Linux** - AppImage, .deb, .rpm packages + +## Comparison: Browser vs Electron + +| Feature | Browser | Electron | +|---------|---------|----------| +| **Filesystem** | Virtual (IndexedDB) | Real OS filesystem | +| **Terminal** | ~30 built-in commands | All OS commands | +| **Storage Limit** | Browser quota (~50GB) | Disk space | +| **File Access** | Only in browser | Any editor/tool | +| **Package Managers** | Not available | Full support | +| **Build Tools** | Limited | Full support | +| **Performance** | Good | Better | +| **Git** | isomorphic-git | isomorphic-git* | +| **Offline** | Yes | Yes | +| **Updates** | Automatic | Manual/Auto-update | + +\* Native Git CLI support planned + +## Getting Started + +### Installation + +Download the latest release for your platform: +- **macOS**: `Shakespeare-{version}.dmg` +- **Windows**: `Shakespeare-Setup-{version}.exe` +- **Linux**: `Shakespeare-{version}.AppImage` + +### Building from Source + +```bash +# Clone the repository +git clone https://github.com/yourusername/shakespeare.git +cd shakespeare + +# Install dependencies +npm install + +# Build for your platform +npm run electron:build + +# Or build for all platforms +npm run electron:build:all +``` + +See [QUICKSTART.md](./QUICKSTART.md) for detailed build instructions. + +## Roadmap + +Planned features for future releases: + +- [ ] Native Git CLI integration +- [ ] Multiple window support +- [ ] System tray integration +- [ ] Auto-update mechanism +- [ ] Local AI model support +- [ ] Enhanced terminal (tabs, splits) +- [ ] File watcher integration +- [ ] Native notifications +- [ ] Keyboard shortcuts customization +- [ ] Theme customization + +## Support + +For issues, questions, or feature requests: +- GitHub Issues: [Create an issue](https://github.com/yourusername/shakespeare/issues) +- Documentation: See other `.md` files in this directory +- Community: Join our Discord/Matrix (links TBD) diff --git a/electron/INDEX.md b/electron/INDEX.md index bce2ae21..97551ea4 100644 --- a/electron/INDEX.md +++ b/electron/INDEX.md @@ -11,6 +11,24 @@ Welcome to the Shakespeare Electron build documentation! This directory contains - Platform-specific instructions - Icon generation +### Features +- **[FEATURES.md](FEATURES.md)** - Overview of Electron-specific features + - Real OS filesystem + - Real OS terminal + - Native window management + - Performance benefits + - Browser vs Electron comparison +- **[REAL_TERMINAL.md](REAL_TERMINAL.md)** - Real terminal feature documentation + - How it works + - Usage examples + - Security considerations + - AI integration + - Troubleshooting +- **[FILESYSTEM.md](FILESYSTEM.md)** - Filesystem configuration details + - Storage location + - Directory structure + - File access patterns + ### Integration - **[INTEGRATION.md](INTEGRATION.md)** - Guide for integrating Electron features into Shakespeare - Detecting Electron environment @@ -27,6 +45,13 @@ Welcome to the Shakespeare Electron build documentation! This directory contains - Platform-specific problems ### Technical Reference +- **[ARCHITECTURE.md](ARCHITECTURE.md)** - System architecture and design + - Process architecture + - Shell execution flow + - Filesystem architecture + - Security boundaries + - Component integration + - Performance considerations - **[README.md](README.md)** - Complete technical documentation - File structure - Build configuration @@ -143,18 +168,23 @@ When updating the Electron build: ## 🌟 Features Current Electron features: +- ✅ **Real OS filesystem** - Projects stored at `~/shakespeare` +- ✅ **Real OS terminal** - Execute any system command - ✅ Platform detection - ✅ App version info - ✅ Secure IPC bridge - ✅ External link handling - ✅ Native window management +See [FEATURES.md](FEATURES.md) for detailed feature documentation. + Potential future features (see [README.md](README.md)): - Auto-updates - Native menus - System tray - File associations - Native dialogs +- Native Git CLI integration ## 📝 Contributing diff --git a/electron/README.md b/electron/README.md index d38e7f95..c1b5271f 100644 --- a/electron/README.md +++ b/electron/README.md @@ -2,7 +2,9 @@ This directory contains the Electron-specific files for building Shakespeare as a desktop application. -## Filesystem +## Key Features + +### Real OS Filesystem When running as an Electron app, Shakespeare uses your **local OS filesystem** at `~/shakespeare` instead of the browser's IndexedDB storage. This provides: @@ -13,6 +15,17 @@ When running as an Electron app, Shakespeare uses your **local OS filesystem** a See [FILESYSTEM.md](./FILESYSTEM.md) for complete details. +### Real Terminal + +The Electron version uses your **real OS terminal** instead of the virtual terminal in the browser. This means: + +- All OS commands available (not just built-in commands) +- Native shell features (pipes, redirection, etc.) +- Package managers work (`npm`, `yarn`, `pnpm`) +- Full access to system utilities and build tools + +See [REAL_TERMINAL.md](./REAL_TERMINAL.md) for complete details. + ## Structure ``` diff --git a/electron/REAL_TERMINAL.md b/electron/REAL_TERMINAL.md new file mode 100644 index 00000000..4d62ae9e --- /dev/null +++ b/electron/REAL_TERMINAL.md @@ -0,0 +1,196 @@ +# Real Terminal in Electron + +When Shakespeare runs in Electron, it automatically uses the **real OS terminal** instead of the virtual terminal used in the browser version. + +## How It Works + +### Architecture + +1. **Electron Main Process** (`electron/main.js`): + - Added `shell:exec` IPC handler that spawns real shell processes + - Uses `child_process.spawn()` to execute commands + - Automatically detects platform (Windows uses `cmd.exe`, Unix uses `/bin/sh`) + - All commands execute in the context of `~/shakespeare` directory + +2. **Preload Script** (`electron/preload.js`): + - Exposes `window.electron.shell.exec()` to renderer process + - Provides secure bridge between renderer and main process + +3. **TypeScript Definitions** (`electron/electron.d.ts`): + - Added `ElectronShellAPI` interface + - Defines `ShellExecResult` type with stdout, stderr, and exitCode + +4. **ShellTool** (`src/lib/tools/ShellTool.ts`): + - Detects if `window.electron.shell` is available + - If in Electron, bypasses virtual command system and uses real shell + - Falls back to virtual commands in browser mode + +5. **Terminal Component** (`src/components/Terminal.tsx`): + - Detects Electron environment + - Routes commands to real shell when available + - Shows "Real Terminal (OS Shell)" in welcome message + - Maintains command history and UI features in both modes + +## Features + +### Real Shell Execution +- **All OS commands available**: Not limited to Shakespeare's built-in commands +- **Native shell features**: Pipes, redirection, environment variables all work natively +- **Package managers**: Run `npm`, `yarn`, `pnpm`, etc. directly +- **Build tools**: Execute `vite`, `webpack`, `tsc`, etc. +- **Git operations**: Full Git CLI available +- **System utilities**: Access to all system commands (`grep`, `sed`, `awk`, etc.) + +### Working Directory +- Commands execute in the project directory: `~/shakespeare/{projectsPath}/{projectId}` +- The `projectsPath` is configurable (default: `projects`) +- Paths are automatically resolved relative to this directory +- Full access to the OS filesystem within the Shakespeare directory + +### Platform Support +- **macOS/Linux**: Uses `/bin/sh` for command execution +- **Windows**: Uses `cmd.exe` for command execution +- Commands are platform-aware and work naturally on each OS + +## Usage + +### In Browser Mode +```bash +# Limited to built-in commands +$ ls +$ cat file.txt +$ git status +``` + +### In Electron Mode +```bash +# All OS commands available +$ npm install +$ npm run build +$ python script.py +$ make +$ docker ps +$ curl https://api.example.com +$ any-other-command +``` + +## Security Considerations + +### Sandboxing +- Commands execute with the permissions of the Electron app +- Limited to the `~/shakespeare` directory by default +- No special elevation or sudo access + +### Command Execution +- Commands run through the platform's default shell +- Environment variables from the Electron process are inherited +- Standard input/output/error streams are captured + +## AI Integration + +The ShellTool used by AI assistants automatically uses real shell execution in Electron: + +```typescript +// AI can execute any OS command +await shellTool.execute({ + command: "npm install lodash" +}); + +await shellTool.execute({ + command: "git commit -m 'Update dependencies'" +}); +``` + +## Differences from Browser Mode + +| Feature | Browser Mode | Electron Mode | +|---------|-------------|---------------| +| Available Commands | Built-in only (~30 commands) | All OS commands | +| Shell Features | Simulated | Native | +| Package Managers | Not available | Full support | +| Build Tools | Limited | Full support | +| File System | Virtual (IndexedDB) | Real OS filesystem | +| Performance | JavaScript execution | Native shell | +| Platform Commands | Emulated | Native to OS | + +## Terminal UI Features + +Both modes share the same terminal UI features: +- Command history (up/down arrows) +- Output formatting with ANSI color support +- Copy to clipboard +- Auto-scroll +- Command execution state +- Error highlighting + +## Example Session + +```bash +$ pwd +/Users/username/shakespeare/projects/my-app + +$ npm install +added 142 packages, and audited 143 packages in 3s + +$ npm run build +> my-app@1.0.0 build +> vite build +✓ built in 1.2s + +$ git status +On branch main +Your branch is up to date with 'origin/main'. + +nothing to commit, working tree clean +``` + +## Troubleshooting + +### Commands Not Found +- Ensure the command is installed on your system +- Check your system's PATH environment variable +- Verify the command works in your regular terminal + +### Permission Errors +- Electron runs with your user's permissions +- Some commands may require additional permissions +- Use absolute paths if relative paths don't work + +### Platform-Specific Issues +- Windows: Some Unix commands may not be available (use Git Bash or WSL) +- macOS: Some commands may require Xcode Command Line Tools +- Linux: Ensure required packages are installed + +## Development + +To test real terminal execution: + +```bash +# Run Electron in development mode +npm run electron:dev + +# Open the terminal in a project +# Try executing real OS commands +``` + +The terminal will show "Real Terminal (OS Shell)" in the welcome message when running in Electron mode. + +### Testing the Shell API + +A test script is provided in `electron/test-terminal.js` to verify the shell execution works correctly: + +```bash +# Start Electron in development mode +npm run electron:dev + +# Open DevTools (View > Toggle Developer Tools) +# Copy and paste the contents of electron/test-terminal.js into the console +# The script will run 5 tests to verify shell execution +``` + +The test script verifies: +1. Basic echo command execution +2. File listing commands +3. Node.js version check +4. Error handling for non-existent commands +5. Working directory verification diff --git a/electron/TROUBLESHOOTING.md b/electron/TROUBLESHOOTING.md index ace00580..b28aecc3 100644 --- a/electron/TROUBLESHOOTING.md +++ b/electron/TROUBLESHOOTING.md @@ -268,6 +268,40 @@ If they're not: 2. Verify the link uses `target="_blank"` 3. Check console for errors +#### Shell Execution Error: "spawn /bin/sh ENOENT" + +**Problem:** Terminal or AI shell commands fail with error: +``` +Error: Error invoking remote method 'shell:exec': Error: Failed to execute command: spawn /bin/sh ENOENT +``` + +**Root Cause:** The working directory doesn't exist on the OS filesystem when the shell command is executed. + +**Solution:** +This should be fixed in the latest version. The `shell:exec` handler now automatically creates the working directory before spawning the shell process. + +**If the issue persists:** +1. Check the Electron console logs to see which directory is being used +2. Verify the directory path is correct (should be under `~/shakespeare/`) +3. Check filesystem permissions on the Shakespeare directory +4. Try manually creating the project directory: `mkdir -p ~/shakespeare/projects/{projectId}` + +**Debug Steps:** +1. Open DevTools in Electron (View → Toggle Developer Tools) +2. Look for console logs showing: + - `Shell exec in directory: ...` + - `Command: ...` +3. Check for any filesystem errors in the console +4. Verify the directory exists: `ls -la ~/shakespeare/projects/` + +**Workaround:** +If the issue continues, you can manually create the directory structure: +```bash +mkdir -p ~/shakespeare/projects +``` + +Then restart the Electron app. + ### Platform-Specific Issues #### macOS: "App is damaged and can't be opened" diff --git a/electron/electron.d.ts b/electron/electron.d.ts index b511c66e..8532e71b 100644 --- a/electron/electron.d.ts +++ b/electron/electron.d.ts @@ -43,6 +43,22 @@ interface ElectronFSAPI { symlink(target: string, path: string): Promise; } +interface ShellExecResult { + stdout: string; + stderr: string; + exitCode: number; +} + +interface ElectronShellAPI { + /** + * Execute a shell command on the host OS. + * @param command - The command to execute + * @param cwd - Working directory (relative to ~/shakespeare) + * @returns Promise with stdout, stderr, and exit code + */ + exec(command: string, cwd?: string): Promise; +} + interface ElectronAPI { /** * Flag indicating the app is running in Electron. @@ -67,6 +83,12 @@ interface ElectronAPI { * All paths are relative to ~/shakespeare directory. */ fs: ElectronFSAPI; + + /** + * Shell API for executing real shell commands on the host OS. + * All paths in commands are relative to ~/shakespeare directory. + */ + shell: ElectronShellAPI; } interface Window { diff --git a/electron/main.js b/electron/main.js index ae86b8c8..cbd491ec 100644 --- a/electron/main.js +++ b/electron/main.js @@ -1,4 +1,5 @@ import { app, BrowserWindow, ipcMain, shell } from 'electron'; +import { spawn } from 'child_process'; import path from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs/promises'; @@ -397,3 +398,64 @@ ipcMain.handle('fs:symlink', async (event, target, filePath) => { throw err; } }); + +// Shell execution handler +ipcMain.handle('shell:exec', async (event, command, cwd) => { + return new Promise(async (resolve, reject) => { + try { + // Determine the shell and command execution method based on platform + const isWindows = process.platform === 'win32'; + const shellCmd = isWindows ? 'cmd.exe' : '/bin/sh'; + const shellArgs = isWindows ? ['/c', command] : ['-c', command]; + + // Resolve the working directory relative to Shakespeare root + const workingDir = cwd ? resolvePath(cwd) : SHAKESPEARE_ROOT; + + // Ensure the working directory exists before spawning + try { + await fs.mkdir(workingDir, { recursive: true }); + console.log(`Shell exec in directory: ${workingDir}`); + console.log(`Command: ${command}`); + } catch (mkdirError) { + console.warn(`Failed to create directory ${workingDir}:`, mkdirError.message); + // Continue anyway - directory might already exist + } + + const child = spawn(shellCmd, shellArgs, { + cwd: workingDir, + env: { ...process.env }, + shell: false, // We're already using the shell + }); + + let stdout = ''; + let stderr = ''; + + child.stdout?.on('data', (data) => { + stdout += data.toString(); + }); + + child.stderr?.on('data', (data) => { + stderr += data.toString(); + }); + + child.on('error', (error) => { + console.error('Shell execution error:', error); + console.error('Working directory:', workingDir); + console.error('Shell command:', shellCmd); + console.error('Shell args:', shellArgs); + reject(new Error(`Failed to execute command: ${error.message} (cwd: ${workingDir})`)); + }); + + child.on('close', (code) => { + resolve({ + stdout, + stderr, + exitCode: code ?? 0, + }); + }); + } catch (error) { + console.error('Shell setup error:', error); + reject(new Error(`Failed to setup shell execution: ${error.message}`)); + } + }); +}); diff --git a/electron/preload.js b/electron/preload.js index b13416a3..0178d2dd 100644 --- a/electron/preload.js +++ b/electron/preload.js @@ -26,4 +26,9 @@ contextBridge.exposeInMainWorld('electron', { readlink: (path) => ipcRenderer.invoke('fs:readlink', path), symlink: (target, path) => ipcRenderer.invoke('fs:symlink', target, path), }, + + // Shell API - execute real shell commands + shell: { + exec: (command, cwd) => ipcRenderer.invoke('shell:exec', command, cwd), + }, }); diff --git a/electron/test-terminal.js b/electron/test-terminal.js new file mode 100644 index 00000000..e52b3725 --- /dev/null +++ b/electron/test-terminal.js @@ -0,0 +1,84 @@ +/** + * Test script to verify real terminal execution in Electron + * + * This script can be run in the Electron console to test the shell execution: + * + * 1. Start Electron: npm run electron:dev + * 2. Open DevTools + * 3. Copy and paste this code into the console + */ + +async function testElectronShell() { + console.log('Testing Electron Shell Execution...\n'); + + if (!window.electron?.shell) { + console.error('❌ Not running in Electron or shell API not available'); + return; + } + + console.log('✅ Electron shell API detected\n'); + + // Test 1: Simple echo command + console.log('Test 1: Echo command'); + try { + const result1 = await window.electron.shell.exec('echo "Hello from real shell!"'); + console.log('stdout:', result1.stdout); + console.log('stderr:', result1.stderr); + console.log('exitCode:', result1.exitCode); + console.log(result1.exitCode === 0 ? '✅ PASS\n' : '❌ FAIL\n'); + } catch (error) { + console.error('❌ FAIL:', error.message, '\n'); + } + + // Test 2: List files + console.log('Test 2: List files'); + try { + const listCmd = process.platform === 'win32' ? 'dir' : 'ls -la'; + const result2 = await window.electron.shell.exec(listCmd); + console.log('stdout:', result2.stdout.substring(0, 200) + '...'); + console.log('exitCode:', result2.exitCode); + console.log(result2.exitCode === 0 ? '✅ PASS\n' : '❌ FAIL\n'); + } catch (error) { + console.error('❌ FAIL:', error.message, '\n'); + } + + // Test 3: Check Node.js version + console.log('Test 3: Node.js version'); + try { + const result3 = await window.electron.shell.exec('node --version'); + console.log('stdout:', result3.stdout); + console.log('exitCode:', result3.exitCode); + console.log(result3.exitCode === 0 ? '✅ PASS\n' : '❌ FAIL\n'); + } catch (error) { + console.error('❌ FAIL:', error.message, '\n'); + } + + // Test 4: Error handling (non-existent command) + console.log('Test 4: Non-existent command'); + try { + const result4 = await window.electron.shell.exec('this-command-does-not-exist'); + console.log('stdout:', result4.stdout); + console.log('stderr:', result4.stderr); + console.log('exitCode:', result4.exitCode); + console.log(result4.exitCode !== 0 ? '✅ PASS (expected failure)\n' : '❌ FAIL\n'); + } catch (error) { + console.log('✅ PASS (error caught as expected)\n'); + } + + // Test 5: Working directory + console.log('Test 5: Working directory'); + try { + const pwdCmd = process.platform === 'win32' ? 'cd' : 'pwd'; + const result5 = await window.electron.shell.exec(pwdCmd); + console.log('stdout:', result5.stdout); + console.log('Should contain "shakespeare":', result5.stdout.includes('shakespeare')); + console.log(result5.stdout.includes('shakespeare') ? '✅ PASS\n' : '❌ FAIL\n'); + } catch (error) { + console.error('❌ FAIL:', error.message, '\n'); + } + + console.log('All tests completed!'); +} + +// Run the tests +testElectronShell(); diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 23b46ecf..77da01a8 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -154,7 +154,7 @@ export const ChatPane = forwardRef(({ 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(), }; diff --git a/src/components/Terminal.tsx b/src/components/Terminal.tsx index 8e38b884..f6de3bda 100644 --- a/src/components/Terminal.tsx +++ b/src/components/Terminal.tsx @@ -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 ' 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 ' 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(); diff --git a/src/lib/ansiToHtml.test.ts b/src/lib/ansiToHtml.test.ts new file mode 100644 index 00000000..c6cc9af5 --- /dev/null +++ b/src/lib/ansiToHtml.test.ts @@ -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'); + }); +}); diff --git a/src/lib/ansiToHtml.ts b/src/lib/ansiToHtml.ts index 3b2fc55a..45638ed9 100644 --- a/src/lib/ansiToHtml.ts +++ b/src/lib/ansiToHtml.ts @@ -49,15 +49,15 @@ const styleMap: Record = { 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, ''); } \ No newline at end of file diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index f51e6aca..f286fd43 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -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 { private cwd: string; private git: Git; private commands: Map; + 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 { ), }); - 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 { 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 { return this.executeCompoundCommands(commands); } + /** + * Execute command using real shell in Electron + */ + private async executeRealShell(commandStr: string): Promise { + 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) */