Skip to main content

Elements

Mountain

The Rust + Tauri native backend for Land: IPC dispatcher, Vine gRPC server, Environment providers, and Cocoon process orchestration.

Mountain is the primary Tauri application and native Rust backend for the Land code editor. Mountain:

  • Implements every abstract trait from Common
  • Hosts the gRPC server
  • Manages application state
  • Dispatches Tauri commands
  • Orchestrates sidecar processes

Table of Contents

  1. Overview
  2. Application Lifecycle
  3. Module Architecture
  4. ApplicationState
  5. Environment and Providers
  6. Tauri Command System
  7. gRPC Service (Vine)
  8. Process Management
  9. IPC and Event System
  10. Cache System
  11. Extension Management
  12. Related Documentation

sequenceDiagram
    participant M as Mountain main()
    participant TB as Tauri Builder
    participant AS as AppState
    participant ME as MountainEnvironment
    participant ART as AppRuntime (Echo)
    participant BK as Background Task
    participant GRPC as gRPC Server (Vine)
    participant COCOON as Cocoon (Node.js)
    participant AIR as Air Daemon

    M->>TB: Tauri::Builder::default()
    TB->>AS: Create AppState (RwLock state)
    TB->>ME: Create MountainEnvironment (24+ providers)
    TB->>ART: Create AppRuntime (Echo scheduler)
    TB->>BK: Spawn background init task

    Note over BK: Post-setup initialization
    BK->>BK: InitializeConfiguration()
    BK->>BK: ExtensionManagement::scan()
    BK->>GRPC: Start gRPC server on port 50051
    BK->>COCOON: Spawn bootstrap-fork.js
    COCOON-->>BK: $initialHandshake gRPC notification
    BK->>COCOON: Send InitData payload
    BK->>AIR: Spawn Air daemon (optional)
    AIR-->>BK: Connect gRPC notification
    Note over M,AIR: System ready for user interaction

Overview 📋

Mountain is a Rust binary built with Tauri v2 and tonic gRPC:

  • It is the single native process that owns all OS-level capabilities (file system, terminal PTY, clipboard, dialogs)
  • It coordinates the Cocoon extension host and Air background daemon
AttributeValue
LanguageRust (edition 2024)
FrameworkTauri v2
gRPCtonic + prost
DependenciesCommon, Echo, Mist, tauri, tauri-plugin-dialog, tauri-plugin-fs, tonic, prost, keyring, portable-pty, tokio
SidecarsCocoon (Node.js), Air (Rust daemon)

Application Lifecycle 🔄

Startup Sequence 🚀

fn main()
    |
    v
1. Tauri::Builder::default() created
    |
    v
2. .setup(|app| {
    a. Create AppState (thread-safe state container)
    b. Create MountainEnvironment (implements all Common traits)
    c. Create AppRuntime (Echo-backed execution engine)
    d. Spawn tokio background task for post-setup init
    e. Return Ok(())
   })
    |
    v
3. Post-setup background task:
    |
    +---> InitializeConfiguration()
    |       - Read settings.json files from disk
    |       - Populate AppState with configuration values
    |
    +---> ExtensionManagement::scan()
    |       - Walk extension directories
    |       - Load and validate extension manifests
    |       - Populate AppState extension registry
    |
    +---> Vine::server::Initialize()
    |       - Start gRPC server on NetworkMountainPort (default: 50051)
    |
    +---> InitializeCocoon()
    |       - Spawn Node.js bootstrap-fork.js
    |       - Wait for $initialHandshake gRPC notification
    |       - Send initExtensionHost with InitData payload
    |
    v
4. System ready for user interaction

Shutdown Sequence 🛑

1. Tauri window close requested
2. SIGTERM sent to Cocoon sidecar (graceful, 5s timeout)
3. SIGTERM sent to Air sidecar (if running)
4. AppState persisted (settings, window state)
5. gRPC server gracefully drained (in-flight requests complete)
6. Echo scheduler shutdown (in-flight tasks complete)
7. Tokio runtime shutdown
8. Process exits

Module Architecture 🗺️

Element/Mountain/Source/
+-- Binary/
|   +-- Main/
|   |   +-- Entry.rs          - fn main(), Tauri builder
|   |   +-- Setup.rs          - .setup() hook
|   |   +-- Shutdown.rs       - Graceful shutdown
|   |   +-- Tray.rs           - System tray icon
|   |   +-- IPC/              - IPC handler registration
|   |   +-- Register/         - Command registration
|   |   +-- Initialize/       - Startup initialization
|   |   +-- Debug/            - Debug build utilities
|   |   +-- Service/          - Service layer initialization

+-- ApplicationState/
|   +-- State.rs              - Central state struct
|   +-- Internal/             - Internal state management
|   +-- DTO/                  - State transfer objects

+-- Environment/
|   +-- MountainEnvironment.rs - Common trait implementations
|   +-- CommandProvider.rs     - Command execution provider
|   +-- ConfigurationProvider/ - Configuration provider
|   +-- FileSystemProvider/    - File system provider
|   +-- TerminalProvider.rs    - Terminal PTY provider
|   +-- ... (24+ providers)

+-- Vine/ (gRPC)
|   +-- Server/               - gRPC server (tonic)

+-- ProcessManagement/
|   +-- CocoonManagement.rs    - Cocoon sidecar lifecycle
|   +-- InitializationData.rs  - Startup payload construction
|   +-- NodeResolver/          - Node.js binary resolution

+-- IPC/ (Tauri)
|   +-- TauriIPCServer.rs      - Tauri IPC server
|   +-- WindServiceHandlers/   - Wind-specific handlers
|   +-- WindAdvancedSync/      - Sync handlers
|   +-- DevLog/                - Developer logging

+-- RPC/ (Internal dispatch)
|   +-- CocoonService/         - Cocoon gRPC service implementation

+-- RunTime/
|   +-- ApplicationRunTime/    - Effect execution engine
|   +-- Execute/               - Effect execution
|   +-- Shutdown/              - Runtime shutdown

+-- Command/                   - Command implementation
+-- Track/                     - Request tracking
+-- ExtensionManagement/       - Extension lifecycle
+-- FileSystem/                - File system operations
+-- Workspace/                 - Workspace management
+-- LandFixTier.rs             - Runtime tier banner
+-- Library.rs                 - Library root

ApplicationState 📦

The central state container managed by Tauri:

pub struct AppState {
    configuration: RwLock<ConfigurationMap>,
    extensions: RwLock<ExtensionRegistry>,
    workspaces: RwLock<WorkspaceManager>,
    // ... additional state domains
}
State DomainAccess PatternPersistence
ConfigurationRwLock<HashMap>settings.json on disk
ExtensionsRwLock<Vec<Manifest>>Scan on startup
WorkspacesRwLock<Vec<Workspace>>Window state on shutdown
Active editorsRwLock<HashMap<URI, EditorState>>Transient
  • State is accessed through Tauri’s State<AppState> managed type
  • Available in every command handler

Environment and Providers 🧩

MountainEnvironment implements every trait from Common. Each capability has a dedicated Provider:

ProviderCommon TraitImplementation
FileSystemProviderFileSystemtokio::fs native operations
ConfigurationProviderConfigurationJSON file read/write with merge
TerminalProviderTerminalportable-pty PTY management
UserInterfaceProviderUserInterfacetauri-plugin-dialog
CommandProviderCommandExecutorCommand registry + dispatch
DocumentProviderDocumentText model management
ExtensionManagementServiceExtensionManagementServiceVSIX install + manifest scan
SearchProviderSearchripgrep-based search
SecretProviderSecretOS keyring (keyring crate)
StorageProviderStorageJSON file key-value
WorkspaceProviderWorkspaceFolder management
IPCProviderIPCgRPC proxy to Cocoon

Provider Registration 📝

impl MountainEnvironment {
    pub fn new(app_state: AppState) -> Self {
        Self {
            file_system: Arc::new(FileSystemProvider::new(app_state.clone())),
            configuration: Arc::new(ConfigurationProvider::new(app_state.clone())),
            terminal: Arc::new(TerminalProvider::new()),
            // ... all 24+ providers
        }
    }
}

Tauri Command System ⌨️

Mountain registers Tauri commands as typed Rust handlers:

#[tauri::command]
async fn read_file(
    path: String,
    state: State<'_, AppState>,
) -> Result<Vec<u8>, String> {
    let fs = state.file_system();
    fs.read_file(Path::new(&path))
        .await
        .map_err(|e| e.to_string())
}

Registered Command Categories

CategoryExample CommandsHandler
File Systemread_file, write_file, stat, readdirFileSystemProvider
Configurationget_configuration, set_configurationConfigurationProvider
Terminalcreate_terminal, write_terminal, resize_terminalTerminalProvider
Dialogopen_dialog, save_dialog, show_messageUserInterfaceProvider
Clipboardget_clipboard, set_clipboardClipboard
Extensioninstall_extension, list_extensionsExtensionManagementService
Searchsearch_files, search_textSearchProvider
Windowset_window_size, focus_windowWindow management
Lifecyclequit, restartProcess management

gRPC Service (Vine) 🌐

Mountain hosts the Vine gRPC server for Cocoon and Air communication.

Server Configuration ⚙️

// Server listens on NetworkMountainPort (default: 50051)
let addr = format!("127.0.0.1:{}", config.network_mountain_port)
    .parse()
    .expect("Invalid gRPC address");

Server::builder()
    .add_service(ExtensionHostServer::new(service_impl))
    .add_service(BackgroundServicesServer::new(background_impl))
    .serve(addr)
    .await?;

Service Handlers 📋

ServiceRPCHandler Module
ExtensionHostInitializeProcessManagement/InitializationData.rs
ExtensionHostExecuteCommandRPC/CocoonService/Command/
ExtensionHostProvideHoverRPC/CocoonService/Provider/
ExtensionHostCreateWebviewPanelRPC/CocoonService/Window/
ExtensionHostHealthCheckVine/Server/

Process Management ⚙️

Cocoon Management 🔄

The CocoonManagement module handles the Cocoon sidecar lifecycle:

  1. Environment construction: Sets PATH, VSCODE_PARENT_PID, tier env vars
  2. Process spawn: std::process::Command spawns node bootstrap-fork.js
  3. Health monitoring: gRPC heartbeat (5s interval, 3 miss timeout)
  4. Crash recovery: Up to 3 automatic restarts with exponential backoff
  5. Graceful shutdown: SIGTERM, 5s timeout, SIGKILL on timeout

Air Management 🔄

The AirManagement module handles Air sidecar lifecycle:

  1. Process spawn: Spawns Air binary with configured data directory
  2. gRPC connection: Connects to Air on port 50053
  3. Service registration: Air reports available services (updater, indexer, etc.)
  4. Health monitoring: Bidirectional heartbeat
  5. Coordination: Mountain dispatches background work via PerformAction

IPC and Event System 📡

Mountain pushes events to Wind/Sky via Tauri’s event system:

// Emit configuration change event
app_handle.emit("configuration-changed", serde_json::json!({
    "keys": ["editor.fontSize", "workbench.colorTheme"]
})).ok();

Event Catalog

EventPayloadTrigger
configuration-changed{ keys: string[] }Configuration save
extension-activated{ id: string }Extension activation
terminal-data{ id: number, data: string }PTY output
file-changed{ path: string, type: string }File watcher
theme-changed{ theme: string }Theme switch
window-state-changed{ state: string }Window resize/move

Cache System 💾

Mountain implements two caching subsystems:

CachePurposeImplementation
AssetMemoryMapAsset file mmap cachingMemory-mapped files with LRU eviction
PathCanonPath canonicalization cacheLRU cache of realpath() results

Extension Management 🧩

OperationImplementation
ScanWalk extension directories, parse package.json manifests
InstallVSIX extraction to extension directory
UninstallRemove extension directory
ListRead extension registry from AppState


Project Maintainers: Source Open (Source/[email protected]) | GitHub Repository | Report an Issue


See Also