feat(update): implement auto-update functionality with electron-updater

- Add AppUpdater module with update lifecycle management
- Create UpdateSettings UI component with progress display
- Add Progress UI component based on Radix UI
- Create update Zustand store for state management
- Register update IPC handlers in main process
- Auto-check for updates on production startup
- Add commit documentation for commits 2-6
This commit is contained in:
Haze
2026-02-05 23:36:12 +08:00
Unverified
parent 98a2d9bc83
commit e02cf05baf
13 changed files with 1313 additions and 50 deletions

View File

@@ -0,0 +1,83 @@
# Commit 2: Gateway Refinements
## Summary
Enhance Gateway process management with auto-reconnection, health checks, and improved state management for more robust WebSocket communication.
## Changes
### Electron Main Process
#### `electron/gateway/manager.ts`
- Added `'reconnecting'` state to `GatewayStatus`
- Implemented `ReconnectConfig` with exponential backoff strategy
- Added `maxAttempts`, `baseDelay`, `maxDelay` configuration
- New methods:
- `isConnected()` - Check WebSocket connection status
- `restart()` - Stop and start Gateway
- `clearAllTimers()` - Clean up timers on shutdown
- `startHealthCheck()` - Periodic health monitoring
- `checkHealth()` - Manual health check
- Enhanced `handleMessage()` to dispatch JSON-RPC responses and notifications
- Expanded `GatewayManagerEvents` for notification forwarding
#### `electron/gateway/client.ts`
- Extended with new interfaces: `SkillBundle`, `CronTask`, `ProviderConfig`
- Added cron task management methods:
- `listCronTasks()`, `createCronTask()`, `updateCronTask()`, `deleteCronTask()`, `runCronTask()`
- Added provider management methods:
- `listProviders()`, `setProvider()`, `removeProvider()`, `testProvider()`
- Enhanced system calls:
- `getHealth()` now includes `version`
- Added `getVersion()`, `getSkillBundles()`, `installBundle()`
#### `electron/main/ipc-handlers.ts`
- Added `gateway:isConnected`, `gateway:health` IPC handlers
- Added `mainWindow.isDestroyed()` checks before sending events
- Forward new gateway events: `gateway:notification`, `gateway:channel-status`, `gateway:chat-message`
#### `electron/preload/index.ts`
- Added new IPC channels for gateway operations
- Added notification event channels
### React Renderer
#### `src/stores/gateway.ts`
- Added `health: GatewayHealth | null`, `lastError: string | null` to state
- Added `checkHealth()`, `rpc()`, `clearError()` actions
- Enhanced `init()` to listen for error and notification events
#### `src/types/gateway.ts`
- Added `'reconnecting'` to `GatewayStatus` state enum
- Added `version`, `reconnectAttempts` fields
- New interfaces: `GatewayHealth`, `GatewayNotification`, `ProviderConfig`
#### `src/components/common/StatusBadge.tsx`
- Added `'reconnecting'` status with warning variant
## Technical Details
### Reconnection Strategy
- Exponential backoff: `delay = min(baseDelay * 2^attempt, maxDelay)`
- Default: 1s base delay, 30s max delay, 10 max attempts
- Automatic reconnection on unexpected disconnection
- Manual control via `shouldReconnect` flag
### Health Check
- Periodic ping/pong via JSON-RPC `system.health`
- Returns status, uptime, version information
- Triggers reconnection on consecutive failures
### Event Flow
```
Gateway Process -> WebSocket -> GatewayManager -> IPC -> Renderer
|
v
Event Emitter
|
+---------------+---------------+
| | |
status notification channel:status
```
## Version
v0.1.0-alpha (incremental)

View File

