Browse Source

fix: simplify Electron single instance enforcement

- Remove complex file-based locking that caused crashes
- Use only Electron's built-in requestSingleInstanceLock() API
- Second instances exit immediately with clear messaging
- Existing instance focuses and shows user-friendly dialog
- Prevents database conflicts and resource contention
- Update documentation with simplified approach

Fixes crashes when multiple instances run simultaneously.
web-serve-fix
Matthew Raymer 2 weeks ago
parent
commit
7fb06eaab5
  1. 408
      electron/README-BUILDING.md
  2. 30
      electron/src/index.ts

408
electron/README-BUILDING.md

@ -1,270 +1,272 @@
# Building TimeSafari Electron App # TimeSafari Electron Build Guide
This guide explains how to build distributable packages for the TimeSafari Electron desktop application. **Author**: Matthew Raymer
**Date**: 2025-01-10
**Status**: **ACTIVE** - Production Ready
## Overview
This guide covers building and running the TimeSafari Electron application for desktop platforms (Windows, macOS, Linux).
## Prerequisites
- Node.js 18+ and npm
- TypeScript
- Electron Builder
- Platform-specific build tools (see below)
## Quick Start ## Quick Start
### From Project Root ### Development Mode
```bash ```bash
# Build all Linux packages (AppImage, deb) # Start development server
npm run electron:build npm run build:electron:dev
# Build specific package types # Or manually
npm run electron:build:appimage # AppImage only cd electron
npm run electron:build:deb # Debian package only npm run electron:start
``` ```
### From Electron Directory ### Production Builds
```bash ```bash
cd electron # Build for current platform
npm run build:electron:prod
# Platform-specific builds
npm run build:electron:windows
npm run build:electron:mac
npm run build:electron:linux
# Package-specific builds
npm run build:electron:appimage # Linux AppImage
npm run build:electron:dmg # macOS DMG installer
npm run build:electron:deb # Linux DEB package
```
# Build all packages ## Single Instance Enforcement
./build-packages.sh
# Build specific types The Electron app enforces single instance operation to prevent database conflicts and resource contention:
./build-packages.sh appimage
./build-packages.sh deb
./build-packages.sh pack # Unpacked directory (for testing)
```
## Package Types ### Implementation
- Uses Electron's built-in `app.requestSingleInstanceLock()`
- Second instances exit immediately with user-friendly message
- Existing instance focuses and shows informational dialog
### 1. AppImage (Recommended for Linux) ### Behavior
- **File**: `TimeSafari-1.0.0.AppImage` - **First instance**: Starts normally and acquires lock
- **Size**: ~145MB - **Second instance**: Detects existing instance, exits immediately
- **Usage**: Download and run directly, no installation required - **User experience**: Clear messaging about single instance requirement
- **Distribution**: Upload to GitHub releases or website
```bash ### Benefits
# Make executable and run - Prevents database corruption from concurrent access
chmod +x TimeSafari-1.0.0.AppImage - Avoids resource conflicts
./TimeSafari-1.0.0.AppImage - Maintains data integrity
``` - User-friendly error handling
### 2. Debian Package (.deb) ## Build Configuration
- **File**: `TimeSafari_1.0.0_amd64.deb`
- **Size**: ~96MB
- **Usage**: Install via package manager
- **Distribution**: Upload to repositories or direct download
### Environment Modes
```bash ```bash
# Install # Development (default)
sudo dpkg -i TimeSafari_1.0.0_amd64.deb npm run build:electron:dev
# Run # Testing
timesafari npm run build:electron:test
```
### 3. RPM Package (.rpm) # Production
- **File**: `TimeSafari-1.0.0.x86_64.rpm` npm run build:electron:prod
- **Requirements**: `rpmbuild` must be installed ```
- **Usage**: Install via package manager
### Platform-Specific Builds
```bash ```bash
# Install rpmbuild (Arch Linux) # Windows
sudo pacman -S rpm-tools npm run build:electron:windows:dev
npm run build:electron:windows:test
# Build RPM npm run build:electron:windows:prod
./build-packages.sh rpm
# macOS
npm run build:electron:mac:dev
npm run build:electron:mac:test
npm run build:electron:mac:prod
# Linux
npm run build:electron:linux:dev
npm run build:electron:linux:test
npm run build:electron:linux:prod
```
# Install (on RPM-based systems) ### Package Types
sudo rpm -i TimeSafari-1.0.0.x86_64.rpm ```bash
# Linux AppImage
npm run build:electron:appimage:dev
npm run build:electron:appimage:test
npm run build:electron:appimage:prod
# macOS DMG
npm run build:electron:dmg:dev
npm run build:electron:dmg:test
npm run build:electron:dmg:prod
# Linux DEB
npm run build:electron:deb:dev
npm run build:electron:deb:test
npm run build:electron:deb:prod
``` ```
## Build Requirements ## Platform-Specific Requirements
### System Dependencies ### Windows
- Node.js 18+ - Windows 10+ (64-bit)
- npm or yarn - Visual Studio Build Tools (for native modules)
- Python 3 (for native module compilation)
- Build tools (gcc, make)
### Optional Dependencies ### macOS
- `rpmbuild` - for RPM packages - macOS 10.15+ (Catalina)
- `fpm` - automatically downloaded by electron-builder - Xcode Command Line Tools
- Code signing certificate (for distribution)
### Node Dependencies ### Linux
All required dependencies are in `package.json`: - Ubuntu 18.04+ / Debian 10+ / CentOS 7+
- `electron-builder` - Main build tool - Development headers for native modules
- `better-sqlite3-multiple-ciphers` - SQLite with encryption
- Native module compilation tools
## Build Process ## Database Configuration
### 1. Preparation ### SQLite Integration
```bash - Uses native Node.js SQLite3 for Electron
# Install dependencies - Database stored in user's app data directory
npm install - Automatic migration from IndexedDB (if applicable)
# Build TypeScript ### Single Instance Protection
npm run build - File-based locking prevents concurrent database access
``` - Automatic cleanup on app exit
- Graceful handling of lock conflicts
### 2. Package Creation ## Security Features
The build process:
1. Compiles TypeScript to JavaScript
2. Rebuilds native modules for Electron
3. Packages the app with electron-builder
4. Creates platform-specific installers
### 3. Output Location ### Content Security Policy
All built packages are saved to `electron/dist/`: - Strict CSP in production builds
``` - Development mode allows localhost connections
dist/ - Automatic configuration based on build mode
├── TimeSafari-1.0.0.AppImage # Portable AppImage
├── TimeSafari_1.0.0_amd64.deb # Debian package
├── TimeSafari-1.0.0.x86_64.rpm # RPM package (if built)
└── linux-unpacked/ # Unpacked directory
```
## Features
### Single Instance Enforcement
TimeSafari Electron enforces single-instance operation to prevent:
- Database corruption from multiple instances
- Resource conflicts and performance issues
- User confusion from multiple windows
**Behavior:**
- Only one instance can run at a time
- Attempting to launch a second instance shows a user-friendly dialog
- The existing window is focused and restored if minimized
- Second instance exits gracefully
**Implementation:**
- Uses Electron's `requestSingleInstanceLock()` API
- Handles `second-instance` events to focus existing window
- Shows informative dialog explaining why only one instance is allowed
## Configuration
### App Metadata
App information is configured in `electron/package.json`:
```json
{
"name": "TimeSafari",
"version": "1.0.0",
"description": "Time Safari - Community building through gifts, gratitude, and collaborative projects",
"homepage": "https://timesafari.app",
"author": {
"name": "Matthew Raymer",
"email": "matthew@timesafari.app"
}
}
```
### Build Configuration ### Auto-Updater
Build settings are in `electron/electron-builder.config.json`: - Disabled in development mode
- Package formats and architectures - Production builds check for updates automatically
- Icons and assets - AppImage builds skip update checks
- Platform-specific settings
- Signing and publishing options
## Troubleshooting ## Troubleshooting
### Common Issues ### Common Issues
#### 1. Native Module Compilation Errors #### Build Failures
```bash ```bash
# Clear cache and rebuild # Clean and rebuild
npm run build npm run clean:electron
``` npm run build:electron:dev
#### 2. Missing Dependencies
```bash
# Install system dependencies (Arch Linux)
sudo pacman -S base-devel python
# Install Node dependencies
npm install
``` ```
#### 3. RPM Build Fails #### Native Module Issues
```bash ```bash
# Install rpmbuild # Rebuild native modules
sudo pacman -S rpm-tools cd electron
npm run electron:rebuild
# Try building again
./build-packages.sh rpm
``` ```
#### 4. Large Package Size #### Single Instance Conflicts
The packages are large (~100-150MB) because they include: - Ensure no other TimeSafari instances are running
- Complete Electron runtime - Check for orphaned processes: `ps aux | grep electron`
- Node.js runtime - Restart system if necessary
- SQLite native modules
- Application assets
This is normal for Electron applications. #### Database Issues
- Check app data directory permissions
- Verify SQLite database integrity
- Clear app data if corrupted
### Debug Mode ### Debug Mode
For detailed build information:
```bash ```bash
DEBUG=electron-builder npx electron-builder build # Enable debug logging
DEBUG=* npm run build:electron:dev
```
## File Structure
```
electron/
├── src/
│ ├── index.ts # Main process entry point
│ ├── preload.ts # Preload script
│ └── setup.ts # App setup and configuration
├── assets/ # App icons and resources
├── package.json # Electron-specific dependencies
├── electron-builder.config.json # Build configuration
└── tsconfig.json # TypeScript configuration
``` ```
## Distribution ## Development Workflow
### GitHub Releases 1. **Start Development**
1. Create a new release on GitHub ```bash
2. Upload the built packages as release assets npm run build:electron:dev
3. Users can download and install directly ```
### Package Repositories 2. **Make Changes**
- **Debian/Ubuntu**: Upload `.deb` to repository - Edit source files in `src/`
- **Fedora/CentOS**: Upload `.rpm` to repository - Changes auto-reload in development
- **Arch Linux**: Create PKGBUILD for AUR
### Direct Download 3. **Test Build**
Host the packages on your website for direct download. ```bash
npm run build:electron:test
```
## Cross-Platform Building 4. **Production Build**
```bash
npm run build:electron:prod
```
### Current Support ## Performance Considerations
- **Linux**: Full support (AppImage, deb, rpm)
- **Windows**: Configured but requires Windows build environment
- **macOS**: Configured but requires macOS build environment
### Building for Other Platforms ### Memory Usage
To build for Windows or macOS, you need: - Monitor renderer process memory
- The target platform's build environment - Implement proper cleanup in components
- Platform-specific signing certificates - Use efficient data structures
- Updated build configuration
## Security Considerations ### Startup Time
- Lazy load non-critical modules
- Optimize database initialization
- Minimize synchronous operations
### Code Signing ### Database Performance
For production releases, consider code signing: - Use transactions for bulk operations
- **Linux**: Not required but recommended - Implement proper indexing
- **Windows**: Required for Windows SmartScreen - Monitor query performance
- **macOS**: Required for Gatekeeper
### Package Integrity ## Security Checklist
- Verify package checksums
- Use HTTPS for distribution
- Consider GPG signatures for packages
## Performance Tips - [ ] Content Security Policy configured
- [ ] Auto-updater properly configured
- [ ] Single instance enforcement active
- [ ] Database access properly secured
- [ ] IPC handlers validate input
- [ ] File system access restricted
- [ ] Network requests validated
### Build Optimization ## Deployment
- Use `--dir` flag for faster development builds
- Cache node_modules between builds
- Use CI/CD for automated builds
### Package Size Reduction ### Distribution
- Remove unnecessary dependencies - Windows: `.exe` installer
- Use electron-builder's file filtering - macOS: `.dmg` disk image
- Consider using electron-updater for delta updates - Linux: `.AppImage` or `.deb` package
## Support ### Code Signing
- Windows: Authenticode certificate
- macOS: Developer ID certificate
- Linux: GPG signing (optional)
For build issues: ### Auto-Updates
1. Check the console output for specific errors - Configured for production builds
2. Verify all dependencies are installed - Disabled for development and AppImage
3. Try cleaning and rebuilding - Handles update failures gracefully
4. Check electron-builder documentation
5. Open an issue with build logs
--- ---
**Happy Building! 🚀** **Last Updated**: 2025-01-10
**Version**: 1.0.3-beta
**Status**: Production Ready

