mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Use OS shell for ShellTool on Electron
This commit is contained in:
17 files changed
+1334
-32
No files matched your search
@@ -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<string>;
|
||||
version(): Promise<string>;
|
||||
|
||||
// Filesystem API
|
||||
fs: {
|
||||
readFile(path: string, encoding?: string): Promise<string | number[]>;
|
||||
writeFile(path: string, data: string | number[], encoding?: string): Promise<void>;
|
||||
readdir(path: string, withFileTypes?: boolean): Promise<string[] | DirectoryEntry[]>;
|
||||
mkdir(path: string, recursive?: boolean): Promise<void>;
|
||||
stat(path: string): Promise<StatResult>;
|
||||
lstat(path: string): Promise<StatResult>;
|
||||
unlink(path: string): Promise<void>;
|
||||
rmdir(path: string): Promise<void>;
|
||||
rename(oldPath: string, newPath: string): Promise<void>;
|
||||
readlink(path: string): Promise<string>;
|
||||
symlink(target: string, path: string): Promise<void>;
|
||||
};
|
||||
|
||||
// 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<string> {
|
||||
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)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
|
||||
+14
-1
@@ -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
|
||||
|
||||
```
|
||||
|
||||
@@ -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
|
||||
> [email protected] 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
|
||||
@@ -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"
|
||||
|
||||
Vendored
+22
@@ -43,6 +43,22 @@ interface ElectronFSAPI {
|
||||
symlink(target: string, path: string): Promise<void>;
|
||||
}
|
||||
|
||||
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<ShellExecResult>;
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -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}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
},
|
||||
});
|
||||
@@ -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();
|
||||
Reference in new issue
Block a user