@@ -0,0 +1,88 @@
# Commit 3: Setup Wizard
## Summary
Implement a functional multi-step setup wizard for first-run user onboarding, guiding users through environment checks, AI provider configuration, channel connection, and skill selection.
## Changes
### React Renderer
#### `src/pages/Setup/index.tsx`
Complete rewrite with functional implementation:
- **Step 0: Welcome** - Introduction to ClawX
- **Step 1: Runtime Check** - Verify Node.js, OpenClaw, and Gateway status
- **Step 2: Provider Configuration** - Select AI provider and enter API key
- **Step 3: Channel Connection** - Choose messaging channel (WhatsApp, Telegram, etc.)
- **Step 4: Skill Selection** - Toggle predefined skill bundles
- **Step 5: Complete** - Summary of configuration
New components:
- `WelcomeContent` - Welcome message and features overview
- `RuntimeContent` - Environment checks with real Gateway status
- `ProviderContent` - Provider selection with API key input and validation
- `ChannelContent` - Channel type selection with QR code placeholder
- `SkillsContent` - Skill bundle toggles
- `CompleteContent` - Configuration summary
Features:
- Animated transitions using Framer Motion
- Progress indicator with step navigation
- Dynamic `canProceed` state based on step requirements
- API key visibility toggle
- Simulated API key validation
#### `src/stores/settings.ts`
- Added `setupComplete: boolean` to state
- Added `markSetupComplete()` action
- Setup status persisted via Zustand persist middleware
#### `src/App.tsx`
- Added `useLocation` for route tracking
- Added redirect logic: if `setupComplete` is false, navigate to `/setup`
- Fixed `handleNavigate` callback signature for IPC events
## Technical Details
### Setup Flow
```
Welcome -> Runtime -> Provider -> Channel -> Skills -> Complete
| | | | | |
v v v v v v
[Skip] [Check] [Validate] [Select] [Toggle] [Finish]
| | | | | |
+---------+----------+----------+----------+----------+
|
markSetupComplete()
|
Navigate to /
```
### Provider Types
- Anthropic (Claude) - API key starts with `sk-ant-`
- OpenAI (GPT) - API key starts with `sk-`
- Google (Gemini) - Length validation
- Ollama (Local) - No API key required
- Custom - Configurable base URL
### Channel Types
- WhatsApp - QR code connection
- Telegram - Bot token
- Discord - Bot token
- Slack - OAuth/Bot token
- WeChat - QR code connection
### Skill Bundles
- Productivity - Calendar, reminders, notes
- Developer - Code assistance, git operations
- Information - Web search, news, weather
- Entertainment - Music, games, trivia
## UI/UX Features
- Gradient background with glassmorphism cards
- Step progress dots with completion indicators
- Animated page transitions
- Back/Skip/Next navigation
- Toast notifications on completion
## Version
v0.1.0-alpha (incremental)

View File