30
electron/src/index.ts

@ -10,24 +10,11 @@ import { join } from 'path';
import { ElectronCapacitorApp, setupContentSecurityPolicy, setupReloadWatcher } from './setup'; import { ElectronCapacitorApp, setupContentSecurityPolicy, setupReloadWatcher } from './setup';
// Single instance enforcement // Use Electron's built-in single instance lock
const gotTheLock = app.requestSingleInstanceLock(); const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) { if (!gotTheLock) {
console.log('[Electron] Another instance is already running. Exiting...'); console.log('[Electron] Another instance is already running. Exiting immediately...');
// Show user-friendly dialog before quitting
dialog.showMessageBox({
type: 'info',
title: 'TimeSafari Already Running',
message: 'TimeSafari is already running in another window.',
detail: 'Please use the existing TimeSafari window instead of opening a new one.',
buttons: ['OK']
}).then(() => {
app.quit();
});
// Exit immediately
process.exit(0); process.exit(0);
} }
@ -100,7 +87,7 @@ autoUpdater.on('error', (error) => {
// Initialize our app, build windows, and load content. // Initialize our app, build windows, and load content.
await myCapacitorApp.init(); await myCapacitorApp.init();
// Handle second instance launch (focus existing window) // Handle second instance launch (focus existing window and show dialog)
app.on('second-instance', (event, commandLine, workingDirectory) => { app.on('second-instance', (event, commandLine, workingDirectory) => {
console.log('[Electron] Second instance attempted to launch'); console.log('[Electron] Second instance attempted to launch');
@ -111,6 +98,17 @@ autoUpdater.on('error', (error) => {
mainWindow.restore(); mainWindow.restore();
} }
mainWindow.focus(); mainWindow.focus();
// Show user-friendly dialog to inform about single instance
dialog.showMessageBox(mainWindow, {
type: 'info',
title: 'TimeSafari Already Running',
message: 'TimeSafari is already running in another window.',
detail: 'Please use this existing TimeSafari window instead of opening a new one.',
buttons: ['OK']
}).catch((error) => {
console.error('[Electron] Error showing dialog:', error);
});
} }
}); });

Loading…
Cancel
Save