68ab6a2016
将 web 和 desktop 的重复代码抽取到 @ai-assistant/ui 包: - 添加可配置的 API 客户端 (configureApiClient) - 迁移共享组件: ChatMessage, ChatInput, Sidebar, FileBrowser, ConfigPanel - 迁移共享 hook: useChat - 添加 responsive prop 支持响应式布局 - 更新 web/desktop 依赖并删除重复代码
@ai-assistant/desktop
Native desktop application for AI Terminal Assistant - built with Tauri for cross-platform support.
📦 Installation
# Install dependencies
pnpm install
# Development
pnpm dev
# Build for current platform
pnpm build
# Build for all platforms
pnpm build:all
🌟 Features
- Native Performance - Built with Rust and Tauri for speed
- Cross-Platform - Windows, macOS, and Linux support
- Small Bundle Size - ~10MB installer, ~30MB installed
- System Integration - Native menus, notifications, and tray
- Secure by Default - Sandboxed with minimal permissions
- Auto Updates - Built-in update mechanism
- Local Storage - SQLite for offline data
- WebView Based - Modern web UI with native wrapper
- Global Shortcuts - System-wide keyboard shortcuts
- File System Access - Native file dialogs and operations
🏗️ Architecture
src-tauri/
├── src/
│ ├── main.rs # Main entry point
│ ├── app.rs # Application setup
│ ├── commands/ # Tauri commands
│ │ ├── chat.rs # Chat operations
│ │ ├── file.rs # File operations
│ │ ├── system.rs # System integration
│ │ └── window.rs # Window management
│ ├── menu.rs # Native menu setup
│ ├── tray.rs # System tray
│ ├── updater.rs # Auto-updater logic
│ ├── store.rs # Local data storage
│ └── utils/ # Utility functions
├── Cargo.toml # Rust dependencies
├── tauri.conf.json # Tauri configuration
└── icons/ # App icons
src/
├── App.tsx # React app entry
├── components/ # UI components (shared with web)
├── hooks/ # Custom hooks
├── services/ # Desktop-specific services
│ ├── ipc.ts # Tauri IPC communication
│ ├── storage.ts # Local storage
│ └── shortcuts.ts # Keyboard shortcuts
└── styles/ # Desktop-specific styles
🚀 Quick Start
Prerequisites
- Node.js 18+ and pnpm
- Rust 1.70+ (install from rustup.rs)
- Platform Tools:
- Windows: Visual Studio C++ Build Tools
- macOS: Xcode Command Line Tools
- Linux:
build-essential,libwebkit2gtk-4.0-dev,libssl-dev
Development Setup
# Clone repository
git clone <repository-url>
cd ai-terminal-assistant/packages/desktop
# Install dependencies
pnpm install
# Start development server
pnpm dev
# App will open automatically with hot reload enabled
Building for Production
# Build for current platform
pnpm build
# Build for specific platform
pnpm build:windows
pnpm build:mac
pnpm build:linux
# Build universal binary for macOS
pnpm build:mac-universal
# Build and sign (requires certificates)
pnpm build:signed
🖥️ Platform Features
Windows
- Installer Types: MSI, NSIS, Portable
- Auto-start on system boot
- Windows Store distribution ready
- Native notifications
- Jump list integration
macOS
- Formats: DMG, App Bundle
- Code signing and notarization
- macOS App Store ready
- Touch Bar support
- Native menu bar
Linux
- Packages: AppImage, Deb, RPM
- System tray support
- Desktop entry creation
- Snap/Flatpak ready
- Wayland/X11 compatible
⚙️ Configuration
Tauri Configuration
src-tauri/tauri.conf.json:
{
"package": {
"productName": "AI Terminal Assistant",
"version": "1.0.0"
},
"tauri": {
"allowlist": {
"all": false,
"shell": {
"execute": true,
"open": true
},
"fs": {
"all": true,
"scope": ["$HOME/**", "$RESOURCE/**"]
},
"http": {
"all": true,
"scope": ["http://localhost/*", "https://api.anthropic.com/*"]
},
"notification": {
"all": true
},
"globalShortcut": {
"all": true
}
},
"windows": [{
"title": "AI Terminal Assistant",
"width": 1200,
"height": 800,
"resizable": true,
"fullscreen": false
}],
"systemTray": {
"iconPath": "icons/icon.png",
"menuOnLeftClick": false
},
"updater": {
"active": true,
"endpoints": ["https://updates.example.com/check"]
}
}
}
🔌 Tauri Commands
IPC Communication
// Frontend (TypeScript)
import { invoke } from '@tauri-apps/api/tauri';
// Call Rust command
const result = await invoke('send_message', {
message: 'Hello from frontend'
});
// Listen to events
import { listen } from '@tauri-apps/api/event';
const unlisten = await listen('chat-update', (event) => {
console.log('New message:', event.payload);
});
// Backend (Rust)
#[tauri::command]
fn send_message(message: String) -> Result<String, String> {
// Process message
Ok(format!("Received: {}", message))
}
// Emit events
app.emit_all("chat-update", Payload {
message: "New update"
}).unwrap();
🎨 Native Features
System Tray
import { createTray } from './services/tray';
const tray = await createTray({
icon: '/icons/tray.png',
menu: [
{ label: 'Show', action: () => showWindow() },
{ label: 'Hide', action: () => hideWindow() },
{ separator: true },
{ label: 'Quit', action: () => app.quit() }
]
});
Global Shortcuts
import { register } from '@tauri-apps/api/globalShortcut';
// Register global hotkey
await register('CommandOrControl+Shift+A', () => {
console.log('Shortcut triggered!');
window.show();
});
File Operations
import { open, save } from '@tauri-apps/api/dialog';
import { readTextFile, writeFile } from '@tauri-apps/api/fs';
// Open file dialog
const selected = await open({
multiple: false,
filters: [{
name: 'Text',
extensions: ['txt', 'md']
}]
});
// Read file
const content = await readTextFile(selected);
// Save file dialog
const savePath = await save({
filters: [{ name: 'Text', extensions: ['txt'] }]
});
await writeFile(savePath, 'content');
Notifications
import { sendNotification } from '@tauri-apps/api/notification';
await sendNotification({
title: 'AI Assistant',
body: 'Task completed successfully!',
icon: '/icons/icon.png'
});
🔐 Security
Permissions
- Minimal permission model
- Scoped file system access
- Controlled shell execution
- CSP headers enforced
Code Signing
# macOS
codesign --deep --force --verify --verbose \
--sign "Developer ID Application: Your Name" \
target/release/bundle/osx/AI\ Terminal\ Assistant.app
# Windows (using SignTool)
signtool sign /a /tr http://timestamp.digicert.com \
/td SHA256 /fd SHA256 \
target/release/bundle/msi/AI_Terminal_Assistant.msi
🚢 Distribution
Auto Updates
// src-tauri/src/updater.rs
use tauri::updater::builder::UpdateBuilder;
pub fn check_for_updates(app: &tauri::App) {
let update = UpdateBuilder::new()
.current_version(&app.package_info().version)
.url("https://updates.example.com/check")
.build()
.unwrap();
if update.should_update {
update.download_and_install().unwrap();
}
}
GitHub Releases
# .github/workflows/release.yml
name: Release
on:
push:
tags: ['v*']
jobs:
release:
strategy:
matrix:
platform: [macos-latest, ubuntu-latest, windows-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- uses: tauri-apps/tauri-action@v0
with:
tagName: v__VERSION__
releaseName: 'v__VERSION__'
releaseBody: 'See CHANGELOG.md'
releaseDraft: true
prerelease: false
🧪 Testing
# Unit tests (Rust)
cd src-tauri
cargo test
# Integration tests
pnpm test:integration
# E2E tests with WebDriver
pnpm test:e2e
📊 Performance
Optimization Tips
- Lazy Loading - Load features on demand
- IPC Batching - Batch multiple commands
- Asset Optimization - Compress images/fonts
- Memory Management - Clean up listeners
- Background Tasks - Use Web Workers
Benchmarks
| Metric | Value |
|---|---|
| Startup Time | < 500ms |
| Memory Usage | ~50MB idle |
| Bundle Size | ~10MB compressed |
| CPU Usage | < 5% idle |
🐛 Debugging
Development Tools
# Enable dev tools
pnpm dev -- --features devtools
# Rust debugging
RUST_LOG=debug pnpm dev
# WebView debugging
# Press F12 in the app window
Logging
// Rust logging
use log::{info, error};
info!("Application started");
error!("Failed to load: {}", error);
// Frontend logging
import { info, error } from '@tauri-apps/api/log';
await info('Application started');
await error(`Failed to load: ${error}`);
🤝 Contributing
See the main repository's contributing guide for details.
📄 License
MIT License - see LICENSE for details.