# @ai-assistant/desktop

Native desktop application for AI Terminal Assistant - built with Tauri for cross-platform support.

## 📦 Installation

```bash
# 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](https://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

```bash
# 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

```bash
# 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`:

```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

```typescript
// 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);
});
```

```rust
// 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

```typescript
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

```typescript
import { register } from '@tauri-apps/api/globalShortcut';

// Register global hotkey
await register('CommandOrControl+Shift+A', () => {
  console.log('Shortcut triggered!');
  window.show();
});
```

### File Operations

```typescript
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

```typescript
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
```bash
# 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

```rust
// 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

```yaml
# .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

```bash
# 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

```bash
# Enable dev tools
pnpm dev -- --features devtools

# Rust debugging
RUST_LOG=debug pnpm dev

# WebView debugging
# Press F12 in the app window
```

### Logging

```rust
// Rust logging
use log::{info, error};

info!("Application started");
error!("Failed to load: {}", error);
```

```typescript
// 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](../../LICENSE) for details.

## 🔗 Links

- [Main Repository](https://github.com/username/ai-terminal-assistant)
- [Tauri Documentation](https://tauri.app/v1/guides/)
- [Release Downloads](https://github.com/username/ai-terminal-assistant/releases)