Files
ai-terminal-assistant/packages/desktop
kurihada 48a11ff077 feat: 添加 :new 系统命令创建新会话
- Core: 新增 :new/:n 命令返回 new_session action
- Server: 处理 new_session action 创建新会话
- UI: useChat 添加 onSessionSwitch 回调
- Web/Desktop: ChatPage 和 App 实现会话切换逻辑
2025-12-17 19:36:47 +08:00
..
2025-12-12 13:19:00 +08:00
2025-12-12 13:19:00 +08:00
2025-12-12 14:28:34 +08:00
2025-12-12 15:31:38 +08:00
2025-12-12 13:19:00 +08:00
2025-12-12 13:19:00 +08:00

@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

  1. Lazy Loading - Load features on demand
  2. IPC Batching - Batch multiple commands
  3. Asset Optimization - Compress images/fonts
  4. Memory Management - Clean up listeners
  5. 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.