@@ -0,0 +1,127 @@
# Commit 4: Provider Configuration
## Summary
Implement secure API key storage using Electron's safeStorage API and create a comprehensive provider management UI for configuring AI model providers.
## Changes
### Electron Main Process
#### `electron/utils/secure-storage.ts` (New)
Secure storage utility using Electron's safeStorage:
- `isEncryptionAvailable()` - Check if system keychain is available
- `storeApiKey(providerId, apiKey)` - Encrypt and store API key
- `getApiKey(providerId)` - Decrypt and retrieve API key
- `deleteApiKey(providerId)` - Remove stored API key
- `hasApiKey(providerId)` - Check if key exists
- `listStoredKeyIds()` - List all stored provider IDs
Provider configuration management:
- `saveProvider(config)` - Save provider configuration
- `getProvider(providerId)` - Get single provider
- `getAllProviders()` - Get all providers
- `deleteProvider(providerId)` - Delete provider and key
- `setDefaultProvider(providerId)` - Set default provider
- `getDefaultProvider()` - Get default provider ID
- `getProviderWithKeyInfo(providerId)` - Get provider with masked key
- `getAllProvidersWithKeyInfo()` - Get all providers with key info
Note: Uses dynamic `import('electron-store')` for ESM compatibility.
#### `electron/main/ipc-handlers.ts`
New `registerProviderHandlers()` function with IPC handlers:
- `provider:encryptionAvailable`
- `provider:list` / `provider:get` / `provider:save` / `provider:delete`
- `provider:setApiKey` / `provider:deleteApiKey` / `provider:hasApiKey` / `provider:getApiKey`
- `provider:setDefault` / `provider:getDefault`
- `provider:validateKey` - Basic format validation
#### `electron/preload/index.ts`
Added all provider IPC channels to valid channels list.
### React Renderer
#### `src/stores/providers.ts` (New)
Zustand store for provider management:
- State: `providers`, `defaultProviderId`, `loading`, `error`
- Actions: `fetchProviders`, `addProvider`, `updateProvider`, `deleteProvider`
- Actions: `setApiKey`, `deleteApiKey`, `setDefaultProvider`, `validateApiKey`, `getApiKey`
#### `src/components/settings/ProvidersSettings.tsx` (New)
Provider management UI component:
- `ProvidersSettings` - Main component orchestrating provider list
- `ProviderCard` - Individual provider display with actions
- `AddProviderDialog` - Modal for adding new providers
Features:
- Provider type icons (Anthropic, OpenAI, Google, Ollama, Custom)
- Masked API key display (first 4 + last 4 characters)
- Set default provider
- Enable/disable providers
- Edit/delete functionality
- API key validation on add
#### `src/pages/Settings/index.tsx`
- Added AI Providers section with `ProvidersSettings` component
- Added `Key` icon import
## Technical Details
### Security Architecture
```
Renderer Process Main Process
| |
| provider:setApiKey |
|--------------------------------->|
| | safeStorage.encryptString()
| | |
| | v
| | System Keychain
| | |
| | electron-store
| | (encrypted base64)
| |
| provider:getApiKey |
|--------------------------------->|
| | safeStorage.decryptString()
|<---------------------------------|
| (plaintext) |
```
### Provider Configuration Schema
```typescript
interface ProviderConfig {
id: string;
name: string;
type: 'anthropic' | 'openai' | 'google' | 'ollama' | 'custom';
baseUrl?: string;
model?: string;
enabled: boolean;
createdAt: string;
updatedAt: string;
}
```
### Key Validation Rules
- Anthropic: Must start with `sk-ant-`
- OpenAI: Must start with `sk-`
- Google: Minimum 20 characters
- Ollama: No key required
- Custom: No validation
### ESM Compatibility
electron-store v10+ is ESM-only. Solution: dynamic imports in main process.
```typescript
let store: any = null;
async function getStore() {
if (!store) {
const Store = (await import('electron-store')).default;
store = new Store({ /* config */ });
}
return store;
}
```
## Version
v0.1.0-alpha (incremental)

View File

