gglib_core/events/
mod.rs

1//! Canonical event union for all cross-adapter events.
2//!
3//! This module is the single source of truth for events used by Tauri listeners,
4//! SSE handlers, and backend emitters.
5//!
6//! # Structure
7//!
8//! - `app` - Application-level events (model added/removed/updated)
9//! - `download` - Download progress and completion events
10//! - `server` - Model server lifecycle events
11//! - `mcp` - MCP server lifecycle events
12//!
13//! # Wire Format
14//!
15//! Events are serialized with a `type` tag for TypeScript compatibility:
16//!
17//! ```json
18//! { "type": "server_started", "modelName": "Llama-2-7B", "port": 8080 }
19//! ```
20
21mod app;
22mod download;
23mod mcp;
24mod server;
25
26use serde::{Deserialize, Serialize};
27
28use crate::ports::McpErrorInfo;
29
30// Re-export event types
31pub use app::ModelSummary;
32pub use mcp::McpServerSummary;
33pub use server::{NoopServerEvents, ServerEvents, ServerSnapshotEntry, ServerSummary};
34
35// Import download types for AppEvent::Download wrapper
36use crate::download::DownloadEvent;
37
38/// Canonical event types for all adapters.
39///
40/// This enum unifies server, download, and model events into a single
41/// discriminated union. Each variant includes all necessary context
42/// for the event to be self-describing.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[serde(tag = "type", rename_all = "snake_case")]
45pub enum AppEvent {
46    // ========== Server Events ==========
47    /// A model server has started and is ready to accept requests.
48    ServerStarted {
49        /// ID of the model being served.
50        #[serde(rename = "modelId")]
51        model_id: i64,
52        /// Name of the model being served.
53        #[serde(rename = "modelName")]
54        model_name: String,
55        /// Port the server is listening on.
56        port: u16,
57    },
58
59    /// A model server has been stopped (clean shutdown).
60    ServerStopped {
61        /// ID of the model that was being served.
62        #[serde(rename = "modelId")]
63        model_id: i64,
64        /// Name of the model that was being served.
65        #[serde(rename = "modelName")]
66        model_name: String,
67    },
68
69    /// A model server encountered an error.
70    ServerError {
71        /// ID of the model being served (if known).
72        #[serde(rename = "modelId")]
73        model_id: Option<i64>,
74        /// Name of the model being served.
75        #[serde(rename = "modelName")]
76        model_name: String,
77        /// Error description.
78        error: String,
79    },
80
81    /// Snapshot of all currently running servers.
82    ServerSnapshot {
83        /// List of currently running servers.
84        servers: Vec<ServerSnapshotEntry>,
85    },
86
87    // ========== Download Events ==========
88    /// Download lifecycle + progress events (including shard progress).
89    ///
90    /// Wraps `DownloadEvent` verbatim to preserve all detail including
91    /// shard-specific progress information.
92    #[serde(rename = "download")]
93    Download {
94        /// The download event payload.
95        event: DownloadEvent,
96    },
97
98    // ========== Model Events ==========
99    /// A model was added to the library.
100    ModelAdded {
101        /// Summary of the added model.
102        model: ModelSummary,
103    },
104
105    /// A model was removed from the library.
106    ModelRemoved {
107        /// ID of the removed model.
108        #[serde(rename = "modelId")]
109        model_id: i64,
110    },
111
112    /// A model was updated in the library.
113    ModelUpdated {
114        /// Summary of the updated model.
115        model: ModelSummary,
116    },
117
118    // ========== Verification Events ==========
119    /// Model verification progress update.
120    VerificationProgress {
121        /// ID of the model being verified.
122        #[serde(rename = "modelId")]
123        model_id: i64,
124        /// Name of the model being verified.
125        #[serde(rename = "modelName")]
126        model_name: String,
127        /// Name of the shard being verified.
128        #[serde(rename = "shardName")]
129        shard_name: String,
130        /// Bytes processed so far.
131        #[serde(rename = "bytesProcessed")]
132        bytes_processed: u64,
133        /// Total bytes to process.
134        #[serde(rename = "totalBytes")]
135        total_bytes: u64,
136    },
137
138    /// Model verification completed.
139    VerificationComplete {
140        /// ID of the verified model.
141        #[serde(rename = "modelId")]
142        model_id: i64,
143        /// Name of the verified model.
144        #[serde(rename = "modelName")]
145        model_name: String,
146        /// Overall health status.
147        #[serde(rename = "overallHealth")]
148        overall_health: crate::services::OverallHealth,
149    },
150
151    /// Server health status has changed.
152    ///
153    /// Emitted by continuous monitoring when a server's health state changes.
154    ServerHealthChanged {
155        /// Unique server instance identifier.
156        #[serde(rename = "serverId")]
157        server_id: i64,
158        /// ID of the model being served.
159        #[serde(rename = "modelId")]
160        model_id: i64,
161        /// New health status.
162        status: crate::ports::ServerHealthStatus,
163        /// Optional detail message (e.g., error description).
164        #[serde(skip_serializing_if = "Option::is_none")]
165        detail: Option<String>,
166        /// Unix timestamp in milliseconds when status changed.
167        timestamp: u64,
168    },
169
170    // ========== MCP Server Events ==========
171    /// An MCP server was added to the configuration.
172    McpServerAdded {
173        /// Summary of the added server.
174        server: McpServerSummary,
175    },
176
177    /// An MCP server was removed from the configuration.
178    McpServerRemoved {
179        /// ID of the removed server.
180        #[serde(rename = "serverId")]
181        server_id: i64,
182    },
183
184    /// An MCP server has started and is ready.
185    McpServerStarted {
186        /// ID of the server.
187        #[serde(rename = "serverId")]
188        server_id: i64,
189        /// Name of the server.
190        #[serde(rename = "serverName")]
191        server_name: String,
192    },
193
194    /// An MCP server has been stopped.
195    McpServerStopped {
196        /// ID of the server.
197        #[serde(rename = "serverId")]
198        server_id: i64,
199        /// Name of the server.
200        #[serde(rename = "serverName")]
201        server_name: String,
202    },
203
204    /// An MCP server encountered an error.
205    McpServerError {
206        /// User-safe error information.
207        error: McpErrorInfo,
208    },
209
210    // ========== Proxy Events ==========
211    /// The OpenAI-compatible proxy has started.
212    ProxyStarted {
213        /// Port the proxy is listening on.
214        port: u16,
215    },
216
217    /// The proxy has been stopped (clean shutdown).
218    ProxyStopped,
219
220    /// The proxy crashed (task exited without cancellation).
221    ProxyCrashed,
222}
223
224impl AppEvent {
225    /// Get the event name for wire protocols.
226    ///
227    /// This provides consistent event naming across Tauri and SSE transports.
228    pub const fn event_name(&self) -> &'static str {
229        match self {
230            Self::ServerStarted { .. } => "server:started",
231            Self::ServerStopped { .. } => "server:stopped",
232            Self::ServerError { .. } => "server:error",
233            Self::ServerSnapshot { .. } => "server:snapshot",
234            Self::ServerHealthChanged { .. } => "server:health_changed",
235            Self::Download { event } => event.event_name(),
236            Self::ModelAdded { .. } => "model:added",
237            Self::ModelRemoved { .. } => "model:removed",
238            Self::ModelUpdated { .. } => "model:updated",
239            Self::VerificationProgress { .. } => "verification:progress",
240            Self::VerificationComplete { .. } => "verification:complete",
241            Self::McpServerAdded { .. } => "mcp:added",
242            Self::McpServerRemoved { .. } => "mcp:removed",
243            Self::McpServerStarted { .. } => "mcp:started",
244            Self::McpServerStopped { .. } => "mcp:stopped",
245            Self::McpServerError { .. } => "mcp:error",
246            Self::ProxyStarted { .. } => "proxy:started",
247            Self::ProxyStopped => "proxy:stopped",
248            Self::ProxyCrashed => "proxy:crashed",
249        }
250    }
251}
252
253impl AppEvent {
254    /// Create a [`ProxyStarted`] event.
255    pub const fn proxy_started(port: u16) -> Self {
256        Self::ProxyStarted { port }
257    }
258
259    /// Create a [`ProxyStopped`] event.
260    pub const fn proxy_stopped() -> Self {
261        Self::ProxyStopped
262    }
263
264    /// Create a [`ProxyCrashed`] event.
265    pub const fn proxy_crashed() -> Self {
266        Self::ProxyCrashed
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn test_event_serialization() {
276        let event = AppEvent::server_started(1, "Llama-2-7B", 8080);
277        let json = serde_json::to_string(&event).unwrap();
278        assert!(json.contains("\"type\":\"server_started\""));
279        assert!(json.contains("\"modelName\":\"Llama-2-7B\""));
280        assert!(json.contains("\"port\":8080"));
281    }
282
283    #[test]
284    fn test_event_names() {
285        assert_eq!(
286            AppEvent::server_started(1, "test", 8080).event_name(),
287            "server:started"
288        );
289        assert_eq!(
290            AppEvent::download_started("id", "name").event_name(),
291            "download:started"
292        );
293        assert_eq!(AppEvent::model_removed(1).event_name(), "model:removed");
294    }
295
296    /// Lock down download event names to prevent frontend subscription mismatches.
297    ///
298    /// This test protects the contract between backend event emission and frontend
299    /// Tauri event subscription. If this test fails, update the `DOWNLOAD_EVENT_NAMES`
300    /// constant in src/services/transport/events/eventNames.ts to match.
301    ///
302    /// Context: Issue where Tauri GUI downloads started but progress UI never appeared
303    /// because frontend listened to wrong event names.
304    #[test]
305    fn download_event_names_are_stable() {
306        let cases = vec![
307            (AppEvent::download_started("id", "name"), "download:started"),
308            (
309                AppEvent::download_progress("id", 50, 100, 1024.0, 10.0, 50.0),
310                "download:progress",
311            ),
312            (
313                AppEvent::download_completed("id", None),
314                "download:completed",
315            ),
316            (AppEvent::download_failed("id", "error"), "download:failed"),
317            (AppEvent::download_cancelled("id"), "download:cancelled"),
318        ];
319
320        for (event, expected_name) in cases {
321            assert_eq!(event.event_name(), expected_name);
322        }
323    }
324}