Remove development artifact documentation

Removed Electron docs that were development/debugging artifacts:
- .electron-build-summary.md - AI build summary
- BUGFIX-ERROR-CODES.md - Specific bug fix notes
- COMPLETE_FIX_SUMMARY.md - More bug fix notes
- ERROR-CODE-FLOW.md - Debug diagrams
- CHANGELOG.md - Development changelog
- INDEX.md - Just listed other docs
- ARCHITECTURE.md - Internal implementation details

Kept essential user/developer documentation:
- README.md - Main technical reference
- QUICKSTART.md - Build/run instructions
- QUICKSTART_FILESYSTEM.md - Quick filesystem guide
- FEATURES.md - Feature overview
- FILESYSTEM.md - Detailed filesystem docs
- REAL_TERMINAL.md - Terminal details
- INTEGRATION.md - Developer integration guide
- TROUBLESHOOTING.md - User troubleshooting

This reduces documentation from ~2,900 lines to ~1,750 lines while
keeping all essential information for users and contributors.
This commit is contained in:
Alex Gleason committed 2025-10-24 19:21:43 -05:00
1 parent 08df445cae
commit b7f366efcd
7 files changed
-1401

No files matched your search

-228
View File
@@ -1,228 +0,0 @@
# ✅ Electron Build Setup Complete
## 🎉 What Was Created
The Shakespeare project now has a complete Electron desktop application build system, with all files organized in the `electron/` directory to keep the existing codebase untouched.
### 📁 Files Created
```
electron/
├── 📄 main.js # Main Electron process (ESM)
├── 📄 preload.js # Secure IPC bridge (ESM)
├── 📄 builder.config.js # Build configuration (ESM)
├── 📄 electron.d.ts # TypeScript definitions
├── 🔧 generate-icons.sh # Icon generation script
├── 🔧 test-config.js # Configuration validator (ESM)
├── 📖 INDEX.md # Documentation index
├── 📖 README.md # Technical documentation
├── 📖 QUICKSTART.md # Quick start guide
├── 📖 INTEGRATION.md # Developer integration guide
├── 📖 TROUBLESHOOTING.md # Troubleshooting guide
├── 📖 CHANGELOG.md # Version history
└── 📁 resources/ # Icon resources directory
└── .gitkeep
```
### 🔧 Package.json Scripts Added
```json
{
"electron:dev": "Run in development mode",
"electron:build": "Build for current platform",
"electron:build:mac": "Build for macOS",
"electron:build:win": "Build for Windows",
"electron:build:linux": "Build for Linux",
"electron:build:all": "Build for all platforms",
"electron:icons": "Generate platform icons"
}
```
### 📦 Dependencies Added
- `electron` - Desktop application framework
- `electron-builder` - Multi-platform build tool
- `concurrently` - Run multiple commands
- `wait-on` - Wait for dev server
- `cross-env` - Cross-platform environment variables
### 📝 Configuration Updates
- ✅ `package.json` - Added main entry point and scripts
- ✅ `tsconfig.json` - Added Electron type definitions
- ✅ `.gitignore` - Added electron-dist directory
- ✅ `README.md` - Added Desktop App section
## 🚀 How to Use
### Development Mode
```bash
npm run electron:dev
```
Opens Shakespeare in an Electron window with hot-reload and DevTools.
### Build for Distribution
```bash
# Build for your current platform
npm run electron:build
# Or 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
```
### Generate Icons (Optional)
```bash
npm run electron:icons
```
Requires ImageMagick. Creates platform-specific icons from `public/shakespeare-512x512.png`.
## 🎯 Platform Support
### macOS
- ✅ Intel (x64) builds
- ✅ Apple Silicon (arm64) builds
- 📦 DMG installer
- 📦 ZIP archive
### Windows
- ✅ x64 builds
- ✅ ARM64 builds
- 📦 NSIS installer
- 📦 Portable executable
### Linux
- ✅ x64 builds
- ✅ ARM64 builds
- 📦 AppImage
- 📦 DEB package
- 📦 RPM package
## 🔒 Security Features
- ✅ Context isolation enabled (primary security boundary)
- ⚠️ Sandbox mode disabled (required for ESM preload scripts)
- ✅ Node integration disabled
- ✅ Minimal IPC API surface
- ✅ Navigation restrictions
- ✅ Secure window opening
## 📚 Documentation
Comprehensive documentation has been created:
1. **[INDEX.md](INDEX.md)** - Start here for documentation overview
2. **[QUICKSTART.md](QUICKSTART.md)** - Quick start guide for users
3. **[INTEGRATION.md](INTEGRATION.md)** - Developer integration guide
4. **[TROUBLESHOOTING.md](TROUBLESHOOTING.md)** - Common issues and solutions
5. **[README.md](README.md)** - Complete technical reference
6. **[CHANGELOG.md](CHANGELOG.md)** - Version history
## 🎨 Icons
**No setup required!** The build automatically uses `public/shakespeare-512x512.png` and converts it to the appropriate format for each platform (icns for macOS, ico for Windows, png for Linux).
If you want custom icons, you can optionally:
```bash
npm run electron:icons # Requires ImageMagick
```
Or manually place custom icons in `electron/resources/` and update `builder.config.js`.
## ✨ Key Features
### Current Features
- Platform detection API
- App version information
- Secure IPC communication
- External link handling
- Native window management
- Hot-reload development mode
### Potential Future Features
- Auto-updates
- Native application menus
- System tray integration
- File type associations
- Native dialogs
- Custom URL schemes
- Multiple windows
- Keyboard shortcuts
## 🧪 Testing Status
- ✅ TypeScript compilation passes
- ✅ All existing tests pass (877 tests)
- ✅ Web build works unchanged
- ✅ No breaking changes to existing code
## 📦 Build Output
Built applications will be in `electron-dist/`:
```
electron-dist/
├── mac/
│ ├── Shakespeare.app
│ └── Shakespeare.dmg
├── win-unpacked/
│ └── Shakespeare.exe
├── Shakespeare Setup.exe
├── Shakespeare Portable.exe
└── shakespeare-*.AppImage
```
## 🎓 Next Steps
1. **Try it out:**
```bash
npm run electron:dev
```
2. **Generate icons:**
```bash
npm run electron:icons
```
3. **Build for your platform:**
```bash
npm run electron:build
```
4. **Read the documentation:**
- Start with `electron/QUICKSTART.md`
- Check `electron/INDEX.md` for full documentation index
5. **Customize as needed:**
- Window size/appearance: `electron/main.js`
- Build settings: `electron/builder.config.js`
- Add features: See `electron/INTEGRATION.md`
## 💡 Important Notes
- ✅ **Existing codebase is untouched** - All Electron code is in `electron/`
- ✅ **Web version still works** - No dependencies on Electron
- ✅ **Progressive enhancement** - Electron features are optional
- ✅ **Type-safe** - Full TypeScript support
- ✅ **Secure** - Follows Electron security best practices
- ✅ **Well-documented** - Comprehensive guides for users and developers
## 🆘 Need Help?
1. Check `electron/TROUBLESHOOTING.md` for common issues
2. Read the relevant documentation in `electron/`
3. Search existing issues on GitLab
4. Create a new issue with details
## 🎉 Success!
Your Shakespeare project now has a complete Electron build system that:
- Keeps the existing codebase untouched
- Provides native desktop apps for all major platforms
- Includes comprehensive documentation
- Follows security best practices
- Is ready to use immediately
**Try it now:** `npm run electron:dev`
-456
View File
@@ -1,456 +0,0 @@
# 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)
-118
View File
@@ -1,118 +0,0 @@
# Electron Filesystem Error Code Preservation Fix
## Problem
When creating projects in the Electron app, the filesystem operations were failing because error codes (like `ENOENT`) were not being preserved during IPC communication between the renderer and main processes.
### Root Cause
The Shakespeare codebase relies on checking `error.code === 'ENOENT'` in multiple places to handle file-not-found scenarios gracefully:
- `ProjectsManager.readFile()`
- `ProjectsManager.readFileBytes()`
- `ProjectsManager.listFiles()`
- `ProjectsManager.fileExists()`
When errors are thrown from Node.js filesystem operations in the Electron main process and sent via IPC to the renderer process, the `code` property was being lost during serialization. This is because error properties are typically non-enumerable and don't survive the IPC boundary.
### Symptoms
```
Error occurred in handler for 'fs:stat': Error: Failed to stat /tmp: ENOENT: no such file or directory
Error occurred in handler for 'fs:stat': Error: Failed to stat /projects/untitled: ENOENT: no such file or directory
```
The error messages contained "ENOENT", but the `error.code` property was `undefined`, causing code that checks `error.code === 'ENOENT'` to fail.
## Solution
The fix required changes in two places:
### 1. Electron Main Process (`electron/main.js`)
Updated all filesystem IPC handlers to explicitly preserve the error `code` property using `Object.defineProperty()` with `enumerable: true`:
```javascript
catch (error) {
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true, // Critical: makes property survive IPC serialization
writable: true,
configurable: true,
});
}
throw err;
}
```
**Updated IPC Handlers:**
- `fs:readFile`
- `fs:writeFile`
- `fs:readdir`
- `fs:mkdir`
- `fs:stat`
- `fs:lstat`
- `fs:unlink`
- `fs:rmdir`
- `fs:rename`
- `fs:readlink`
- `fs:symlink`
### 2. Electron FS Adapter (`src/lib/ElectronFSAdapter.ts`)
Added error unwrapping in the renderer process to handle Electron's IPC error wrapping. When errors cross the IPC boundary, Electron wraps them in messages like "Error invoking remote method 'fs:stat': ...". The adapter now:
1. **Catches all errors** from IPC calls
2. **Extracts the error code** from either:
- The `code` property (if preserved from main process)
- The error message via regex matching (fallback)
3. **Re-throws a clean error** with the proper `code` property
```typescript
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
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;
}
```
All filesystem methods in `ElectronFSAdapter` now wrap their calls in try-catch blocks and use `unwrapElectronError()` to ensure error codes are properly preserved.
## Difference from LightningFS
**LightningFS** runs entirely in the renderer process (browser context), so errors never cross the IPC boundary. Error objects maintain all their properties, including the `code` property.
**ElectronFS** uses IPC to communicate between renderer and main processes. Without explicitly making the `code` property enumerable, it gets lost during serialization.
## Testing
After this fix, project creation in the Electron app should work identically to the browser version:
1. Creating new projects from templates
2. Importing projects from ZIP files
3. Git operations on non-existent paths
4. File existence checks
All operations that rely on `ENOENT` detection should now function correctly.
-73
View File
@@ -1,73 +0,0 @@
# Electron Build Changelog
All notable changes to the Shakespeare Electron build will be documented in this file.
## [Unreleased]
### Added
- Initial Electron build support
- Main process with secure window management (`main.js`)
- Preload script with minimal API exposure (`preload.js`)
- electron-builder configuration for multi-platform builds (`builder.config.js`)
- TypeScript definitions for Electron API (`electron.d.ts`)
- Icon generation script (`generate-icons.sh`)
- Comprehensive documentation:
- `INDEX.md` - Documentation index
- `README.md` - Technical documentation
- `QUICKSTART.md` - Quick start guide
- `INTEGRATION.md` - Developer integration guide
- `TROUBLESHOOTING.md` - Troubleshooting guide
- NPM scripts for development and building:
- `electron:dev` - Development mode
- `electron:build` - Build for current platform
- `electron:build:mac` - Build for macOS
- `electron:build:win` - Build for Windows
- `electron:build:linux` - Build for Linux
- `electron:build:all` - Build for all platforms
- `electron:icons` - Generate platform icons
### Security
- Enabled context isolation
- Enabled sandbox mode
- Disabled node integration
- Implemented navigation restrictions
- Configured secure window opening behavior
- Minimal IPC API surface through preload script
### Platform Support
- macOS (Intel and Apple Silicon)
- DMG installer
- ZIP archive
- Windows (x64 and ARM64)
- NSIS installer
- Portable executable
- Linux (x64 and ARM64)
- AppImage
- DEB package
- RPM package
### API
- `window.electron.isElectron` - Detect Electron environment
- `window.electron.platform()` - Get platform information
- `window.electron.version()` - Get app version
## Future Enhancements
Planned features for future releases:
- [ ] Auto-update support
- [ ] Native application menu
- [ ] System tray integration
- [ ] File type associations
- [ ] Custom URL scheme handling
- [ ] Native file dialogs
- [ ] Enhanced offline capabilities
- [ ] Keyboard shortcuts/accelerators
- [ ] Window state persistence
- [ ] Multiple window support
- [ ] Native notifications
- [ ] Deep linking support
## Notes
The Electron build is designed to keep the existing web codebase untouched. All Electron-specific code is contained in the `electron/` directory, and the web version continues to work independently.
-198
View File
@@ -1,198 +0,0 @@
# Complete Electron Filesystem Fix Summary
This document summarizes all fixes applied to enable project creation in the Electron app.
## Problems Encountered
### Problem 1: Error Codes Not Preserved Across IPC
**Symptom**: isomorphic-git's `FileSystem.exists()` method was throwing "Unhandled error" instead of returning `false` for non-existent files.
**Root Cause**: Error `code` properties (like `ENOENT`) were being lost during IPC serialization because they are non-enumerable by default.
**Impact**: Code that checks `error.code === 'ENOENT'` failed, breaking file existence checks throughout the codebase.
### Problem 2: Missing fs.Stats Methods
**Symptom**: `TypeError: h.isSymbolicLink is not a function`
**Root Cause**: The `stat()` and `lstat()` methods only returned `isDirectory()` and `isFile()`, but isomorphic-git requires the complete fs.Stats interface including `isSymbolicLink()`.
**Impact**: isomorphic-git operations failed when checking file types during Git operations.
## Solutions Implemented
### Fix 1: Error Code Preservation (Two-Part Fix)
#### Part A: Main Process (`electron/main.js`)
Made error codes enumerable so they survive IPC serialization:
```javascript
catch (error) {
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true, // ← Critical for IPC serialization
writable: true,
configurable: true,
});
}
throw err;
}
```
Applied to all 11 IPC handlers:
- `fs:readFile`
- `fs:writeFile`
- `fs:readdir`
- `fs:mkdir`
- `fs:stat`
- `fs:lstat`
- `fs:unlink`
- `fs:rmdir`
- `fs:rename`
- `fs:readlink`
- `fs:symlink`
#### Part B: Renderer Process (`src/lib/ElectronFSAdapter.ts`)
Added error unwrapping to handle Electron's IPC error wrapping:
```typescript
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
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;
}
```
All filesystem methods now wrap IPC calls in try-catch and use `unwrapElectronError()`.
### Fix 2: Complete fs.Stats Interface
Added all fs.Stats methods to `stat()` and `lstat()` in both main process and adapter:
**Main Process (`electron/main.js`):**
```javascript
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(), // ← Critical for isomorphic-git
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs,
};
```
**Renderer Process (`src/lib/ElectronFSAdapter.ts`):**
```typescript
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,
mtimeMs: result.mtimeMs,
};
```
**TypeScript Definitions (`electron/electron.d.ts`):**
```typescript
interface StatResult {
isDirectory: boolean;
isFile: boolean;
isBlockDevice: boolean;
isCharacterDevice: boolean;
isSymbolicLink: boolean;
isFIFO: boolean;
isSocket: boolean;
size?: number;
mtimeMs?: number;
}
```
## Files Modified
1. **`electron/main.js`**
- Added error code preservation to all IPC handlers
- Added complete fs.Stats methods to `stat()` and `lstat()`
2. **`src/lib/ElectronFSAdapter.ts`**
- Added `unwrapElectronError()` helper method
- Updated all filesystem methods to use error unwrapping
- Added complete fs.Stats methods to `stat()` and `lstat()`
3. **`electron/electron.d.ts`**
- Updated `StatResult` interface with all fs.Stats methods
4. **Documentation**
- `electron/BUGFIX-ERROR-CODES.md`
- `ELECTRON_ERROR_FIX_SUMMARY.md`
- `electron/ERROR-CODE-FLOW.md`
- `electron/COMPLETE_FIX_SUMMARY.md` (this file)
## Validation
✅ **TypeScript compilation**: Passes without errors
✅ **Test suite**: All 877 tests pass (106 test files)
✅ **Error codes preserved**: Both in main and renderer processes
✅ **isomorphic-git compatibility**: Full fs.Stats interface provided
✅ **Project creation**: Should now work in Electron app
## Why Both Fixes Were Necessary
1. **Error Code Fix**: Required for isomorphic-git to determine if files exist
2. **fs.Stats Methods Fix**: Required for isomorphic-git to check file types during Git operations
Both fixes work together to provide complete filesystem compatibility with isomorphic-git in the Electron environment.
## Differences from LightningFS
**LightningFS** (browser):
- Runs in renderer process - no IPC boundary
- Error properties preserved automatically
- May have incomplete fs.Stats interface (but isomorphic-git handles gracefully)
**ElectronFS** (desktop):
- Uses IPC - requires explicit error code preservation
- Requires complete fs.Stats interface for isomorphic-git compatibility
- Must unwrap Electron's IPC error wrapping
## Testing in Electron App
To verify the fixes work:
1. Build the Electron app: `npm run electron:build`
2. Run the app
3. Try creating a new project
4. Project creation should complete successfully without errors
Expected behavior:
- No "Unhandled error in FileSystem.exists()" errors
- No "isSymbolicLink is not a function" errors
- Project files created successfully
- Git repository initialized properly
-127
View File
@@ -1,127 +0,0 @@
# Error Code Preservation Flow
## Before the Fix ❌
```
┌─────────────────────────────────────────────────────────────────┐
│ RENDERER PROCESS │
│ │
│ ElectronFSAdapter.stat('/projects/untitled') │
│ │ │
│ └──────► IPC Call: fs:stat │
└─────────────────────────────────────────────────────────────────┘
│
│ IPC Channel
▼
┌─────────────────────────────────────────────────────────────────┐
│ MAIN PROCESS │
│ │
│ IPC Handler receives: '/projects/untitled' │
│ │ │
│ └──────► fs.stat('/home/user/shakespeare/projects/...')│
│ │ │
│ ▼ │
│ ❌ ENOENT Error │
│ { │
│ message: "ENOENT: no such file...", │
│ code: 'ENOENT' ← Non-enumerable! │
│ } │
│ │ │
│ └──────► Throw error │
└─────────────────────────────────────────────────────────────────┘
│
│ IPC Serialization (loses code!)
▼
┌─────────────────────────────────────────────────────────────────┐
│ RENDERER PROCESS │
│ │
│ Error received: │
│ { │
│ message: "Error invoking remote method 'fs:stat': ...", │
│ code: undefined ← LOST! │
│ } │
│ │ │
│ └──────► isomorphic-git checks: err.code === 'ENOENT' │
│ │ │
│ ▼ │
│ ❌ FALSE (code is undefined) │
│ │ │
│ └──────► Throws unhandled error │
│ 💥 PROJECT CREATION FAILS │
└─────────────────────────────────────────────────────────────────┘
```
## After the Fix ✅
```
┌─────────────────────────────────────────────────────────────────┐
│ RENDERER PROCESS │
│ │
│ ElectronFSAdapter.stat('/projects/untitled') │
│ │ │
│ └──────► IPC Call: fs:stat │
└─────────────────────────────────────────────────────────────────┘
│
│ IPC Channel
▼
┌─────────────────────────────────────────────────────────────────┐
│ MAIN PROCESS │
│ │
│ IPC Handler receives: '/projects/untitled' │
│ │ │
│ └──────► fs.stat('/home/user/shakespeare/projects/...')│
│ │ │
│ ▼ │
│ ❌ ENOENT Error │
│ { │
│ message: "ENOENT: no such file...", │
│ code: 'ENOENT' │
│ } │
│ │ │
│ └──────► Catch & Re-throw │
│ │
│ ✅ FIX #1: Make code enumerable │
│ Object.defineProperty(err, 'code', { │
│ value: error.code, │
│ enumerable: true ← Survives IPC! │
│ }) │
└─────────────────────────────────────────────────────────────────┘
│
│ IPC Serialization (preserves code!)
▼
┌─────────────────────────────────────────────────────────────────┐
│ RENDERER PROCESS │
│ │
│ Error received: │
│ { │
│ message: "Error invoking remote method 'fs:stat': ...", │
│ code: 'ENOENT' ← PRESERVED! ✅ │
│ } │
│ │ │
│ └──────► ✅ FIX #2: unwrapElectronError() │
│ │ │
│ ▼ │
│ Extract code from error │
│ Create new error with code property │
│ │ │
│ └──────► Return to caller │
│ │
│ isomorphic-git checks: err.code === 'ENOENT' │
│ │ │
│ ▼ │
│ ✅ TRUE (code preserved!) │
│ │ │
│ └──────► Returns false │
│ ✅ PROJECT CREATION SUCCEEDS │
└─────────────────────────────────────────────────────────────────┘
```
## Key Points
1. **Problem**: Error `code` property is non-enumerable by default and gets lost during IPC serialization
2. **Fix #1 (Main Process)**: Use `Object.defineProperty()` with `enumerable: true` to make the code property survive IPC
3. **Fix #2 (Renderer Process)**: Unwrap Electron's error wrapping and extract the code property (or parse from message as fallback)
4. **Result**: isomorphic-git's `FileSystem.exists()` method can properly detect ENOENT errors and return `false` instead of throwing
-201
View File
@@ -1,201 +0,0 @@
# Electron Build Documentation
Welcome to the Shakespeare Electron build documentation! This directory contains everything needed to build and run Shakespeare as a native desktop application.
## 📚 Documentation Index
### Getting Started
- **[QUICKSTART.md](QUICKSTART.md)** - Quick start guide for building and running Electron builds
- Development mode setup
- Building for distribution
- 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
- Using the Electron API
- Adding new features
- Security best practices
- Code examples
### Troubleshooting
- **[TROUBLESHOOTING.md](TROUBLESHOOTING.md)** - Solutions to common issues
- Development issues
- Build issues
- Runtime issues
- 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
- Security implementation
- Customization options
- **[ESM.md](ESM.md)** - Why we use ES Modules (ESM) instead of CommonJS
- Benefits and rationale
- Examples and patterns
- Migration guide
## 🗂️ File Structure
```
electron/
├── INDEX.md # This file - documentation index
├── README.md # Complete technical documentation
├── QUICKSTART.md # Quick start guide
├── INTEGRATION.md # Integration guide for developers
├── TROUBLESHOOTING.md # Troubleshooting guide
├── main.js # Electron main process (ESM)
├── preload.js # Preload script (ESM)
├── builder.config.js # electron-builder configuration (ESM)
├── electron.d.ts # TypeScript definitions for Electron API
├── generate-icons.sh # Script to generate platform icons
├── test-config.js # Configuration validation script (ESM)
└── resources/ # Build resources (icons, etc.)
└── .gitkeep
```
## 🚀 Quick Commands
```bash
# Development
npm run electron:dev # Run in development mode
# Building
npm run electron:build # Build for current platform
npm run electron:build:mac # Build for macOS
npm run electron:build:win # Build for Windows
npm run electron:build:linux # Build for Linux
npm run electron:build:all # Build for all platforms
# Utilities
npm run electron:icons # Generate icons from Shakespeare logo
```
## 🎯 What You Need to Know
### For Users
1. Read [QUICKSTART.md](QUICKSTART.md) to build and run the app
2. Check [TROUBLESHOOTING.md](TROUBLESHOOTING.md) if you encounter issues
### For Developers
1. Start with [QUICKSTART.md](QUICKSTART.md) for basic setup
2. Read [INTEGRATION.md](INTEGRATION.md) to add Electron features
3. Refer to [README.md](README.md) for technical details
4. Use [TROUBLESHOOTING.md](TROUBLESHOOTING.md) when debugging
## 🔒 Security
The Electron build implements security best practices:
- Context isolation enabled (primary security boundary)
- Sandbox mode disabled (required for ESM preload scripts)
- Node integration disabled
- Minimal API surface through preload script
- Navigation and window opening restrictions
See [README.md](README.md) for complete security details.
## 🎨 Icons
Before building for distribution, generate platform-specific icons:
```bash
npm run electron:icons
```
This requires ImageMagick. Alternatively, use online tools or electron-icon-builder.
See [QUICKSTART.md](QUICKSTART.md) for details.
## 📦 Build Output
Built applications are placed in `electron-dist/`:
- macOS: `.dmg` installer and `.app` bundle
- Windows: NSIS installer and portable `.exe`
- Linux: AppImage, `.deb`, and `.rpm` packages
## 🆘 Need Help?
1. Check the documentation files in order:
- [QUICKSTART.md](QUICKSTART.md)
- [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
- [INTEGRATION.md](INTEGRATION.md)
- [README.md](README.md)
2. Search existing issues on GitLab
3. Create a new issue with:
- OS and version
- Steps to reproduce
- Error messages
- Relevant logs
## 🔄 Updating
When updating the Electron build:
1. Update Electron version: `npm install electron@latest --save-dev`
2. Update electron-builder: `npm install electron-builder@latest --save-dev`
3. Test thoroughly on all target platforms
4. Update documentation if APIs change
## 🌟 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
When contributing to the Electron build:
1. Keep the web version working - it should not depend on Electron
2. Use progressive enhancement - Electron features should be optional
3. Follow security best practices
4. Update documentation
5. Test on all platforms if possible
## 📄 License
The Electron build is part of Shakespeare and is licensed under GNU AGPLv3.