@@ -0,0 +1,124 @@
# Commit 5: Channel Connection Flows
## Summary
Implement comprehensive channel management UI with multi-platform support, including QR code-based connection for WhatsApp/WeChat and token-based connection for Telegram/Discord/Slack.
## Changes
### React Renderer
#### `src/pages/Channels/index.tsx`
Complete rewrite with enhanced functionality:
**Main Components:**
- `Channels` - Main page with channel list, stats, and add dialog
- `ChannelCard` - Individual channel display with connect/disconnect/delete
- `AddChannelDialog` - Multi-step channel addition flow
**Features:**
- Channel statistics (Total, Connected, Disconnected)
- Gateway status warning when not running
- Supported channel type grid for quick add
- Connection-type specific flows:
- QR Code: WhatsApp, WeChat
- Token: Telegram, Discord, Slack
**AddChannelDialog Flow:**
1. Select channel type
2. View connection instructions
3. For QR: Generate and display QR code
4. For Token: Enter bot token
5. Optionally name the channel
6. Confirm and add
**Channel Info Configuration:**
```typescript
const channelInfo: Record<ChannelType, {
description: string;
connectionType: 'qr' | 'token' | 'oauth';
instructions: string[];
tokenLabel?: string;
docsUrl?: string;
}>
```
#### `src/stores/channels.ts`
Enhanced channel store with new actions:
- `addChannel(params)` - Add new channel with type, name, token
- `deleteChannel(channelId)` - Remove channel
- `requestQrCode(channelType)` - Request QR code from Gateway
- `clearError()` - Clear error state
Improved error handling:
- Graceful fallback when Gateway unavailable
- Local channel creation for offline mode
#### `src/types/channel.ts`
No changes - existing types sufficient.
### Electron Main Process
#### `electron/utils/store.ts`
- Converted to dynamic imports for ESM compatibility
- All functions now async
#### `electron/main/window.ts`
- Converted to dynamic imports for ESM compatibility
- `getWindowState()` and `saveWindowState()` now async
## Technical Details
### Channel Connection Architecture
```
AddChannelDialog
|
+-- QR Flow
| |
| v
| requestQrCode() --> Gateway --> WhatsApp/WeChat API
| | |
| v v
| Display QR <-- qrCode string <-- QR Generated
| |
| v
| User Scans --> Device Confirms --> channel:status event
|
+-- Token Flow
|
v
Enter Token --> addChannel() --> Gateway --> Bot API
| |
v v
Validate <-- success/error <-- Connection Attempt
```
### Channel Types Configuration
| Type | Connection | Token Label | Docs |
|------|------------|-------------|------|
| WhatsApp | QR Code | - | WhatsApp FAQ |
| Telegram | Token | Bot Token | BotFather Docs |
| Discord | Token | Bot Token | Developer Portal |
| Slack | Token | Bot Token (xoxb-) | Slack API |
| WeChat | QR Code | - | - |
### Connection Instructions
Each channel type provides step-by-step instructions:
- WhatsApp: Open app > Settings > Linked Devices > Scan
- Telegram: @BotFather > /newbot > Copy token
- Discord: Developer Portal > Application > Bot > Token
- Slack: API Apps > Create App > OAuth > Install
### UI Components Used
- `Card`, `Button`, `Input`, `Label` - Base components
- `Separator` - Visual dividers
- `StatusBadge` - Connection status
- `LoadingSpinner` - Loading states
- Lucide icons: Plus, Radio, RefreshCw, Power, QrCode, etc.
### Error Handling
- Gateway offline: Create local channel, show warning
- Connection failed: Display error on ChannelCard
- Invalid token: Show validation error in dialog
## Version
v0.1.0-alpha (incremental)

View File

