Merge branch 'electron' into 'main'

Electron

See merge request soapbox-pub/shakespeare!68
This commit is contained in:
Alex Gleason committed 2025-10-29 22:35:22 +00:00
commit 695b56c3cb
27 files changed
+5954 -47

No files matched your search

+3
View File
@@ -15,6 +15,9 @@ dist-ssr
*.apk
*.aab
# Electron build output
electron-dist
# Editor directories and files
.idea
.DS_Store
+12 -1
View File
@@ -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:
+27
View File
@@ -12,6 +12,7 @@ https://shakespeare.diy
- **Buy credits anonymously** with Nostr and Lightning ⚡
- **Redeem gift cards** with shareable links for instant credits
- **Runs entirely in the browser** No backend required
- **Desktop app available** Run as a native Electron application on macOS, Windows, and Linux
## How it Works
@@ -29,6 +30,32 @@ Shakespeare can work on any type of project. But it is specialized to build Reac
Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The purpose of Shakespeare is to provide a free and open platform for building AI applications that respects user privacy and freedom.
## Desktop App
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
- **Offline-first experience**
- **Better performance** for intensive operations
- **Platform-specific installers** (DMG, NSIS, AppImage, etc.)
### Quick Start
**Development Mode:**
```bash
npm run electron:dev
```
**Build for Your Platform:**
```bash
npm run electron:build
```
For detailed instructions, see [electron/QUICKSTART.md](electron/QUICKSTART.md).
## Mirrors
Shakespeare is available on the following URLs:
+582
View File
@@ -0,0 +1,582 @@
# Shakespeare Electron - Complete Guide
This guide provides comprehensive documentation for developing, building, and troubleshooting the Shakespeare Electron desktop application.
## Table of Contents
1. [Filesystem Architecture](#filesystem-architecture)
2. [Terminal Integration](#terminal-integration)
3. [Development Workflow](#development-workflow)
4. [Building for Distribution](#building-for-distribution)
5. [Troubleshooting](#troubleshooting)
---
## Filesystem Architecture
### Overview
The Electron version uses your local OS filesystem at `~/shakespeare` instead of IndexedDB, providing direct file access and unlimited storage.
### Path Resolution
All paths are relative to `~/shakespeare`:
- `/projects/my-app/` → `~/shakespeare/projects/my-app/`
- `/tmp/upload.txt` → `~/shakespeare/tmp/upload.txt`
- `/config/ai.json` → `~/shakespeare/config/ai.json`
### Implementation
**Automatic Adapter Selection** (`src/App.tsx`):
```typescript
const fs = window.electron?.isElectron
? new NodeFSAdapter() // Real filesystem
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
```
**IPC Communication Flow:**
1. **Renderer** (`NodeFSAdapter.ts`) - Calls `window.electron.fs.*` methods
2. **Preload** (`preload.js`) - Exposes API via `contextBridge`
3. **Main** (`main.js`) - Handles IPC with `ipcMain.handle()`, performs filesystem operations
### Supported Operations
All standard filesystem operations are supported:
- **Files**: `readFile`, `writeFile`, `unlink`, `rename`
- **Directories**: `readdir`, `mkdir`, `rmdir`
- **Metadata**: `stat`, `lstat`
- **Symlinks**: `readlink`, `symlink`
### Benefits
✅ **No storage limits** - Only limited by disk space
✅ **Direct access** - Use any editor, file manager, or Git client
✅ **Easy backup** - Standard backup tools work
✅ **Better performance** - Faster for large projects
✅ **Data portability** - Copy projects between machines
### Data Migration
**Browser to Electron:**
1. Export project as ZIP from browser
2. Import ZIP in Electron version
**Electron to Browser:**
1. Export project as ZIP from Electron
2. Import ZIP in browser version
---
## Terminal Integration
### Overview
The Electron version uses the **real OS terminal** instead of the virtual terminal, providing access to all system commands.
### Architecture
**ShellTool Detection** (`src/lib/tools/ShellTool.ts`):
```typescript
if (window.electron?.shell) {
// Use real OS shell
const result = await window.electron.shell.exec(command, workingDir);
} else {
// Use virtual command system
const result = await executeCommand(command, workingDir, fs);
}
```
**Shell Execution** (`electron/main.js`):
- Uses `child_process.spawn()` to execute commands
- Windows: Uses `cmd.exe`
- macOS/Linux: Uses `/bin/sh`
- Executes in project directory: `~/shakespeare/projects/{projectId}`
### Features
**All OS Commands Available:**
```bash
# Package managers
$ npm install
$ yarn add lodash
$ pnpm update
# Build tools
$ vite build
$ webpack --config webpack.config.js
$ tsc --noEmit
# Git operations
$ git commit -m "Update"
$ git push origin main
# System utilities
$ grep -r "TODO" src/
$ curl https://api.example.com
$ python script.py
```
**Native Shell Features:**
- Pipes: `ls | grep ".ts$"`
- Redirection: `echo "test" > file.txt`
- Environment variables: `$PATH`, `$HOME`
- Command chaining: `npm install && npm run build`
### ANSI Code Stripping
Output from shell commands is cleaned for AI consumption:
- Color codes removed (e.g., `\u001b[31m`)
- Cursor control sequences stripped
- Text formatting removed (bold, italic)
- Newlines preserved
**Example:**
```
Input: \u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s
Output: added 142 packages in 3s
```
Terminal UI still shows colored output for users.
### Platform Support
| Platform | Shell | Notes |
|----------|-------|-------|
| macOS | `/bin/sh` | All Unix commands available |
| Linux | `/bin/sh` | Standard Linux utilities |
| Windows | `cmd.exe` | Windows commands, consider Git Bash for Unix tools |
### Security
- Commands run with user permissions (no sudo/elevation)
- Working directory sandboxed to `~/shakespeare`
- Environment variables inherited from Electron process
---
## Development Workflow
### Running in Development Mode
```bash
npm run electron:dev
```
This will:
1. Start Vite dev server on http://localhost:5173
2. Wait for server to be ready
3. Launch Electron with hot reload
4. Open DevTools automatically
### Testing Shell Execution
Use the provided test script to verify shell functionality:
```bash
# Start Electron in dev mode
npm run electron:dev
# Open DevTools (View > Toggle Developer Tools)
# Paste contents of electron/test-terminal.js into console
```
The test script verifies:
- Basic command execution
- File listing
- Node.js version check
- Error handling
- Working directory
### Debugging
**Renderer Process:**
- DevTools open automatically in dev mode
- Or press `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux)
**Main Process:**
```bash
# Enable verbose logging
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
```
**Check Configuration:**
```bash
node electron/test-config.js
```
### File Watching
In development mode:
- Vite provides hot module replacement
- Changes to React components reload instantly
- Electron process restarts on main.js changes (via `nodemon` in the script)
---
## Building for Distribution
### Prerequisites
- Node.js 18+ installed
- All dependencies installed: `npm install`
- Web build completed: `npm run build`
### Build Commands
**Current Platform:**
```bash
npm run electron:build
```
**Specific Platforms:**
```bash
npm run electron:build:mac # macOS (DMG + ZIP)
npm run electron:build:win # Windows (NSIS + Portable)
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
npm run electron:build:all # All platforms
```
### Build Output
```
electron-dist/
├── mac/
│ ├── Shakespeare.app # macOS application bundle
│ ├── Shakespeare.dmg # DMG installer
│ └── Shakespeare-mac.zip # ZIP archive
├── win-unpacked/
│ └── Shakespeare.exe # Windows executable
├── Shakespeare Setup.exe # NSIS installer
├── Shakespeare Portable.exe # Portable executable
├── shakespeare-*.AppImage # Linux AppImage
├── shakespeare_*.deb # Debian package
└── shakespeare-*.rpm # RPM package
```
### Platform-Specific Notes
**macOS:**
- Builds for Intel (x64) and Apple Silicon (arm64)
- Code signing optional for development
- For distribution: Requires Apple Developer account
**Windows:**
- Builds for x64 and ARM64
- No code signing required for development
- For distribution: EV certificate recommended for SmartScreen
**Linux:**
- Builds for x64 and ARM64
- AppImage requires FUSE: `sudo apt-get install fuse`
- DEB/RPM packages can be installed with package managers
### Cross-Platform Limitations
- **macOS builds require macOS** (for code signing)
- Windows/Linux can be built from any platform
- Use GitHub Actions or CI/CD for multi-platform builds
### Code Signing
**Development (Disable Signing):**
Edit `electron/builder.config.js`:
```javascript
mac: {
identity: null, // Disable code signing
}
```
**Production (macOS):**
1. Obtain Apple Developer account
2. Create certificates in Xcode
3. Configure signing in builder.config.js
4. See: https://www.electron.build/code-signing
**Production (Windows):**
1. Obtain EV code signing certificate
2. Configure in builder.config.js
3. Builds reputation with SmartScreen over time
---
## Troubleshooting
### Development Issues
#### Port 5173 Already in Use
**Solution:**
```bash
# Find and kill the process
lsof -i :5173 # macOS/Linux
netstat -ano | findstr :5173 # Windows
# Or change the port in vite.config.ts
export default defineConfig({
server: { port: 5174 },
});
```
#### Blank Screen on Launch
**Browser Mode:**
1. Check Vite server is running: http://localhost:5173
2. Check Electron console for errors
3. Verify URL in `electron/main.js` matches Vite server
4. Clear cache: Delete `node_modules/.vite`
**Production Build:**
1. Ensure `base: './'` is set in `vite.config.ts`
2. Check `dist/` directory contains all files
3. Look for "Failed to load resource" errors in console
4. Verify file:// protocol is used in loadURL
#### Assets Fail to Load: "net::ERR_FILE_NOT_FOUND"
**Problem:** CSS/JS fail to load with `file:///assets/npm/...` errors
**Solution:** Add to `vite.config.ts`:
```typescript
export default defineConfig(() => ({
base: './', // Required for Electron
// ... rest of config
}))
```
Then rebuild: `npm run build`
#### 404 Error: Page Not Found
**Problem:** App shows "404: Oops! Page not found" on launch
**Solution:** Verify `HashRouter` is used in Electron.
Check `src/AppRouter.tsx`:
```typescript
const Router = window.electron?.isElectron ? HashRouter : BrowserRouter;
```
Rebuild: `npm run build && npm run electron:build`
#### Service Worker Errors
**Solution:** Service workers don't work with `file://` protocol.
Check `src/main.tsx`:
```typescript
if ('serviceWorker' in navigator && !window.electron?.isElectron) {
// Only register in web environment
}
```
#### CSP Font Errors
**Solution:** Update CSP in `index.html`:
```html
<meta http-equiv="content-security-policy"
content="... font-src 'self' data:; ...">
```
#### Broken SVG Images
**Problem:** Logo/SVG files show as broken
**Solution:** Import SVG files properly:
```typescript
// ❌ Wrong
<img src="/shakespeare.svg" alt="Logo" />
// ✅ Correct
import logo from '/shakespeare.svg?url';
<img src={logo} alt="Logo" />
```
#### Preload Script ESM Errors
**Solution:** Requires `sandbox: false` in webPreferences.
Check `electron/main.js`:
```javascript
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true, // Still enabled
sandbox: false, // Disabled for ESM
webSecurity: true,
}
```
### Build Issues
#### Build Fails with "Cannot find module"
**Solutions:**
1. Install dependencies: `npm install`
2. Clear and reinstall: `rm -rf node_modules package-lock.json && npm install`
3. Build web first: `npm run build`
4. Verify `dist/` exists
5. Check config: `node electron/test-config.js`
#### Icons Not Appearing
**Solution:** Should work automatically with `public/shakespeare-512x512.png`.
If not:
1. Verify PNG exists
2. Check build output for icon errors
3. Try: `npm run electron:icons` (requires ImageMagick)
4. Check paths in `electron/builder.config.js`
#### Code Signing Errors (macOS)
**Development:** Disable signing:
```javascript
mac: {
identity: null,
}
```
**Production:** Requires Apple Developer account and certificates.
#### App Won't Launch After Build
**Solutions:**
1. Check console/terminal for errors
2. Try unpacked version first
3. macOS: Check Security & Privacy settings
4. Windows: Check Windows Defender logs
5. Verify `dist/` contains valid files
### Runtime Issues
#### App Crashes on Startup
**Solutions:**
1. Check crash logs:
- macOS: `~/Library/Logs/Shakespeare/`
- Windows: `%APPDATA%\Shakespeare\logs\`
- Linux: `~/.config/Shakespeare/logs/`
2. Run from terminal to see errors
3. Test web build in browser first
#### Shell Execution Error: "spawn /bin/sh ENOENT"
**Problem:** Terminal commands fail with spawn error
**Root Cause:** Working directory doesn't exist
**Solution:** Should be fixed - main.js creates directories automatically.
**Debug:**
1. Open DevTools
2. Check console for "Shell exec in directory: ..."
3. Verify directory exists: `ls -la ~/shakespeare/projects/`
4. Manually create if needed: `mkdir -p ~/shakespeare/projects`
#### External Links Not Opening
**Solution:** Should open in default browser automatically.
Check `electron/main.js` has:
```javascript
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
```
### Platform-Specific Issues
#### macOS: "App is damaged and can't be opened"
**Solutions:**
1. Development: `xattr -cr /path/to/Shakespeare.app`
2. Distribution: Requires code signing
3. Users: Right-click → Open (instead of double-click)
#### Windows: "Windows protected your PC"
**Solutions:**
1. Testing: Click "More info" → "Run anyway"
2. Distribution: Requires EV code signing
3. Build reputation over time
#### Linux: "Permission denied"
**Solutions:**
1. Make executable: `chmod +x Shakespeare*.AppImage`
2. Install FUSE: `sudo apt-get install fuse`
3. Try DEB/RPM package instead
### Performance Issues
#### App Feels Slow
**Solutions:**
1. Close DevTools
2. Check system resources
3. Use production build
4. Disable hardware acceleration in `main.js`:
```javascript
app.disableHardwareAcceleration();
```
#### High Memory Usage
**Solutions:**
1. Normal for Chromium-based apps
2. Close unused projects
3. Restart app periodically
4. Check for memory leaks in web code
---
## Getting Help
If issues persist:
1. **Check existing issues:** https://gitlab.com/soapbox-pub/shakespeare/-/issues
2. **Create new issue** with:
- OS and version
- Electron version: `npm list electron`
- Steps to reproduce
- Error messages/logs
- Screenshots
3. **Community support:** Check project README for links
## Useful Commands
**Complete rebuild:**
```bash
rm -rf node_modules dist electron-dist package-lock.json
npm install
npm run build
npm run electron:build
```
**Check versions:**
```bash
npm list electron
node --version
npm --version
```
**Verbose logging:**
```bash
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
```
**Check build contents:**
```bash
npm run electron:build -- --dir
ls -la electron-dist/[platform]-unpacked/
```
## Additional Resources
- [Electron Documentation](https://www.electronjs.org/docs)
- [electron-builder Documentation](https://www.electron.build/)
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security)
- [Debugging Electron](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process)
- [Shakespeare Main Docs](../README.md)
+195
View File
@@ -0,0 +1,195 @@
# Shakespeare Electron Desktop App
Shakespeare can run as a native desktop application on macOS, Windows, and Linux using Electron. The desktop version provides enhanced features over the browser version, including real OS filesystem access and native terminal execution.
## Quick Start
### Development Mode
```bash
npm run electron:dev
```
### Build for Distribution
```bash
# Build for your current platform
npm run electron:build
# Build for specific platforms
npm run electron:build:mac # macOS (DMG + ZIP)
npm run electron:build:win # Windows (NSIS + Portable)
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
npm run electron:build:all # All platforms
```
Built applications will be in the `electron-dist/` directory.
## Key Features
### 1. Real OS Filesystem
Projects are stored at `~/shakespeare` on your local filesystem instead of browser IndexedDB:
- **No storage limits** - Only limited by disk space
- **Direct file access** - Use any code editor, file manager, or Git client
- **Easy backup** - Standard filesystem backup tools work
- **Better performance** - Faster for large projects
**Directory Structure:**
```
~/shakespeare/
├── projects/ # Your Shakespeare projects
├── config/ # AI and Git settings
└── tmp/ # Temporary files
```
**Opening the directory:**
- macOS: `open ~/shakespeare`
- Linux: `xdg-open ~/shakespeare`
- Windows: `explorer %USERPROFILE%\shakespeare`
### 2. Real OS Terminal
All OS commands are available, not just built-in commands:
- **Package managers**: `npm`, `yarn`, `pnpm` work directly
- **Build tools**: `vite`, `webpack`, `tsc`, etc.
- **Git CLI**: Full Git command-line interface
- **Native shell features**: Pipes, redirection, environment variables
- **System utilities**: All your favorite command-line tools
Commands execute in the project directory at `~/shakespeare/projects/{projectId}` with your user's permissions.
### 3. Clean UI
- **No menu bar** - Frameless interface focused on Shakespeare
- **Native window controls** - Standard minimize/maximize/close buttons
- **Auto-updates ready** - Can be configured for automatic updates
## Project Structure
```
electron/
├── main.js # Main process (window management, IPC)
├── preload.js # Secure IPC bridge
├── builder.config.js # Build configuration
├── resources/ # Icons and build assets
├── test-config.js # Configuration validator
├── test-terminal.js # Terminal testing script
├── generate-icons.sh # Icon generation script
├── README.md # This file
└── GUIDE.md # Detailed guide and troubleshooting
```
## Icons
No icon setup required! The build automatically uses `public/shakespeare-512x512.png` and converts it for each platform:
- **macOS**: Converts to `.icns`
- **Windows**: Converts to `.ico`
- **Linux**: Uses PNG directly
For custom icons, run `npm run electron:icons` (requires ImageMagick) or place platform-specific icons in `electron/resources/`.
## Platform-Specific Builds
### macOS
- Creates DMG installer and ZIP archive
- Builds for both Intel (x64) and Apple Silicon (arm64)
- Requires macOS for code signing (optional for development)
### Windows
- Creates NSIS installer and portable executable
- Builds for both x64 and ARM64
- No code signing required for development
### Linux
- Creates AppImage, DEB, and RPM packages
- Builds for both x64 and ARM64
- Works from any platform
## Security
The Electron build follows security best practices:
- **Context Isolation**: Enabled to prevent renderer access to Node.js
- **Web Security**: Enforces same-origin policy
- **Navigation Protection**: Blocks navigation to external sites
- **Minimal IPC API**: Only essential functionality exposed
- **Sandboxed Execution**: Commands run with user permissions
## API Exposed to Renderer
The preload script exposes a minimal API via `window.electron`:
```typescript
window.electron.isElectron // Boolean: true in Electron
window.electron.platform() // Returns: 'darwin' | 'win32' | 'linux'
window.electron.version() // Returns app version
window.electron.fs.* // Filesystem operations
window.electron.shell.exec() // Execute shell commands
```
## Customization
### Window Configuration
Edit `electron/main.js` to customize:
- Window size and position
- Minimum/maximum dimensions
- Background color
- Title bar style
### Build Settings
Edit `electron/builder.config.js` to configure:
- App metadata (ID, name, category)
- Platform-specific options
- Installer settings
- Auto-update configuration
### Additional Features
Add to `electron/main.js` and `electron/preload.js`:
- Native menus
- System tray icon
- File associations
- Custom URL schemes
- Native dialogs
## Development vs Production
**Development Mode** (`npm run electron:dev`):
- Loads from Vite dev server (http://localhost:5173)
- Hot reload enabled
- DevTools open automatically
- Faster iteration
**Production Build** (`npm run electron:build`):
- Loads from built files (file:// protocol)
- Optimized and minified
- No DevTools by default
- Ready for distribution
## Common Issues
See [GUIDE.md](./GUIDE.md) for detailed troubleshooting, including:
- Port conflicts
- Blank screen issues
- Asset loading errors
- Build failures
- Platform-specific problems
## Next Steps
1. **Try it out**: Run `npm run electron:dev` to test locally
2. **Build it**: Create a distributable with `npm run electron:build`
3. **Customize**: Modify window settings, add native features
4. **Distribute**: Set up code signing and auto-updates for production
## Resources
- [Electron Documentation](https://www.electronjs.org/docs)
- [electron-builder Documentation](https://www.electron.build/)
- [Shakespeare Main Documentation](../README.md)
- [Detailed Guide](./GUIDE.md)
---
**Note:** For comprehensive documentation including filesystem details, terminal usage, and troubleshooting, see [GUIDE.md](./GUIDE.md).
+106
View File
@@ -0,0 +1,106 @@
export default {
appId: 'pub.soapbox.shakespeare',
productName: 'Shakespeare',
directories: {
output: 'electron-dist',
buildResources: 'electron/resources',
},
files: [
'dist/**/*',
'electron/main.js',
'electron/preload.js',
'public/shakespeare-512x512.png',
'public/shakespeare.svg',
],
extraMetadata: {
main: 'electron/main.js',
},
// macOS configuration
mac: {
category: 'public.app-category.developer-tools',
icon: 'public/shakespeare-512x512.png', // Will be converted automatically
target: [
{
target: 'dmg',
arch: ['x64', 'arm64'],
},
{
target: 'zip',
arch: ['x64', 'arm64'],
},
],
darkModeSupport: true,
},
dmg: {
contents: [
{
x: 130,
y: 220,
},
{
x: 410,
y: 220,
type: 'link',
path: '/Applications',
},
],
window: {
width: 540,
height: 380,
},
},
// Windows configuration
win: {
icon: 'public/shakespeare-512x512.png', // Will be converted automatically
target: [
{
target: 'nsis',
arch: ['x64', 'arm64'],
},
{
target: 'portable',
arch: ['x64', 'arm64'],
},
],
},
nsis: {
oneClick: false,
allowToChangeInstallationDirectory: true,
createDesktopShortcut: true,
createStartMenuShortcut: true,
},
// Linux configuration
linux: {
icon: 'public/shakespeare-512x512.png',
category: 'Development',
target: [
{
target: 'AppImage',
arch: ['x64', 'arm64'],
},
{
target: 'deb',
arch: ['x64', 'arm64'],
},
{
target: 'rpm',
arch: ['x64', 'arm64'],
},
],
},
appImage: {
license: 'LICENSE',
},
// Publish configuration (optional - for auto-updates)
publish: null,
};
+94
View File
@@ -0,0 +1,94 @@
/**
* TypeScript definitions for the Electron API exposed to the renderer process.
*
* Add this to your tsconfig.json include array to use these types:
* "include": ["src", "electron/electron.d.ts"]
*/
interface DirectoryEntry {
name: string;
isDirectory: boolean;
isFile: boolean;
}
interface StatResult {
isDirectory: boolean;
isFile: boolean;
isBlockDevice: boolean;
isCharacterDevice: boolean;
isSymbolicLink: boolean;
isFIFO: boolean;
isSocket: boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
// Timestamps (serialized as numbers for IPC)
mtime: number;
ctime: number;
atime: number;
}
interface ElectronFSAPI {
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>;
}
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 {
/**
* Get the current platform.
* @returns 'darwin' | 'win32' | 'linux'
*/
platform(): Promise<string>;
/**
* Get the application version from package.json.
* @returns Version string (e.g., "1.0.0")
*/
version(): Promise<string>;
/**
* Filesystem API for accessing the local OS filesystem.
* 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 {
/**
* Electron API exposed via preload script.
* Only available when running in Electron.
*/
electron?: ElectronAPI;
}
+92
View File
@@ -0,0 +1,92 @@
#!/bin/bash
# Script to generate Electron icons from the Shakespeare logo
# Requires ImageMagick to be installed: brew install imagemagick (macOS) or apt-get install imagemagick (Linux)
set -e
echo "🎭 Generating Electron icons for Shakespeare..."
# Check if ImageMagick is installed
if ! command -v convert &> /dev/null; then
echo "❌ ImageMagick is not installed."
echo ""
echo "Please install ImageMagick:"
echo " macOS: brew install imagemagick"
echo " Ubuntu: sudo apt-get install imagemagick"
echo " Windows: Download from https://imagemagick.org/script/download.php"
echo ""
echo "Alternatively, use an online tool or electron-icon-builder:"
echo " npm install -g electron-icon-builder"
echo " electron-icon-builder --input=public/shakespeare-512x512.png --output=electron/resources"
exit 1
fi
# Source image
SOURCE="public/shakespeare-512x512.png"
if [ ! -f "$SOURCE" ]; then
echo "❌ Source image not found: $SOURCE"
exit 1
fi
# Create resources directory if it doesn't exist
mkdir -p electron/resources/icons
echo "📦 Generating macOS icon (icon.icns)..."
# Create iconset directory
mkdir -p electron/resources/icon.iconset
# Generate different sizes for macOS
convert "$SOURCE" -resize 16x16 electron/resources/icon.iconset/icon_16x16.png
convert "$SOURCE" -resize 32x32 electron/resources/icon.iconset/[email protected]
convert "$SOURCE" -resize 32x32 electron/resources/icon.iconset/icon_32x32.png
convert "$SOURCE" -resize 64x64 electron/resources/icon.iconset/[email protected]
convert "$SOURCE" -resize 128x128 electron/resources/icon.iconset/icon_128x128.png
convert "$SOURCE" -resize 256x256 electron/resources/icon.iconset/[email protected]
convert "$SOURCE" -resize 256x256 electron/resources/icon.iconset/icon_256x256.png
convert "$SOURCE" -resize 512x512 electron/resources/icon.iconset/[email protected]
convert "$SOURCE" -resize 512x512 electron/resources/icon.iconset/icon_512x512.png
convert "$SOURCE" -resize 1024x1024 electron/resources/icon.iconset/[email protected]
# Convert to icns (macOS only)
if command -v iconutil &> /dev/null; then
iconutil -c icns electron/resources/icon.iconset -o electron/resources/icon.icns
echo "✅ Created icon.icns"
else
echo "⚠️ iconutil not found (macOS only). Skipping .icns generation."
echo " You can use an online converter or run this on macOS."
fi
# Clean up iconset
rm -rf electron/resources/icon.iconset
echo "📦 Generating Windows icon (icon.ico)..."
# Generate ico file with multiple sizes
convert "$SOURCE" -resize 256x256 \
\( -clone 0 -resize 16x16 \) \
\( -clone 0 -resize 32x32 \) \
\( -clone 0 -resize 48x48 \) \
\( -clone 0 -resize 64x64 \) \
\( -clone 0 -resize 128x128 \) \
\( -clone 0 -resize 256x256 \) \
-delete 0 electron/resources/icon.ico
echo "✅ Created icon.ico"
echo "📦 Generating Linux icons (PNG)..."
# Generate PNG icons for Linux
for size in 16 32 48 64 128 256 512 1024; do
convert "$SOURCE" -resize ${size}x${size} electron/resources/icons/${size}x${size}.png
done
echo "✅ Created Linux PNG icons"
echo ""
echo "✨ Icon generation complete!"
echo ""
echo "Generated files:"
echo " - electron/resources/icon.icns (macOS)"
echo " - electron/resources/icon.ico (Windows)"
echo " - electron/resources/icons/*.png (Linux)"
echo ""
echo "You can now build Electron apps with:"
echo " npm run electron:build"
+522
View File
@@ -0,0 +1,522 @@
import { app, BrowserWindow, ipcMain, shell, Menu, protocol } from 'electron';
import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import os from 'os';
// ESM equivalent of __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let mainWindow;
function createWindow() {
// Remove the default menu (File, Edit, View, etc.)
Menu.setApplicationMenu(null);
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Disabled to support ESM in preload
webSecurity: true,
},
icon: path.join(__dirname, '../public/shakespeare-512x512.png'),
title: 'Shakespeare',
backgroundColor: '#ffffff',
});
// Enable DevTools keyboard shortcut (Ctrl+Shift+I / Cmd+Option+I)
mainWindow.webContents.on('before-input-event', (event, input) => {
// Check for Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac)
if (input.control && input.shift && input.key.toLowerCase() === 'i') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
// Also support F12
if (input.key === 'F12') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
});
// Load the app
if (process.env.ELECTRON_DEV) {
// Development mode - load from Vite dev server
console.log('Loading from Vite dev server: http://localhost:5173');
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
// Production mode - load from custom protocol
// This allows absolute paths like /shakespeare.svg to work naturally
console.log('Loading from app:// protocol: app://./index.html');
mainWindow.loadURL('app://./index.html');
}
// Log any load errors
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error('Failed to load:', validatedURL, errorCode, errorDescription);
});
// Log successful load
mainWindow.webContents.on('did-finish-load', () => {
console.log('Successfully loaded app');
});
// Handle window close
mainWindow.on('closed', () => {
mainWindow = null;
});
}
// Register custom protocol scheme before app is ready (required for privileges)
if (!process.env.ELECTRON_DEV) {
protocol.registerSchemesAsPrivileged([
{
scheme: 'app',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
},
},
]);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.whenReady().then(async () => {
// Register the app:// protocol to serve files from dist/
// This allows absolute paths (/) to work naturally without base: './'
if (!process.env.ELECTRON_DEV) {
protocol.registerFileProtocol('app', (request, callback) => {
// Remove 'app://' prefix and normalize path
let filePath = request.url.replace('app://', '');
// Remove trailing slashes
filePath = filePath.replace(/\/+$/, '');
// Handle root path
if (filePath === '' || filePath === '/') {
filePath = 'index.html';
}
// Remove leading slash if present
if (filePath.startsWith('/')) {
filePath = filePath.substring(1);
}
// Resolve to dist directory
const fullPath = path.join(__dirname, '../dist', filePath);
console.log('Protocol handler:', request.url, '->', fullPath);
callback({ path: fullPath });
});
}
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// Quit when all windows are closed, except on macOS.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Handle app-level events
app.on('web-contents-created', (event, contents) => {
// Security: Prevent navigation to external sites
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl);
// Allow navigation within the app
if (parsedUrl.origin === 'http://localhost:5173' ||
parsedUrl.protocol === 'file:') {
return;
}
// Block all other navigation
event.preventDefault();
});
// Security: Prevent opening new windows
contents.setWindowOpenHandler(({ url }) => {
// Open external links in the default browser
shell.openExternal(url);
return { action: 'deny' };
});
});
// IPC handlers can be added here if needed for future Electron-specific features
// For example: file system access, native dialogs, etc.
// Example: Handle getting app version
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});
// Example: Handle getting platform
ipcMain.handle('get-platform', () => {
return process.platform;
});
// Helper function to expand tilde (~) in paths
function expandTilde(filepath) {
if (filepath.startsWith('~/') || filepath === '~') {
return path.join(os.homedir(), filepath.slice(1));
}
return filepath;
}
// Filesystem IPC handlers
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
if (!filePath) {
const err = new Error('Failed to read file: path is required');
err.code = 'EINVAL';
throw err;
}
try {
const fullPath = expandTilde(filePath);
const data = await fs.readFile(fullPath, encoding ? { encoding } : undefined);
// If no encoding, convert Buffer to array for IPC serialization
return encoding ? data : Array.from(data);
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
// Serialize the error code as a regular property so it survives IPC
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
// Copy enumerable properties including code
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:writeFile', async (event, filePath, data, encoding) => {
if (!filePath) {
const err = new Error('Failed to write file: path is required');
err.code = 'EINVAL';
throw err;
}
try {
const fullPath = expandTilde(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(fullPath), { recursive: true });
// Convert array back to Buffer if needed
const dataToWrite = Array.isArray(data) ? Buffer.from(data) : data;
await fs.writeFile(fullPath, dataToWrite, encoding ? { encoding } : undefined);
} catch (error) {
const err = new Error(`Failed to write file ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
try {
const fullPath = expandTilde(dirPath);
const entries = await fs.readdir(fullPath, { withFileTypes: !!withFileTypes });
if (withFileTypes) {
// Convert Dirent objects to plain objects for IPC
return entries.map(entry => ({
name: entry.name,
isDirectory: entry.isDirectory(),
isFile: entry.isFile(),
}));
}
return entries;
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:mkdir', async (event, dirPath, recursive) => {
try {
const fullPath = expandTilde(dirPath);
await fs.mkdir(fullPath, { recursive: !!recursive });
} catch (error) {
const err = new Error(`Failed to create directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:stat', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
const stats = await fs.stat(fullPath);
const now = Date.now();
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(),
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs ?? now,
ctimeMs: stats.ctimeMs ?? now,
atimeMs: stats.atimeMs ?? now,
// Date objects need to be serialized as timestamps for IPC
// Use optional chaining and fallback to now to prevent valueOf errors
mtime: stats.mtime?.getTime() ?? now,
ctime: stats.ctime?.getTime() ?? now,
atime: stats.atime?.getTime() ?? now,
};
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:lstat', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
const stats = await fs.lstat(fullPath);
const now = Date.now();
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(),
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs ?? now,
ctimeMs: stats.ctimeMs ?? now,
atimeMs: stats.atimeMs ?? now,
// Date objects need to be serialized as timestamps for IPC
// Use optional chaining and fallback to now to prevent valueOf errors
mtime: stats.mtime?.getTime() ?? now,
ctime: stats.ctime?.getTime() ?? now,
atime: stats.atime?.getTime() ?? now,
};
} catch (error) {
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:unlink', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
await fs.unlink(fullPath);
} catch (error) {
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:rmdir', async (event, dirPath) => {
try {
const fullPath = expandTilde(dirPath);
await fs.rmdir(fullPath);
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to remove directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:rename', async (event, oldPath, newPath) => {
try {
const fullOldPath = expandTilde(oldPath);
const fullNewPath = expandTilde(newPath);
// Ensure parent directory of new path exists
await fs.mkdir(path.dirname(fullNewPath), { recursive: true });
await fs.rename(fullOldPath, fullNewPath);
} catch (error) {
const err = new Error(`Failed to rename ${oldPath} to ${newPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:readlink', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
return await fs.readlink(fullPath);
} catch (error) {
const err = new Error(`Failed to read link ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:symlink', async (event, target, filePath) => {
try {
const fullPath = expandTilde(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.symlink(target, fullPath);
} catch (error) {
const err = new Error(`Failed to create symlink ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
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];
// Expand tilde in working directory if provided, otherwise use home directory
const workingDir = cwd ? expandTilde(cwd) : os.homedir();
// 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}`));
}
});
});
+31
View File
@@ -0,0 +1,31 @@
import { contextBridge, ipcRenderer } from 'electron';
// Expose protected methods that allow the renderer process to use
// ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld('electron', {
// Platform information
platform: () => ipcRenderer.invoke('get-platform'),
// App version
version: () => ipcRenderer.invoke('get-app-version'),
// Filesystem API - paths support tilde (~) expansion for home directory
fs: {
readFile: (path, encoding) => ipcRenderer.invoke('fs:readFile', path, encoding),
writeFile: (path, data, encoding) => ipcRenderer.invoke('fs:writeFile', path, data, encoding),
readdir: (path, withFileTypes) => ipcRenderer.invoke('fs:readdir', path, withFileTypes),
mkdir: (path, recursive) => ipcRenderer.invoke('fs:mkdir', path, recursive),
stat: (path) => ipcRenderer.invoke('fs:stat', path),
lstat: (path) => ipcRenderer.invoke('fs:lstat', path),
unlink: (path) => ipcRenderer.invoke('fs:unlink', path),
rmdir: (path) => ipcRenderer.invoke('fs:rmdir', path),
rename: (oldPath, newPath) => ipcRenderer.invoke('fs:rename', oldPath, newPath),
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),
},
});
+7
View File
@@ -0,0 +1,7 @@
# Place your platform-specific icons here:
#
# - icon.icns (macOS)
# - icon.ico (Windows)
# - icons/ directory with PNG files (Linux)
#
# See electron/README.md for details on creating these icons.
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
/**
* Test script to validate electron-builder configuration
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
console.log('🔍 Validating Electron build configuration...\n');
const errors = [];
const warnings = [];
// Check if required files exist
const requiredFiles = [
'electron/main.js',
'electron/preload.js',
'electron/builder.config.js',
'public/shakespeare-512x512.png',
'package.json',
];
console.log('📁 Checking required files:');
requiredFiles.forEach(file => {
if (fs.existsSync(file)) {
console.log(` ✅ ${file}`);
} else {
console.log(` ❌ ${file}`);
errors.push(`Missing required file: ${file}`);
}
});
// Check if dist directory exists
console.log('\n📦 Checking build output:');
if (fs.existsSync('dist')) {
const distFiles = fs.readdirSync('dist');
if (distFiles.includes('index.html')) {
console.log(' ✅ dist/index.html exists');
} else {
console.log(' ❌ dist/index.html missing');
errors.push('Run "npm run build" first to create dist/index.html');
}
} else {
console.log(' ❌ dist directory missing');
errors.push('Run "npm run build" first to create the dist directory');
}
// Check package.json
console.log('\n📄 Checking package.json:');
try {
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
if (pkg.main === 'electron/main.js') {
console.log(' ✅ main entry point set correctly');
} else {
console.log(` ⚠️ main entry point is "${pkg.main}" (expected "electron/main.js")`);
warnings.push('package.json main should be "electron/main.js"');
}
if (pkg.devDependencies?.electron) {
console.log(' ✅ electron dependency found');
} else {
console.log(' ❌ electron dependency missing');
errors.push('Install electron: npm install --save-dev electron');
}
if (pkg.devDependencies?.['electron-builder']) {
console.log(' ✅ electron-builder dependency found');
} else {
console.log(' ❌ electron-builder dependency missing');
errors.push('Install electron-builder: npm install --save-dev electron-builder');
}
} catch (e) {
console.log(' ❌ Error reading package.json');
errors.push(`Failed to read package.json: ${e.message}`);
}
// Check builder config
console.log('\n⚙️ Checking builder configuration:');
try {
const configModule = await import('./builder.config.js');
const config = configModule.default;
if (config.appId) {
console.log(` ✅ appId: ${config.appId}`);
} else {
console.log(' ⚠️ appId not set');
warnings.push('Consider setting appId in builder.config.js');
}
if (config.productName) {
console.log(` ✅ productName: ${config.productName}`);
} else {
console.log(' ⚠️ productName not set');
warnings.push('Consider setting productName in builder.config.js');
}
// Check icon paths
const iconPaths = [];
if (config.mac?.icon) iconPaths.push({ platform: 'macOS', path: config.mac.icon });
if (config.win?.icon) iconPaths.push({ platform: 'Windows', path: config.win.icon });
if (config.linux?.icon) iconPaths.push({ platform: 'Linux', path: config.linux.icon });
console.log('\n🎨 Checking icon configuration:');
iconPaths.forEach(({ platform, path: iconPath }) => {
if (fs.existsSync(iconPath)) {
console.log(` ✅ ${platform}: ${iconPath}`);
} else {
console.log(` ⚠️ ${platform}: ${iconPath} (will be generated from PNG)`);
}
});
} catch (e) {
console.log(' ❌ Error reading builder.config.js');
errors.push(`Failed to read builder.config.js: ${e.message}`);
}
// Summary
console.log('\n' + '='.repeat(60));
if (errors.length === 0 && warnings.length === 0) {
console.log('✅ Configuration is valid! Ready to build.');
console.log('\nNext steps:');
console.log(' Development: npm run electron:dev');
console.log(' Build: npm run electron:build');
process.exit(0);
} else {
if (errors.length > 0) {
console.log('❌ Errors found:');
errors.forEach(err => console.log(` - ${err}`));
}
if (warnings.length > 0) {
console.log('\n⚠️ Warnings:');
warnings.forEach(warn => console.log(` - ${warn}`));
}
if (errors.length > 0) {
console.log('\n❌ Fix errors before building.');
process.exit(1);
} else {
console.log('\n✅ Configuration is valid (with warnings).');
process.exit(0);
}
}
+84
View File
@@ -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();
+3476
View File
File diff suppressed because it is too large. Load diff
+12 -1
View File
@@ -6,6 +6,7 @@
"private": true,
"version": "0.0.0",
"type": "module",
"main": "electron/main.js",
"author": {
"name": "shakespeare.diy",
"email": "[email protected]"
@@ -19,7 +20,15 @@
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup",
"electron:dev": "npm run build && electron .",
"electron:build": "npm run build && electron-builder --config electron/builder.config.js",
"electron:build:mac": "npm run build && electron-builder --mac --config electron/builder.config.js",
"electron:build:win": "npm run build && electron-builder --win --config electron/builder.config.js",
"electron:build:linux": "npm run build && electron-builder --linux --config electron/builder.config.js",
"electron:build:all": "npm run build && electron-builder --mac --win --linux --config electron/builder.config.js",
"electron:icons": "bash electron/generate-icons.sh",
"electron:validate": "node electron/test-config.js"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
@@ -124,6 +133,8 @@
"@types/uri-templates": "^0.1.34",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"electron": "^38.4.0",
"electron-builder": "^26.0.12",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
+51 -6
View File
@@ -20,6 +20,7 @@ import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
@@ -43,6 +44,47 @@ const queryClient = new QueryClient({
},
});
// Get OS-specific default paths for Electron
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string } {
if (!globalThis.electron) {
// Browser defaults - use virtual filesystem paths
return {
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
};
}
// Electron defaults - use OS-specific paths
// Note: The ~ will be expanded by the Electron main process
const platform = navigator.platform.toLowerCase();
if (platform.includes('win')) {
// Windows
return {
fsPathProjects: "~/Documents/Projects",
fsPathConfig: "~/AppData/Local/shakespeare",
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
};
} else if (platform.includes('mac')) {
// macOS
return {
fsPathProjects: "~/Projects",
fsPathConfig: "~/Library/Application Support/shakespeare",
fsPathTmp: "/tmp/shakespeare",
};
} else {
// Linux and other Unix-like systems
return {
fsPathProjects: "~/Projects",
fsPathConfig: "~/.config/shakespeare",
fsPathTmp: "/tmp/shakespeare",
};
}
}
const electronPaths = getElectronDefaultPaths();
const defaultConfig: AppConfig = {
theme: "system",
relayUrl: "wss://relay.ditto.pub",
@@ -54,9 +96,9 @@ const defaultConfig: AppConfig = {
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
fsPathProjects: electronPaths.fsPathProjects,
fsPathConfig: electronPaths.fsPathConfig,
fsPathTmp: electronPaths.fsPathTmp,
};
const presetRelays = [
@@ -66,9 +108,12 @@ const presetRelays = [
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
// Initialize LightningFS
const lightningFS = new LightningFS('shakespeare-fs');
const fs = new LightningFSAdapter(lightningFS.promises);
// Initialize filesystem adapter based on environment
// In Electron, use Electron filesystem at ~/shakespeare
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
const fs = globalThis.electron
? new ElectronFSAdapter()
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
// Component to handle filesystem cleanup on startup
// Automatically removes files older than 1 hour from tmp directory
+6 -3
View File
@@ -1,4 +1,4 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
@@ -24,8 +24,11 @@ import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
export function AppRouter() {
// Use HashRouter in Electron, BrowserRouter in web
const Router = globalThis.electron ? HashRouter : BrowserRouter;
return (
<BrowserRouter>
<Router>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
@@ -53,7 +56,7 @@ export function AppRouter() {
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</Router>
);
}
export default AppRouter;
+1 -1
View File
@@ -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(),
};
+3 -3
View File
@@ -4,9 +4,9 @@ export interface ShakespeareLogoProps {
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
return (
<img
src="/shakespeare.svg"
alt="Shakespeare"
<img
src="/shakespeare.svg"
alt="Shakespeare"
className={className}
/>
);
+62 -16
View File
@@ -38,7 +38,7 @@ 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
setLines([{
@@ -81,7 +81,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 +95,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 +163,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory]);
}, [addLine, commandHistory, projectId, projectsPath]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
+13 -2
View File
@@ -42,7 +42,7 @@ export interface ProjectDeploySettings {
* Hook to manage project-specific deployment settings
* Stores settings in .git/shakespeare/deploy.json
*/
export function useProjectDeploySettings(projectId: string) {
export function useProjectDeploySettings(projectId: string | null) {
const fs = useFS();
const { projectsPath } = useFSPaths();
const [settings, setSettings] = useState<ProjectDeploySettings>({ providers: {} });
@@ -51,6 +51,13 @@ export function useProjectDeploySettings(projectId: string) {
const settingsPath = `${projectsPath}/${projectId}/.git/shakespeare/deploy.json`;
const loadSettings = useCallback(async () => {
// Don't try to load if projectId is falsy
if (!projectId) {
setSettings({ providers: {} });
setIsLoading(false);
return;
}
try {
setIsLoading(true);
const content = await fs.fs.readFile(settingsPath, 'utf8');
@@ -71,13 +78,17 @@ export function useProjectDeploySettings(projectId: string) {
} finally {
setIsLoading(false);
}
}, [fs.fs, settingsPath]);
}, [fs.fs, settingsPath, projectId]);
useEffect(() => {
loadSettings();
}, [loadSettings]);
const saveSettings = async (newSettings: ProjectDeploySettings) => {
if (!projectId) {
throw new Error('Cannot save settings: no project selected');
}
try {
// Ensure .git/shakespeare directory exists
const shakespeareDir = `${projectsPath}/${projectId}/.git/shakespeare`;
+238
View File
@@ -0,0 +1,238 @@
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
/**
* Electron filesystem adapter that implements JSRuntimeFS interface
* This adapter communicates with Electron's main process via IPC to perform
* filesystem operations on the actual OS filesystem.
*
* Note: This adapter should only be instantiated when running in Electron.
*/
export class ElectronFSAdapter implements JSRuntimeFS {
private get electron() {
if (!window.electron) {
throw new Error('ElectronFSAdapter can only be used in Electron environment');
}
return window.electron;
}
/**
* Unwrap Electron IPC errors to preserve error codes.
* Electron wraps errors in "Error invoking remote method..." messages,
* but we need to preserve the original error code for isomorphic-git.
*/
private unwrapElectronError(error: unknown): Error {
if (!(error instanceof Error)) {
return error as Error;
}
// Extract error code from the error object if it exists
const code = (error as NodeJS.ErrnoException).code;
// If there's already a code, preserve it
if (code) {
const err = new Error(error.message);
(err as NodeJS.ErrnoException).code = code;
return err;
}
// If no code property, try to extract from the message
// Messages look like: "Error invoking remote method 'fs:stat': Error: Failed to stat /path: ENOENT: no such file or directory"
const match = error.message.match(/:\s*(E[A-Z]+):/);
if (match) {
const err = new Error(error.message);
(err as NodeJS.ErrnoException).code = match[1];
return err;
}
return error;
}
async readFile(path: string): Promise<Uint8Array<ArrayBuffer>>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>> {
try {
const encoding = typeof options === 'string' ? options : options?.encoding;
const result = await this.electron.fs.readFile(path, encoding);
// If no encoding, convert array to Uint8Array
if (!encoding && Array.isArray(result)) {
return new Uint8Array(result);
}
return result as string;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void> {
try {
const encoding = typeof options === 'string' ? options : options?.encoding;
// Convert Uint8Array to regular array for IPC serialization
const dataToWrite = data instanceof Uint8Array ? Array.from(data) : data;
return await this.electron.fs.writeFile(path, dataToWrite, encoding);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
try {
const result = await this.electron.fs.readdir(path, options?.withFileTypes);
if (options?.withFileTypes) {
// Convert plain objects to DirectoryEntry format
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({
name: entry.name,
isDirectory: () => entry.isDirectory,
isFile: () => entry.isFile,
}));
}
return result as string[];
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
try {
// Default to recursive: true for isomorphic-git compatibility
// isomorphic-git expects mkdir to behave like 'mkdir -p'
const recursive = options?.recursive !== false;
return await this.electron.fs.mkdir(path, recursive);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
mtime: Date;
ctime: Date;
atime: Date;
}> {
try {
const result = await this.electron.fs.stat(path);
const now = Date.now();
return {
isDirectory: () => result.isDirectory,
isFile: () => result.isFile,
isBlockDevice: () => result.isBlockDevice,
isCharacterDevice: () => result.isCharacterDevice,
isSymbolicLink: () => result.isSymbolicLink,
isFIFO: () => result.isFIFO,
isSocket: () => result.isSocket,
size: result.size ?? 0,
mtimeMs: result.mtimeMs ?? now,
ctimeMs: result.ctimeMs ?? now,
atimeMs: result.atimeMs ?? now,
// Convert timestamps back to Date objects
mtime: new Date(result.mtime ?? now),
ctime: new Date(result.ctime ?? now),
atime: new Date(result.atime ?? now),
};
} catch (error) {
// Electron IPC wraps errors, extract the original error code
throw this.unwrapElectronError(error);
}
}
async lstat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
mtime: Date;
ctime: Date;
atime: Date;
}> {
try {
const result = await this.electron.fs.lstat(path);
const now = Date.now();
return {
isDirectory: () => result.isDirectory,
isFile: () => result.isFile,
isBlockDevice: () => result.isBlockDevice,
isCharacterDevice: () => result.isCharacterDevice,
isSymbolicLink: () => result.isSymbolicLink,
isFIFO: () => result.isFIFO,
isSocket: () => result.isSocket,
size: result.size ?? 0,
mtimeMs: result.mtimeMs ?? now,
ctimeMs: result.ctimeMs ?? now,
atimeMs: result.atimeMs ?? now,
// Convert timestamps back to Date objects
mtime: new Date(result.mtime ?? now),
ctime: new Date(result.ctime ?? now),
atime: new Date(result.atime ?? now),
};
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async unlink(path: string): Promise<void> {
try {
return await this.electron.fs.unlink(path);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async rmdir(path: string): Promise<void> {
try {
return await this.electron.fs.rmdir(path);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async rename(oldPath: string, newPath: string): Promise<void> {
try {
return await this.electron.fs.rename(oldPath, newPath);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async readlink(path: string): Promise<string> {
try {
return await this.electron.fs.readlink(path);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async symlink(target: string, path: string): Promise<void> {
try {
return await this.electron.fs.symlink(target, path);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
}
+103
View File
@@ -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
View File
@@ -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, '');
}
+59 -1
View File
@@ -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)
*/
+1 -1
View File
@@ -15,4 +15,4 @@ import '@fontsource-variable/inter';
// Prism syntax highlighting
import 'prismjs/themes/prism.css';
createRoot(document.getElementById("root")!).render(<App />);
createRoot(document.getElementById("root")!).render(<App />);
+1 -1
View File
@@ -27,5 +27,5 @@
"@/*": ["./src/*"]
}
},
"include": ["src"]
"include": ["src", "electron/electron.d.ts"]
}