Skip to content

Backend Architecture

The Rust backend is compiled into a single native binary (the Tauri application). It owns all system-level resources: processes, file handles, sockets, and the database. The frontend has no direct access to any of these — everything is mediated through Tauri commands and events.

Magia uses Tokio as its async runtime (features: process, io-util, sync, time, rt, net). Blocking work (filesystem scans, database writes, PTY operations) is offloaded to tokio::task::spawn_blocking to avoid stalling the async executor.

ModuleDescription
agentSpawns agent CLI processes, manages running agents (SharedAgentManager), handles permission requests (SharedPermissionManager), start_permission_listener Unix socket
hooksReceives hook events from agent processes over a Unix socket, normalises them into AgentEvent structs, maintains the live sessions map (SharedLiveSessions)
session_cacheIn-memory + on-disk cache of all discovered sessions (ActiveSession); incremental sync, PID health checks, dead session cleanup
discoveryScans provider session directories (Claude, Gemini, Codex) and project metadata; extracts first prompts, models, costs; submodules: types, provider, project, session, commands
transcriptReads and streams JSONL transcript files for past sessions
observerBackground LLM calls to generate session titles and summaries from transcripts
reflectorBackground process that distills long-term memory observations from session data
ModuleDescription
ptyPTY lifecycle management using portable-pty; creates PTY pairs, spawns processes inside them, bridges PTY I/O to Tauri events
ide_serverWebSocket server that implements the Claude Code IDE protocol; allows VS Code / other editors to connect and receive session events
ModuleDescription
provider_managerRegistry of all supported provider CLIs; detects installed binaries, manages provider state
provider_configReads and writes provider configuration files (e.g. ~/.claude/settings.json)
provider_accountProvider account management (connect, disconnect, list)
provider_permissionsTool permission model per provider account
provider_instructionsCustom system prompt / instruction injection per provider
claude_compatClaude Code CLI compatibility layer (session format, hook protocol)
codex_compatOpenAI Codex CLI compatibility layer
gemini_compatGoogle Gemini CLI compatibility layer
llmLow-level LLM HTTP client; submodules: binary, cli, provider, spawn, types
ModuleDescription
watchersWatcherManager (provider config files), ActiveSessionWatcher (hook-driven, watches active session working dirs), ProviderSessionWatcher (Gemini + Codex session dirs), ThemeWatcher (~/.magia/themes/)
projectsProject directory management and metadata
workspacesNamed workspaces (groups of project paths)
filesFile read/write commands exposed to the frontend
searchFull-text search across session transcripts and files
symbolsSymbol extraction (ctags-style) for the context extractor
gitGit integration — branch info, status, diff
resourcesStatic resource access (bundled assets)
ModuleDescription
lspLanguage Server Protocol client — bridges LSP responses to the frontend editor
keybindingsPersists and loads user keybinding customisations
ModuleDescription
otelgRPC OpenTelemetry collector (Unix socket, with HTTP/TCP fallback); stores metrics in SharedMetricsStore
audit_logStructured audit log for user-facing events
statsPer-session and per-project statistics aggregation
costsToken cost calculation for different models
event_normalizerNormalises raw provider events into a unified AgentEvent shape
ModuleDescription
sttSpeech-to-text pipeline: audio capture → Whisper inference via whisper-rs
parakeetAlternative STT backend using ONNX Runtime (ort) and the Parakeet model
parakeet_managerManages Parakeet model download and lifecycle
model_managerGeneric model download and cache management
ModuleDescription
settingsReads and writes settings.json; exposes SharedAppSettings (Arc-wrapped, async-Mutex)
dbSQLite connection management, WAL mode configuration, and refinery migration runner
pathsCentral path resolution — all app directories go through this module
cliUnix socket listener for CLI commands from magia-hook-handler and the magia CLI binary
cli_installInstalls / uninstalls the magia symlink in ~/.local/bin or /usr/local/bin
themesCustom theme loading from ~/.magia/themes/
pluginsMCP plugin management (install, enable, disable, list)
fontsSystem font enumeration for the editor
extensionsExtension / plugin marketplace integration
hook_registryRegistry of user-defined Claude Code hooks
traySystem tray icon and menu management
tray_panelFloating tray panel window (mini session launcher)
ModuleDescription
authOAuth flow orchestration (GitHub App + Google OAuth)
api_clientHTTP client wrapper for the Magia API (MAGIA_API_URL)
cloudCloud feature gate (is_cloud_build())
licenseLicense entitlement checks
ModuleDescription
ipcCross-platform local socket abstraction (interprocess crate); Unix file sockets on macOS/Linux, named pipes on Windows

All background services are started by start_background_sync(), which is called by the frontend after onboarding is complete. The function is protected by an atomic flag and is safe to call multiple times.

Services start in this order:

  1. Hook listener — Unix socket that receives lifecycle events from agent CLIs.
  2. CLI listener — Unix socket for commands from the magia CLI and magia-hook-handler binary.
  3. Permission listener — Unix socket for tool permission requests from agents.
  4. OTel gRPC collector — gRPC server on a Unix socket; falls back to HTTP/TCP if the socket cannot be created.
  5. File watchersWatcherManager, ActiveSessionWatcher, ProviderSessionWatcher, ThemeWatcher.
  6. Session cache sync — initial incremental sync runs immediately; periodic sync runs on a configurable interval (default 10 minutes, minimum 1 minute).
  7. IDE integration server — WebSocket server for the Claude Code VS Code extension.
  8. Observer — background LLM title/summary generation.
  9. Reflector — background memory distillation.
  10. Claude status polling — fetches the Claude.ai status page periodically.
  11. PID health check — runs every 5 seconds; marks sessions with dead PIDs as historical.
  12. Orphaned session cleanup — runs every 60 seconds (after a 30-second initial delay); removes sessions whose JSONL files no longer exist.

The database lives at {data_dir}/magia.db. It is opened in WAL mode with a 5-second busy timeout and NORMAL synchronous mode. This allows the magia-hook-handler process to write to the same database concurrently without blocking the main process.

Schema migrations are managed by refinery and embedded at compile time from the src-tauri/migrations/ directory:

MigrationDescription
V1__initial_schema.sqlCore tables: sessions, projects
V2__add_icon_image.sqlProject icon storage
V3__add_include_subdirs.sqlSubdirectory inclusion flag on projects
V4__add_git_repos.sqlGit repository metadata

src-tauri/src/bin/magia-hook-handler.rs is a separate binary (magia-hook-handler) that is installed as a Claude Code hook. When the agent CLI fires a hook event, it executes magia-hook-handler, which serialises the event and delivers it to the main Magia process via the hook Unix socket. This design keeps the hook path lightweight and avoids spawning a new Magia process for every event.