@@ -0,0 +1,171 @@
# Commit 6: Auto-Update Functionality
## Summary
Integrate electron-updater for automatic application updates with a comprehensive UI for checking, downloading, and installing updates.
## Changes
### Electron Main Process
#### `electron/main/updater.ts` (New)
Complete auto-update module:
**AppUpdater Class:**
- Extends EventEmitter for event-based notifications
- Configures electron-updater settings
- Manages update lifecycle
**Methods:**
- `setMainWindow(window)` - Set window for IPC
- `getStatus()` - Get current update status
- `checkForUpdates()` - Check for available updates
- `downloadUpdate()` - Download available update
- `quitAndInstall()` - Install update and restart
- `setChannel(channel)` - Set update channel (stable/beta/dev)
- `setAutoDownload(enable)` - Configure auto-download
- `getCurrentVersion()` - Get app version
**Update Status:**
- `idle` - No update activity
- `checking` - Checking for updates
- `available` - Update available
- `not-available` - Already on latest
- `downloading` - Download in progress
- `downloaded` - Ready to install
- `error` - Update failed
**IPC Handlers (registerUpdateHandlers):**
- `update:status` - Get current status
- `update:version` - Get app version
- `update:check` - Trigger update check
- `update:download` - Start download
- `update:install` - Install and restart
- `update:setChannel` - Change update channel
- `update:setAutoDownload` - Toggle auto-download
**Events forwarded to renderer:**
- `update:status-changed`
- `update:checking`
- `update:available`
- `update:not-available`
- `update:progress`
- `update:downloaded`
- `update:error`
#### `electron/main/index.ts`
- Import and register update handlers
- Auto-check for updates in production (10s delay)
#### `electron/preload/index.ts`
- Added all update IPC channels
### React Renderer
#### `src/stores/update.ts` (New)
Zustand store for update state:
- State: `status`, `currentVersion`, `updateInfo`, `progress`, `error`, `isInitialized`
- Actions: `init`, `checkForUpdates`, `downloadUpdate`, `installUpdate`, `setChannel`, `setAutoDownload`, `clearError`
- Listens for all update events from main process
#### `src/components/settings/UpdateSettings.tsx` (New)
Update UI component:
- Current version display
- Status indicator with icon
- Status text description
- Action buttons (Check/Download/Install/Retry)
- Download progress bar with transfer stats
- Update info card (version, date, release notes)
- Error details display
**Progress Display:**
- Transferred / Total bytes
- Transfer speed (bytes/second)
- Progress percentage bar
#### `src/components/ui/progress.tsx` (New)
Radix UI Progress component for download visualization.
#### `src/pages/Settings/index.tsx`
- Replaced manual update section with `UpdateSettings` component
- Added `useUpdateStore` for version display
- Removed unused state and effect hooks
## Technical Details
### Update Flow
```
App Start (Production)
|
v
10s Delay
|
v
checkForUpdates()
|
+-- No Update --> status: 'not-available'
|
+-- Update Found --> status: 'available'
|
v
[User Action]
|
v
downloadUpdate()
|
v
status: 'downloading'
progress events
|
v
status: 'downloaded'
|
v
[User Action]
|
v
quitAndInstall()
|
v
App Restarts
```
### electron-updater Configuration
```typescript
autoUpdater.autoDownload = false; // Manual download trigger
autoUpdater.autoInstallOnAppQuit = true; // Install on quit
autoUpdater.logger = customLogger; // Console logging
```
### Update Channels
- `stable` - Production releases
- `beta` - Pre-release testing
- `dev` - Development builds
### Progress Info Interface
```typescript
interface ProgressInfo {
total: number; // Total bytes
delta: number; // Bytes since last event
transferred: number; // Bytes downloaded
percent: number; // 0-100
bytesPerSecond: number; // Transfer speed
}
```
### UI States
| Status | Icon | Action Button |
|--------|------|---------------|
| idle | RefreshCw (gray) | Check for Updates |
| checking | Loader2 (spin, blue) | Checking... (disabled) |
| available | Download (green) | Download Update |
| downloading | Download (pulse, blue) | Downloading... (disabled) |
| downloaded | CheckCircle2 (green) | Install & Restart |
| error | AlertCircle (red) | Retry |
| not-available | CheckCircle2 (green) | Check for Updates |
## Dependencies
- electron-updater ^6.3.9 (already installed)
- @radix-ui/react-progress ^1.1.1 (already installed)
## Version
v0.1.0-alpha (incremental)

View File

@@ -11,6 +11,7 @@
* [commit_3] Setup wizard - Multi-step onboarding flow with provider, channel, skill selection
* [commit_4] Provider configuration - Secure API key storage, provider management UI
* [commit_5] Channel connection flows - Multi-channel support with QR/token connection UI
* [commit_6] Auto-update functionality - electron-updater integration with UI
### Plan:
1. ~~Initialize project structure~~
@@ -18,7 +19,7 @@
3. ~~Implement Setup wizard with actual functionality~~
4. ~~Add Provider configuration (API Key management)~~
5. ~~Implement Channel connection flows~~
6. Add auto-update functionality
6. ~~Add auto-update functionality~~
7. Packaging and distribution setup
## Version Milestones