Chattydesk Architecture & Performance Benchmark: Universal OpenRouter Chat Client Deep Dive

Live web application screenshot and interface of Chattydesk - Universal Model Chat Client

Modern AI development demands frictionless access to diverse Large Language Models (LLMs). Developers routinely juggle ChatGPT, Claude, Gemini, and open-source endpoints—each with distinct APIs, billing, and interfaces. Chattydesk solves this fragmentation by delivering a Universal OpenRouter chat client that aggregates 400+ models into a unified interface, deployable as both a native cross-platform Electron AI desktop app and a lightweight static web application.

Key Takeaways

  • Dual-Target Architecture: Single React/Vite codebase compiles to both Hash-routed Electron desktop apps and History-routed static web builds.
  • Unified Model Access: Proxies 400+ OpenRouter models via a centralized Django/FastAPI backend with JWT session management.
  • Mid-Conversation Model Switching: Preserves full message history while dynamically swapping active model IDs and context windows.
  • Custom API Key Overrides: Users inject personal OpenRouter keys client-side, eliminating server-side credit dependencies.
  • Autonomous Agent Ready: Exposes /.well-known/ard.json, /poppy.json, and /llms.txt for agent discovery.
Live Project Access: https://chatty.nevatal.id

Live web application screenshot and interface of Chattydesk - Universal Model Chat Client
Live web application interface of Chattydesk – Universal Model Chat Client (https://chatty.nevatal.id)

The Engineering Challenge: Why Chattydesk Was Architected

The core problem was context switching overhead. Prior to Chattydesk, evaluating a prompt across Claude 3.5 Sonnet, GPT-4o, and Llama 3.1 required three browser tabs, three billing accounts, and manual copy-pasting of context. Existing third-party clients often locked users to single providers or lacked desktop parity.

Chattydesk’s architecture targets three constraints simultaneously:

  1. Provider Abstraction: Normalize 400+ heterogeneous model endpoints behind OpenRouter’s unified API schema.
  2. Runtime Portability: Deliver identical UX in browser (static hosting) and OS-native windows (Electron) from one codebase.
  3. Data Sovereignty: Keep conversation history portable via centralized PostgreSQL/SQLite backend while allowing client-side API key injection for zero-trust cost control.

Core Architecture & Technical Stack Deep-Dive

Monorepo Strategy: Dual Build Profiles

The frontend resides in a single React 18 + Vite 5 codebase. Vite’s defineConfig splits compilation into two distinct entry points:

// vite.config.ts (simplified)
export default defineConfig(({ mode }) => ({
  plugins: [react()],
  build: {
    rollupOptions: {
      input: mode === 'electron' ? 'index.html' : 'index.html', // Same entry, different base
      output: { dir: mode === 'electron' ? 'dist-electron' : 'dist-web' }
    },
    base: mode === 'electron' ? './' : '/' // Relative paths for Electron file:// protocol
  }
}));

Routing Divergence: The web build uses HTML5 History API (/chat, /settings) for SEO-friendly URLs on Vercel/Netlify. The Electron build switches to Hash routing (#/chat) to function under the file:// protocol without a local server.

Backend: Django REST Framework + FastAPI Hybrid

The centralized backend serves three roles:

  • Auth Gateway: Issues short-lived JWT access tokens (15 min) and long-lived refresh tokens (7 days) stored in HttpOnly; Secure; SameSite=Lax cookies.
  • OpenRouter Proxy: Forwards POST /api/v1/chat/completions to OpenRouter, injecting server-side fallback keys if user overrides are absent.
  • Persistence Layer: PostgreSQL (production) / SQLite (dev) stores users, conversations, messages, and encrypted API key overrides via django-cryptography.

FastAPI mounts alongside Django for high-throughput streaming endpoints (/api/v1/stream), leveraging asyncio and httpx.AsyncClient to maintain persistent connections to OpenRouter without blocking Django’s WSGI workers.

Database Schema & Context Window Management

Conversations use a polymorphic context_window integer field (default 4096, max 128k) allowing per-chapter token budgeting. The Message model stores token_count and cost_usd per turn, enabling real-time usage dashboards.

class Message(models.Model):
    conversation = ForeignKey(Conversation, on_delete=CASCADE)
    role = CharField(choices=[('user','user'),('assistant','assistant'),('system','system')])
    content = TextField()
    model_id = CharField(max_length=128)  # e.g., 'anthropic/claude-3.5-sonnet'
    token_count = IntegerField(default=0)
    cost_usd = DecimalField(max_digits=10, decimal_places=6, default=0)
    created_at = DateTimeField(auto_now_add=True)

Electron Main Process & IPC Bridge

The Electron shell (electron/main.ts) spawns a hidden BrowserWindow with nodeIntegration: false and contextIsolation: true. A preload script exposes a minimal contextBridge API:

// preload.js
contextBridge.exposeInMainWorld('electronAPI', {
  minimize: () => ipcRenderer.send('window:minimize'),
  maximize: () => ipcRenderer.send('window:maximize'),
  close: () => ipcRenderer.send('window:close'),
  setTitle: (title) => ipcRenderer.send('window:set-title', title),
  // No direct Node.js or file system exposure
});

This satisfies security audits while enabling native window controls and custom title bars matching the web app’s Tailwind CSS design system.

Key Features Breakdown & Practical Benefits

Compare AI: Side-by-Side Multi-Model Arena

The /compare route broadcasts a single user prompt to 2–4 selected models in parallel via Promise.allSettled. Each stream renders into an independent component backed by a shared AbortController for unified cancellation. Latency variance across models is visualized in real-time, enabling prompt engineers to select the optimal cost/quality frontier.

Mid-Conversation Model Switching

Users can swap the active model_id at any message turn. The frontend sends the full message history (truncated to the new model’s context_window) with the new model_id to the proxy. No conversation forking occurs—the original thread retains continuity, and the UI displays a inline at the switch point.

Custom OpenRouter API Key Overrides

In /settings, users paste a personal OpenRouter key. The frontend encrypts it via Web Crypto API (AES-GCM) before sending to PATCH /api/v1/user/api-key. The backend stores only the ciphertext. On chat requests, the proxy checks user.api_key_override first; if present, it decrypts server-side and forwards as Authorization: Bearer to OpenRouter. This decouples user spend from operator infrastructure.

Automatic Free-Model Failover

When OpenRouter returns 402 Payment Required or 429 Rate Limited, the client automatically retries the request against a curated list of free-tier models (e.g., meta-llama/llama-3.1-8b-instruct:free). The fallback is transparent—the response renders normally with a subtle badge.

Autonomous Agent Discovery Endpoints

Static files served at root enable machine-readable capability advertisement:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *