Expand description
§ApplicationState Module
§Responsibilities
This module defines the central, shared, thread-safe state for the entire Mountain application. It serves as the single source of truth for all runtime state including:
State Management:
- Main
ApplicationStatestruct with all runtime state - Thread-safe access via
Arc<Mutex<...>>wrappers - State transitions and invariants enforcement
- Recovery mechanisms for corrupted state
- Disk persistence for memento (workspace and global) state
Data Structures:
- Data Transfer Objects (DTOs) for various components
- Type-safe state representations
- Serialization/deserialization support
- Validation for state updates
Internal Utilities:
- File I/O and path resolution
- State initialization and loading
- Extension scanning and population
- URL serialization helpers
- Recovery utilities for corrupted state
§Architectural Role
The ApplicationState module is the state management layer of Mountain:
UI ──► Commands ──► ApplicationState (State) ──► Providers/Services
│
↓
Disk (Persistence)§Design Principles:
- Single Source of Truth: All state lives in one place
- Thread Safety: All state is protected by Arc<Mutex<…>>
- Recovery-Oriented: Comprehensive error handling and recovery
- Type Safety: Strong typing at all levels
- Observability: Comprehensive logging for state changes
§VS Code Reference:
This module borrows from VS Code’s state management patterns in:
vs/base/parts/storage/common/storageService.ts- Storage managementvs/workbench/services/environment/common/environmentService.ts- Environment statevs/platform/workspace/common/workspace.ts- Workspace statevs/workbench/services/extensions/common/extensions.ts- Extension state
Key concepts:
- Global vs workspace-scoped storage
- Memento (state serialization) for crash recovery
- Thread-safe state access with proper locking
- State validation and invariants
§Key Components
§ApplicationState
The central state struct containing all runtime state:
Workspace State:
WorkspaceFolders- Currently open workspace foldersWorkspaceConfigurationPath- Path to workspace configIsTrusted- Workspace trust statusWindowState- Window size, position, etc.ActiveDocumentURI- Currently active document
Configuration & Storage:
Configuration- Merged configuration stateGlobalMemento- Global storage (keys → values)WorkspaceMemento- Workspace-scoped storage- Memento paths for persistence
Extension & Provider Management:
CommandRegistry- Registered commandsLanguageProviders- Language feature providersScannedExtensions- Discovered extensionsExtensionScanPaths- Paths to search for extensionsEnabledProposedAPIs- Proposed API permissions
Feature-specific State:
DiagnosticsMap- Compiler/diagnostic errorsOpenDocuments- Currently open documentsOutputChannels- Output channel stateActiveTerminals- Active terminal instancesActiveWebviews- Active webview panelsActiveCustomDocuments- Custom editor stateActiveStatusBarItems- Status bar entriesActiveTreeViews- Tree view providersSourceControlManagement*- SCM provider state
IPC & UI State:
PendingUserInterfaceRequests- Pending UI interactions (dialogs, etc.)
§DTOs
Type-safe representations of state components:
WorkspaceFolderStateDTO- Workspace folder representationDocumentStateDTO- Document metadata and contentExtensionDescriptionStateDTO- Extension metadataTreeViewStateDTO- Tree view stateWebviewStateDTO- Webview panel state- etc.
§Internal
Helper functions for state management:
LoadInitialMementoFromDisk- Load persistent state from diskResolveMementoStorageFilePath- Resolve storage pathsScanAndPopulateExtensions- Scan for extensionsAnalyzeTextLinesAndEOL- Text content analysis- Recovery utilities and error handling
§Thread Safety
All state is protected by Arc<Mutex<...>> for thread-safe access:
pub struct ApplicationState {
pub WorkspaceFolders:Arc<Mutex<Vec<WorkspaceFolderStateDTO>>>,
pub Configuration:Arc<Mutex<MergedConfigurationStateDTO>>,
// ... all fields follow this pattern
}Best Practices:
- Always lock mutexes before accessing state
- Use
map_err(MapLockError)for lock error handling - Release locks as soon as possible (use RAII)
- Avoid nested locks to prevent deadlocks
§State Persistence
§Memento System
Mountain uses a memento system for state persistence:
Global Memento:
- Lives at
{AppData}/globalStorage.json - Contains global application state
- Persists across workspace changes
Workspace Memento:
- Lives at
{AppData}/workspaceStorage/{workspace-id}/storage.json - Contains workspace-specific state
- Changes when workspace changes
Recovery:
- Corrupted JSON files are backed up with timestamps
- Empty maps are returned on parse errors
- Directories are created automatically
§Error Handling
All state operations return Result<T, CommonError> where:
Ok(T)- Successful operation with resultErr(CommonError)- Error with context
Error types:
StateLockPoisoned- Mutex was poisoned (another thread panicked)FileSystemIO- File system operations failedSerializationError- JSON parsing failedUnknown- Uncategorized errors
Recovery mechanisms:
MapLockErrorWithRecovery- Attempt recovery from poisoned locksSafeStateOperation- Safe state operation with recoveryRecoverApplicationState- Comprehensive state recovery
§State Transitions
Valid state transitions:
Uninitialized → Default State → Workspace Loaded → Workspace Unloaded
↓ ↓ ↓ ↓
Load Recover Update Memento Clean UpInvariants:
- Workspace identifier is computed from folder or config
- Memento paths are synced with workspace changes
- Provider handles are monotonically increasing
- Unique IDs are never reused
§TODOs
High Priority:
- Add state migration support for version changes
- Implement state diffing for better debugging
- Add state snapshots for rollback support
Medium Priority:
- Add state compression for large workspaces
- Implement incremental memento updates
- Add state validation on load
Low Priority:
- Add state analytics and metrics
- Implement state cloning for testing
- Add state export/import functionality
Re-exports§
pub use State::ApplicationState::ApplicationState;pub use State::ApplicationState::MapLockError;pub use State::ApplicationState::MapLockErrorWithRecovery;pub use State::ApplicationState::StateOperationResult;pub use State::ConfigurationState;pub use State::ExtensionState;pub use State::FeatureState;pub use State::UIState;pub use State::WorkspaceState;pub use Internal::ExtensionScanner;pub use Internal::PathResolution;pub use Internal::Persistence;pub use Internal::Recovery;pub use Internal::Serialization;pub use Internal::TextProcessing;