Mountain/IPC/WindAirCommands.rs
1//! # Wind-Air Commands - Air Daemon Delegation Layer
2//!
3//! **File Responsibilities:**
4//! This module provides the Tauri IPC commands that enable Wind (the TypeScript
5//! frontend) to delegate background operations to Air (the Rust daemon). All
6//! commands use the gRPC-based AirClient for communication and return
7//! structured DTOs or detailed error messages.
8//!
9//! **Architectural Role in Wind-Mountain-Air Connection:**
10//!
11//! The WindAirCommands module forms the delegation layer that:
12//!
13//! 1. **Bridge to Air Daemon:** Provides a Tauri IPC interface to Air's gRPC
14//! services
15//! 2. **Background Operations:** Offloads long-running tasks from Wind to Air
16//! 3. **Type Translation:** Converts between Tauri JSON and gRPC protobuf
17//! messages
18//! 4. **Error Handling:** Translates gRPC errors to user-friendly error
19//! messages
20//! 5. **Connection Management:** Manages Air client lifecycle and reconnections
21//!
22//! **Three-Tier Architecture:**
23//! ```
24//! Wind (Frontend - TypeScript)
25//! |
26//! | Tauri IPC Commands
27//! v
28//! WindAirCommands (Mountain - Rust)
29//! |
30//! | gRPC Calls
31//! v
32//! AirClient (gRPC Client)
33//! |
34//! | Network Communication
35//! v
36//! Air Daemon (gRPC Server)
37//! ```
38//!
39//! **Available Commands (Tauri IPC):**
40//!
41//! **1. Update Management:**
42//! - `CheckForUpdates` - Check for application updates
43//! - `DownloadUpdate` - Download update package
44//! - `ApplyUpdate` - Apply downloaded update
45//!
46//! **2. File Operations:**
47//! - `DownloadFile` - Download any file from URL
48//!
49//! **3. Authentication:**
50//! - `AuthenticateUser` - Authenticate with various providers
51//!
52//! **4. Indexing & Search:**
53//! - `IndexFiles` - Index directory contents
54//! - `SearchFiles` - Search indexed files
55//!
56//! **5. Monitoring:**
57//! - `GetAirStatus` - Get Air daemon status
58//! - `GetAirMetrics` - Get performance & resource metrics
59//!
60//! **Data Transfer Objects (DTOs):**
61//!
62//! **UpdateInfoDTO:**
63//! ```rust
64//! struct UpdateInfoDTO {
65//! update_available:bool,
66//! version:String,
67//! download_url:String,
68//! release_notes:String,
69//! }
70//! ```
71//!
72//! **DownloadResultDTO:**
73//! ```rust
74//! struct DownloadResultDTO {
75//! success:bool,
76//! file_path:String,
77//! file_size:u64,
78//! checksum:String,
79//! }
80//! ```
81//!
82//! **AuthResponseDTO:**
83//! ```rust
84//! struct AuthResponseDTO {
85//! success:bool,
86//! token:String,
87//! error:Option<String>,
88//! }
89//! ```
90//!
91//! **IndexResultDTO:**
92//! ```rust
93//! struct IndexResultDTO {
94//! success:bool,
95//! files_indexed:u32,
96//! total_size:u64,
97//! }
98//! ```
99//!
100//! **SearchResultsDTO:**
101//! ```rust
102//! struct SearchResultsDTO {
103//! results:Vec<FileResultDTO>,
104//! total_results:u32,
105//! }
106//! ```
107//!
108//! **FileResultDTO:**
109//! ```rust
110//! struct FileResultDTO {
111//! path:String,
112//! size:u64,
113//! line:Option<u32>,
114//! content:Option<String>,
115//! }
116//! ```
117//!
118//! **AirServiceStatusDTO:**
119//! ```rust
120//! struct AirServiceStatusDTO {
121//! version:String,
122//! uptime_seconds:u64,
123//! total_requests:u64,
124//! successful_requests:u64,
125//! failed_requests:u64,
126//! active_requests:u32,
127//! healthy:bool,
128//! }
129//! ```
130//!
131//! **AirMetricsDTO:**
132//! ```rust
133//! struct AirMetricsDTO {
134//! memory_usage_mb:f64,
135//! cpu_usage_percent:f64,
136//! average_response_time:f64,
137//! disk_usage_mb:f64,
138//! network_usage_mbps:f64,
139//! }
140//! ```
141//!
142//! **Command Registration:**
143//!
144//! All commands are registered with Tauri's invoke_handler:
145//!
146//! ```rust
147//! builder.invoke_handler(tauri::generate_handler![
148//! CheckForUpdates,
149//! DownloadUpdate,
150//! ApplyUpdate,
151//! DownloadFile,
152//! AuthenticateUser,
153//! IndexFiles,
154//! SearchFiles,
155//! GetAirStatus,
156//! GetAirMetrics,
157//! ])
158//! ```
159//!
160//! **Client Connection Management:**
161//!
162//! **AirClientWrapper:**
163//! - Wraps the gRPC AirClient
164//! - Manages reconnections
165//! - Default address: `DEFAULT_AIR_SERVER_ADDRESS`
166//!
167//! **Connection Flow:**
168//! ```rust
169//! // 1. Get Air address from config
170//! let air_address = get_air_address(&app_handle)?;
171//!
172//! // 2. Create or reuse client
173//! let client = get_or_create_air_client(&app_handle, air_address).await?;
174//!
175//! // 3. Call Air's gRPC method
176//! let response = client.CheckForUpdates(request).await?;
177//!
178//! // 4. Check for errors
179//! if !response.error.is_empty() {
180//! return Err(response.error);
181//! }
182//!
183//! // 5. Convert to DTO
184//! let result = UpdateInfoDTO { ... };
185//! ```
186//!
187//! **Error Handling Strategy:**
188//!
189//! **gRPC Errors:**
190//! - Catch all gRPC errors
191//! - Translate to user-friendly messages
192//! - Include context about what operation failed
193//!
194//! **Response Errors:**
195//! - Check `response.error` field
196//! - Return error instead of DTO if present
197//! - Preserve original error message
198//!
199//! **Client Errors:**
200//! - Connection failures -> "Failed to connect to Air daemon"
201//! - Timeout errors -> "Operation timed out"
202//! - Parse errors -> "Failed to parse response"
203//!
204//! **Usage Examples from Wind:**
205//!
206//! **Check for Updates:**
207//! ```typescript
208//! const updates = await invoke('CheckForUpdates', {
209//! currentVersion: '1.0.0',
210//! channel: 'stable'
211//! });
212//!
213//! if (updates.updateAvailable) {
214//! console.log(`New version: ${updates.version}`);
215//! }
216//! ```
217//!
218//! **Download Update:**
219//! ```typescript
220//! const result = await invoke('DownloadUpdate', {
221//! url: 'https://example.com/update.zip',
222//! destination: '/tmp/update.zip',
223//! checksum: 'abc123...'
224//! });
225//!
226//! if (result.success) {
227//! console.log(`Downloaded: ${result.filePath}`);
228//! }
229//! ```
230//!
231//! **Authenticate:**
232//! ```typescript
233//! const auth = await invoke('AuthenticateUser', {
234//! username: '[email protected]',
235//! password: 'secret',
236//! provider: 'github'
237//! });
238//!
239//! if (auth.success) {
240//! localStorage.setItem('token', auth.token);
241//! }
242//! ```
243//!
244//! **Index Files:**
245//! ```typescript
246//! const indexResult = await invoke('IndexFiles', {
247//! path: '/project',
248//! patterns: ['*.ts', '*.rs'],
249//! excludePatterns: ['node_modules', 'target'],
250//! maxDepth: 10
251//! });
252//!
253//! console.log(`Indexed ${indexResult.filesIndexed} files`);
254//! ```
255//!
256//! **Search Files:**
257//! ```typescript
258//! const searchResults = await invoke('SearchFiles', {
259//! query: 'TODO:',
260//! indexId: '/project',
261//! maxResults: 100
262//! });
263//!
264//! for (const file of searchResults.results) {
265//! console.log(`${file.path}:${file.line} - ${file.content}`);
266//! }
267//! ```
268//!
269//! **Integration with Other Modules:**
270//!
271//! **TauriIPCServer:**
272//! - Commands registered in same invoke handler
273//! - Both provide Tauri IPC interfaces
274//!
275//! **Configuration:**
276//! - Air address configurable via Mountain settings
277//! - Uses default if not specified
278//!
279//! **StatusReporter:**
280//! - Air status can be reported to Sky
281//! - Metrics collected for monitoring
282//!
283//! **Security Considerations:**
284//!
285//! - Passwords never logged
286//! - Checksums verified for downloads
287//! - File paths validated
288//! - Provider authentication handled securely by Air
289//!
290//! **Performance Considerations:**
291//!
292//! - Client connections are created fresh each call (current implementation)
293//! - Could cache clients for better performance in production
294//! - Large file downloads streamed via Air
295//! - Indexing operations run asynchronously in Air
296
297use std::sync::Arc;
298
299use serde::{Deserialize, Serialize};
300use tauri::{AppHandle, Manager};
301use log::{debug, info};
302use CommonLibrary::Error::CommonError::CommonError;
303
304// Import Air types from the new AirClient implementation.
305// These provide actual gRPC connectivity to the Air daemon service.
306use crate::Air::AirClient as AirClientModule;
307use crate::Air::DEFAULT_AIR_SERVER_ADDRESS;
308
309/// Data Transfer Objects for Wind-Air communication
310
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct UpdateInfoDTO {
313 pub update_available:bool,
314 pub version:String,
315 pub download_url:String,
316 pub release_notes:String,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize)]
320pub struct DownloadResultDTO {
321 pub success:bool,
322 pub file_path:String,
323 pub file_size:u64,
324 pub checksum:String,
325}
326
327#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct AuthResponseDTO {
329 pub success:bool,
330 pub token:String,
331 pub error:Option<String>,
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct IndexResultDTO {
336 pub success:bool,
337 pub files_indexed:u32,
338 pub total_size:u64,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
342pub struct SearchResultsDTO {
343 pub results:Vec<FileResultDTO>,
344 pub total_results:u32,
345}
346
347#[derive(Debug, Clone, Serialize, Deserialize)]
348pub struct FileResultDTO {
349 pub path:String,
350 pub size:u64,
351 pub line:Option<u32>,
352 pub content:Option<String>,
353}
354
355#[derive(Debug, Clone, Serialize, Deserialize)]
356pub struct AirServiceStatusDTO {
357 pub version:String,
358 pub uptime_seconds:u64,
359 pub total_requests:u64,
360 pub successful_requests:u64,
361 pub failed_requests:u64,
362 pub active_requests:u32,
363 pub healthy:bool,
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize)]
367pub struct AirMetricsDTO {
368 pub memory_usage_mb:f64,
369 pub cpu_usage_percent:f64,
370 pub average_response_time:f64,
371 pub disk_usage_mb:f64,
372 pub network_usage_mbps:f64,
373}
374
375/// Air Client - Wrapper for the gRPC client connection to Air daemon
376#[derive(Debug, Clone)]
377pub struct AirClientWrapper {
378 client:AirClientModule::AirClient,
379}
380
381impl AirClientWrapper {
382 /// Create a new AirClient connected to the Air daemon
383 pub async fn new(address:String) -> Result<Self, String> {
384 debug!("[WindAirCommands] Connecting to Air daemon at: {}", address);
385
386 let client = AirClientModule::AirClient::new(&address)
387 .await
388 .map_err(|e| format!("Failed to connect to Air daemon: {:?}", e))?;
389
390 info!("[WindAirCommands] Successfully connected to Air daemon");
391 Ok(Self { client })
392 }
393
394 /// Reconnect to Air daemon
395 pub async fn reconnect(&mut self, address:String) -> Result<(), String> {
396 debug!("[WindAirCommands] Reconnecting to Air daemon at: {}", address);
397
398 let client = AirClientModule::AirClient::new(&address)
399 .await
400 .map_err(|e| format!("Failed to reconnect to Air daemon: {:?}", e))?;
401
402 self.client = client;
403 info!("[WindAirCommands] Successfully reconnected to Air daemon");
404 Ok(())
405 }
406}
407
408// ============================================================================
409// Tauri IPC Commands for Wind-Air Communication
410// ============================================================================
411
412/// Command: Check for Updates
413///
414/// Checks if a newer version of the application is available.
415/// Delegates to Air's update checking service.
416///
417/// # Arguments
418/// * `app_handle` - Tauri application handle
419/// * `current_version` - Current application version
420/// * `channel` - Update channel ("stable", "beta", "nightly")
421///
422/// # Returns
423/// `UpdateInfoDTO` with update information or error message
424#[tauri::command]
425pub async fn CheckForUpdates(current_version:Option<String>, channel:Option<String>) -> Result<UpdateInfoDTO, String> {
426 debug!(
427 "[WindAirCommands] CheckForUpdates called with version: {:?}, channel: {:?}",
428 current_version, channel
429 );
430
431 // Get the Air client from app state or configuration
432 let air_address = get_air_address()?;
433 let client = get_or_create_air_client(air_address).await?;
434
435 // Use the new AirClient API
436 let request_id = uuid::Uuid::new_v4().to_string();
437 let current_version = current_version.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
438 let channel = channel.unwrap_or_else(|| "stable".to_string());
439
440 // Delegate to Air via gRPC
441 let update_info = client
442 .check_for_updates(request_id, current_version, channel)
443 .await
444 .map_err(|e| format!("Update check failed: {:?}", e))?;
445
446 let result = UpdateInfoDTO {
447 update_available:update_info.update_available,
448 version:update_info.version,
449 download_url:update_info.download_url,
450 release_notes:update_info.release_notes,
451 };
452
453 info!(
454 "[WindAirCommands] Update check completed: available={}",
455 result.update_available
456 );
457 Ok(result)
458}
459
460/// Command: Download Update
461///
462/// Downloads an application update from the specified URL.
463/// Delegates to Air's download service.
464///
465/// # Arguments
466/// * `app_handle` - Tauri application handle
467/// * `url` - URL to download the update from
468/// * `destination` - Local destination path for the download
469/// * `checksum` - Optional SHA256 checksum for verification
470///
471/// # Returns
472/// `DownloadResultDTO` with download status
473#[tauri::command]
474pub async fn DownloadUpdate(
475 url:String,
476 destination:String,
477 checksum:Option<String>,
478) -> Result<DownloadResultDTO, String> {
479 debug!("[WindAirCommands] DownloadUpdate called: {} -> {}", url, destination);
480
481 let air_address = get_air_address()?;
482 let client = get_or_create_air_client(air_address).await?;
483
484 let request_id = uuid::Uuid::new_v4().to_string();
485
486 // Delegate to Air via gRPC
487 let file_info = client
488 .download_update(
489 request_id,
490 url,
491 destination,
492 checksum.unwrap_or_default(),
493 std::collections::HashMap::new(),
494 )
495 .await
496 .map_err(|e| format!("Update download failed: {:?}", e))?;
497
498 let result = DownloadResultDTO {
499 success:true,
500 file_path:file_info.file_path,
501 file_size:file_info.file_size,
502 checksum:file_info.checksum,
503 };
504
505 info!("[WindAirCommands] Update download completed: success={}", result.success);
506 Ok(result)
507}
508
509/// Command: Apply Update
510///
511/// Applies a downloaded update to the application.
512/// Delegates to Air's update installation service.
513///
514/// # Arguments
515/// * `app_handle` - Tauri application handle
516/// * `update_id` - Identifier of the update to apply
517/// * `update_path` - Path to the update package
518///
519/// # Returns
520/// Success status or error message
521#[tauri::command]
522pub async fn ApplyUpdate(update_id:String, update_path:String) -> Result<bool, String> {
523 debug!("[WindAirCommands] ApplyUpdate called: id={}, path={}", update_id, update_path);
524
525 let air_address = get_air_address()?;
526 let client = get_or_create_air_client(air_address).await?;
527
528 let request_id = uuid::Uuid::new_v4().to_string();
529
530 // Apply downloaded updates by sending ApplyUpdateRequest to the Air service.
531 // The Air service handles platform-specific installation (replacing binaries,
532 // restarting the application, cleaning up old versions).
533 client
534 .apply_update(request_id, update_id, update_path)
535 .await
536 .map_err(|e| format!("Update application failed: {:?}", e))?;
537
538 info!("[WindAirCommands] Update applied successfully");
539 Ok(true)
540}
541
542/// Command: Download File
543///
544/// Downloads any file from a URL.
545/// Delegates to Air's download service.
546///
547/// # Arguments
548/// * `app_handle` - Tauri application handle
549/// * `url` - URL to download from
550/// * `destination` - Local destination path
551///
552/// # Returns
553/// `DownloadResultDTO` with download status
554#[tauri::command]
555pub async fn DownloadFile(url:String, destination:String) -> Result<DownloadResultDTO, String> {
556 debug!("[WindAirCommands] DownloadFile called: {} -> {}", url, destination);
557
558 let air_address = get_air_address()?;
559 let client = get_or_create_air_client(air_address).await?;
560
561 let request_id = uuid::Uuid::new_v4().to_string();
562
563 let file_info = client
564 .download_file(request_id, url, destination, String::new(), std::collections::HashMap::new())
565 .await
566 .map_err(|e| format!("File download failed: {:?}", e))?;
567
568 let result = DownloadResultDTO {
569 success:true,
570 file_path:file_info.file_path,
571 file_size:file_info.file_size,
572 checksum:file_info.checksum,
573 };
574
575 info!("[WindAirCommands] File download completed");
576 Ok(result)
577}
578
579/// Command: Authenticate User
580///
581/// Authenticates a user with the specified provider.
582/// Delegates to Air's authentication service.
583///
584/// # Arguments
585/// * `app_handle` - Tauri application handle
586/// * `username` - User's username/email
587/// * `password` - User's password (or auth token)
588/// * `provider` - Auth provider ("github", "gitlab", "microsoft", etc.)
589///
590/// # Returns
591/// `AuthResponseDTO` with authentication token
592#[tauri::command]
593pub async fn AuthenticateUser(username:String, password:String, provider:String) -> Result<AuthResponseDTO, String> {
594 debug!("[WindAirCommands] AuthenticateUser called: {} via {}", username, provider);
595
596 let air_address = get_air_address()?;
597 let client = get_or_create_air_client(air_address).await?;
598
599 let request_id = uuid::Uuid::new_v4().to_string();
600
601 let token = client
602 .authenticate(request_id, username, password, provider)
603 .await
604 .map_err(|e| format!("Authentication failed: {:?}", e))?;
605
606 let result = AuthResponseDTO { success:true, token, error:None };
607
608 info!("[WindAirCommands] Authentication completed: success={}", result.success);
609 Ok(result)
610}
611
612/// Command: Index Files
613///
614/// Initiates file indexing for a directory.
615/// Delegates to Air's file indexing service.
616///
617/// # Arguments
618/// * `app_handle` - Tauri application handle
619/// * `path` - Path to directory to index
620/// * `patterns` - File patterns to include
621/// * `exclude_patterns` - File patterns to exclude
622/// * `max_depth` - Maximum directory depth to traverse
623///
624/// # Returns
625/// `IndexResultDTO` with indexing results
626#[tauri::command]
627pub async fn IndexFiles(
628 path:String,
629 patterns:Vec<String>,
630 exclude_patterns:Option<Vec<String>>,
631 max_depth:Option<u32>,
632) -> Result<IndexResultDTO, String> {
633 debug!("[WindAirCommands] IndexFiles called: {} with patterns: {:?}", path, patterns);
634
635 let air_address = get_air_address()?;
636 let client = get_or_create_air_client(air_address).await?;
637
638 let request_id = uuid::Uuid::new_v4().to_string();
639
640 let index_info = client
641 .index_files(
642 request_id,
643 path,
644 patterns,
645 exclude_patterns.unwrap_or_default(),
646 max_depth.unwrap_or(100),
647 )
648 .await
649 .map_err(|e| format!("File indexing failed: {:?}", e))?;
650
651 let result = IndexResultDTO {
652 success:true,
653 files_indexed:index_info.files_indexed,
654 total_size:index_info.total_size,
655 };
656
657 info!("[WindAirCommands] File indexing completed: {} files", result.files_indexed);
658 Ok(result)
659}
660
661/// Command: Search Files
662///
663/// Searches previously indexed files.
664/// Delegates to Air's search service.
665///
666/// # Arguments
667/// * `app_handle` - Tauri application handle
668/// * `query` - Search query string
669/// * `index_id` - Index identifier (or path for backward compatibility)
670/// * `max_results` - Maximum number of results to return
671///
672/// # Returns
673/// `SearchResultsDTO` with matching files
674#[tauri::command]
675pub async fn SearchFiles(
676 query:String,
677 file_patterns:Vec<String>,
678 max_results:Option<u32>,
679) -> Result<SearchResultsDTO, String> {
680 debug!(
681 "[WindAirCommands] SearchFiles called: query={}, patterns={:?}",
682 query, file_patterns
683 );
684
685 let air_address = get_air_address()?;
686 let client = get_or_create_air_client(air_address).await?;
687
688 let request_id = uuid::Uuid::new_v4().to_string();
689 let max_results_count = max_results.unwrap_or(100);
690
691 let search_results = client
692 .search_files(
693 request_id,
694 query,
695 file_patterns.first().map(|s| s.as_str()).unwrap_or("").to_string(),
696 max_results_count,
697 )
698 .await
699 .map_err(|e| format!("File search failed: {:?}", e))?;
700
701 let results:Vec<FileResultDTO> = search_results
702 .into_iter()
703 .map(|r| {
704 FileResultDTO {
705 path:r.path,
706 size:r.size,
707 line:Some(r.line_number),
708 content:Some(r.match_preview),
709 }
710 })
711 .collect();
712
713 let total_results = results.len() as u32;
714 let result = SearchResultsDTO { results, total_results };
715
716 info!("[WindAirCommands] File search completed: {} results", result.total_results);
717 Ok(result)
718}
719
720/// Command: Get Air Status
721///
722/// Retrieves the current status of the Air daemon.
723/// Delegates to Air's status service.
724///
725/// # Arguments
726/// * `app_handle` - Tauri application handle
727///
728/// # Returns
729/// `AirServiceStatusDTO` with service status information
730#[tauri::command]
731pub async fn GetAirStatus() -> Result<AirServiceStatusDTO, String> {
732 debug!("[WindAirCommands] GetAirStatus called");
733
734 let air_address = get_air_address()?;
735 let client = get_or_create_air_client(air_address).await?;
736
737 let request_id = uuid::Uuid::new_v4().to_string();
738
739 let status = client
740 .get_status(request_id)
741 .await
742 .map_err(|e| format!("Failed to get Air status: {:?}", e))?;
743
744 // Use the health check RPC to determine service availability
745 let healthy = client.health_check().await.unwrap_or(false);
746
747 let result = AirServiceStatusDTO {
748 version:status.version,
749 uptime_seconds:status.uptime_seconds,
750 total_requests:status.total_requests,
751 successful_requests:status.successful_requests,
752 failed_requests:status.failed_requests,
753 active_requests:status.active_requests,
754 healthy,
755 };
756
757 info!("[WindAirCommands] Air status retrieved: healthy={}", result.healthy);
758 Ok(result)
759}
760
761/// Command: Get Air Metrics
762///
763/// Retrieves performance and resource metrics from Air.
764/// Delegates to Air's metrics service.
765///
766/// # Arguments
767/// * `app_handle` - Tauri application handle
768/// * `metric_type` - Type of metrics ("all", "performance", "resources",
769/// "requests")
770///
771/// # Returns
772/// `AirMetricsDTO` with metrics data
773#[tauri::command]
774pub async fn GetAirMetrics(metric_type:Option<String>) -> Result<AirMetricsDTO, String> {
775 debug!("[WindAirCommands] GetAirMetrics called with type: {:?}", metric_type);
776
777 let air_address = get_air_address()?;
778 let client = get_or_create_air_client(air_address).await?;
779
780 let request_id = uuid::Uuid::new_v4().to_string();
781
782 let metrics = client
783 .get_metrics(request_id, metric_type)
784 .await
785 .map_err(|e| format!("Failed to get Air metrics: {:?}", e))?;
786
787 let result = AirMetricsDTO {
788 memory_usage_mb:metrics.memory_usage_mb,
789 cpu_usage_percent:metrics.cpu_usage_percent,
790 average_response_time:metrics.average_response_time,
791 disk_usage_mb:metrics.disk_usage_mb,
792 network_usage_mbps:metrics.network_usage_mbps,
793 };
794
795 debug!("[WindAirCommands] Air metrics retrieved");
796 Ok(result)
797}
798
799// ============================================================================
800// Helper Functions
801// ============================================================================
802
803/// Get the Air daemon address from configuration
804fn get_air_address() -> Result<String, String> {
805 // Return default Air address
806 Ok(DEFAULT_AIR_SERVER_ADDRESS.to_string())
807}
808
809/// Get or create the Air client instance
810async fn get_or_create_air_client(address:String) -> Result<AirClientModule::AirClient, String> {
811 // Create a new client each time
812 // In production, you'd use a state management pattern
813 AirClientModule::AirClient::new(&address)
814 .await
815 .map_err(|e| format!("Failed to create Air client: {:?}", e))
816}
817
818/// Register all Wind-Air commands with Tauri
819pub fn register_wind_air_commands<R:tauri::Runtime>(builder:tauri::Builder<R>) -> tauri::Builder<R> {
820 builder.invoke_handler(tauri::generate_handler![
821 CheckForUpdates,
822 DownloadUpdate,
823 ApplyUpdate,
824 DownloadFile,
825 AuthenticateUser,
826 IndexFiles,
827 SearchFiles,
828 GetAirStatus,
829 GetAirMetrics,
830 ])
831}