summaryrefslogtreecommitdiff
path: root/makima/src/daemon/tui/ws_client.rs
blob: 3462467fff1b6c850c11694c8a6f1c075b24a9c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
//! TUI WebSocket client for task output streaming.
//!
//! Uses a dedicated async thread to handle WebSocket communication,
//! bridging async/sync worlds via channels.

use std::sync::mpsc as std_mpsc;
use std::thread;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::runtime::Runtime;
use tokio::sync::mpsc as tokio_mpsc;
use uuid::Uuid;

/// Commands sent from TUI to WebSocket client
#[derive(Debug, Clone)]
pub enum WsCommand {
    /// Subscribe to task output
    Subscribe { task_id: Uuid },
    /// Unsubscribe from task output
    Unsubscribe { task_id: Uuid },
    /// Shutdown the WebSocket client
    Shutdown,
}

/// Events sent from WebSocket client to TUI
#[derive(Debug, Clone)]
pub enum WsEvent {
    /// WebSocket connected
    Connected,
    /// WebSocket disconnected
    Disconnected,
    /// WebSocket reconnecting
    Reconnecting { attempt: u32 },
    /// Subscription confirmed
    Subscribed { task_id: Uuid },
    /// Unsubscription confirmed
    Unsubscribed { task_id: Uuid },
    /// Task output received
    TaskOutput(TaskOutputEvent),
    /// Error occurred
    Error { message: String },
}

/// Task output event from server
#[derive(Debug, Clone)]
pub struct TaskOutputEvent {
    pub task_id: Uuid,
    pub message_type: String,
    pub content: String,
    pub tool_name: Option<String>,
    pub tool_input: Option<serde_json::Value>,
    pub is_error: Option<bool>,
    pub cost_usd: Option<f64>,
    pub duration_ms: Option<u64>,
    pub is_partial: bool,
}

/// Messages sent to the WebSocket server
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum ClientMessage {
    SubscribeOutput {
        #[serde(rename = "taskId")]
        task_id: Uuid,
    },
    UnsubscribeOutput {
        #[serde(rename = "taskId")]
        task_id: Uuid,
    },
}

/// Messages received from the WebSocket server
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum ServerMessage {
    OutputSubscribed {
        #[serde(rename = "taskId")]
        task_id: Uuid,
    },
    OutputUnsubscribed {
        #[serde(rename = "taskId")]
        task_id: Uuid,
    },
    TaskOutput {
        #[serde(rename = "taskId")]
        task_id: Uuid,
        #[serde(rename = "messageType")]
        message_type: String,
        content: String,
        #[serde(rename = "toolName")]
        tool_name: Option<String>,
        #[serde(rename = "toolInput")]
        tool_input: Option<serde_json::Value>,
        #[serde(rename = "isError")]
        is_error: Option<bool>,
        #[serde(rename = "costUsd")]
        cost_usd: Option<f64>,
        #[serde(rename = "durationMs")]
        duration_ms: Option<u64>,
        #[serde(rename = "isPartial")]
        is_partial: bool,
    },
    Error {
        code: String,
        message: String,
    },
    // Other message types we don't care about
    #[serde(other)]
    Other,
}

/// TUI WebSocket client handle
pub struct TuiWsClient {
    /// Command sender to WebSocket thread
    command_tx: tokio_mpsc::Sender<WsCommand>,
    /// Event receiver from WebSocket thread
    event_rx: std_mpsc::Receiver<WsEvent>,
}

impl TuiWsClient {
    /// Start a new WebSocket client in a dedicated thread
    pub fn start(api_url: String, api_key: String) -> Self {
        let (command_tx, command_rx) = tokio_mpsc::channel(32);
        let (event_tx, event_rx) = std_mpsc::channel();

        // Spawn as daemon thread so it doesn't block process exit
        thread::Builder::new()
            .name("ws-client".to_string())
            .spawn(move || {
                let rt = match Runtime::new() {
                    Ok(rt) => rt,
                    Err(e) => {
                        let _ = event_tx.send(WsEvent::Error {
                            message: format!("Failed to create tokio runtime: {}", e),
                        });
                        return;
                    }
                };
                rt.block_on(run_ws_client(api_url, api_key, command_rx, event_tx));
            })
            .ok();

        Self {
            command_tx,
            event_rx,
        }
    }

    /// Send a command to the WebSocket client (non-blocking)
    pub fn send(&self, command: WsCommand) {
        // Use try_send to avoid blocking on shutdown
        let _ = self.command_tx.try_send(command);
    }

    /// Subscribe to task output
    pub fn subscribe(&self, task_id: Uuid) {
        self.send(WsCommand::Subscribe { task_id });
    }

    /// Unsubscribe from task output
    pub fn unsubscribe(&self, task_id: Uuid) {
        self.send(WsCommand::Unsubscribe { task_id });
    }

    /// Shutdown the WebSocket client
    pub fn shutdown(&self) {
        self.send(WsCommand::Shutdown);
    }

    /// Try to receive an event (non-blocking)
    pub fn try_recv(&self) -> Option<WsEvent> {
        self.event_rx.try_recv().ok()
    }

    /// Receive an event with timeout
    pub fn recv_timeout(&self, timeout: Duration) -> Option<WsEvent> {
        self.event_rx.recv_timeout(timeout).ok()
    }
}

impl Drop for TuiWsClient {
    fn drop(&mut self) {
        // Try to send shutdown command, but don't wait
        let _ = self.command_tx.try_send(WsCommand::Shutdown);
    }
}

/// WebSocket client main loop
async fn run_ws_client(
    api_url: String,
    api_key: String,
    mut command_rx: tokio_mpsc::Receiver<WsCommand>,
    event_tx: std_mpsc::Sender<WsEvent>,
) {
    use futures::{SinkExt, StreamExt};
    use tokio_tungstenite::{connect_async, tungstenite::client::IntoClientRequest, tungstenite::Message};

    // Build WebSocket URL from HTTP URL
    let ws_url = api_url
        .replace("https://", "wss://")
        .replace("http://", "ws://");
    let ws_url = format!("{}/api/v1/mesh/tasks/subscribe", ws_url);

    let mut reconnect_attempt = 0u32;
    let max_reconnect_delay = Duration::from_secs(30);
    let initial_delay = Duration::from_secs(1);

    loop {
        // Build request with API key header
        let mut request = match ws_url.clone().into_client_request() {
            Ok(r) => r,
            Err(e) => {
                let _ = event_tx.send(WsEvent::Error {
                    message: format!("Invalid URL: {}", e),
                });
                return;
            }
        };

        // Send both headers - server will try tool key first, then API key
        if let Ok(header_value) = api_key.parse() {
            request.headers_mut().insert("x-makima-tool-key", header_value);
        }
        if let Ok(header_value) = api_key.parse() {
            request.headers_mut().insert("x-makima-api-key", header_value);
        }

        if reconnect_attempt > 0 {
            let _ = event_tx.send(WsEvent::Reconnecting {
                attempt: reconnect_attempt,
            });

            // Exponential backoff
            let delay = std::cmp::min(
                initial_delay * 2u32.saturating_pow(reconnect_attempt - 1),
                max_reconnect_delay,
            );
            tokio::time::sleep(delay).await;
        }

        // Try to connect
        let (ws_stream, _) = match connect_async(request).await {
            Ok(result) => {
                reconnect_attempt = 0;
                let _ = event_tx.send(WsEvent::Connected);
                result
            }
            Err(e) => {
                reconnect_attempt += 1;
                let _ = event_tx.send(WsEvent::Error {
                    message: format!("Connection failed: {}", e),
                });
                continue;
            }
        };

        let (mut write, mut read) = ws_stream.split();

        // Main message loop
        loop {
            tokio::select! {
                // Handle commands from TUI
                cmd = command_rx.recv() => {
                    match cmd {
                        Some(WsCommand::Subscribe { task_id }) => {
                            let msg = ClientMessage::SubscribeOutput { task_id };
                            if let Ok(json) = serde_json::to_string(&msg) {
                                let _ = write.send(Message::Text(json)).await;
                            }
                        }
                        Some(WsCommand::Unsubscribe { task_id }) => {
                            let msg = ClientMessage::UnsubscribeOutput { task_id };
                            if let Ok(json) = serde_json::to_string(&msg) {
                                let _ = write.send(Message::Text(json)).await;
                            }
                        }
                        Some(WsCommand::Shutdown) | None => {
                            let _ = write.close().await;
                            return;
                        }
                    }
                }

                // Handle messages from server
                msg = read.next() => {
                    match msg {
                        Some(Ok(Message::Text(text))) => {
                            if let Ok(server_msg) = serde_json::from_str::<ServerMessage>(&text) {
                                match server_msg {
                                    ServerMessage::OutputSubscribed { task_id } => {
                                        let _ = event_tx.send(WsEvent::Subscribed { task_id });
                                    }
                                    ServerMessage::OutputUnsubscribed { task_id } => {
                                        let _ = event_tx.send(WsEvent::Unsubscribed { task_id });
                                    }
                                    ServerMessage::TaskOutput {
                                        task_id,
                                        message_type,
                                        content,
                                        tool_name,
                                        tool_input,
                                        is_error,
                                        cost_usd,
                                        duration_ms,
                                        is_partial,
                                    } => {
                                        let _ = event_tx.send(WsEvent::TaskOutput(TaskOutputEvent {
                                            task_id,
                                            message_type,
                                            content,
                                            tool_name,
                                            tool_input,
                                            is_error,
                                            cost_usd,
                                            duration_ms,
                                            is_partial,
                                        }));
                                    }
                                    ServerMessage::Error { code, message } => {
                                        let _ = event_tx.send(WsEvent::Error {
                                            message: format!("{}: {}", code, message),
                                        });
                                    }
                                    ServerMessage::Other => {
                                        // Ignore other message types
                                    }
                                }
                            }
                        }
                        Some(Ok(Message::Ping(data))) => {
                            let _ = write.send(Message::Pong(data)).await;
                        }
                        Some(Ok(Message::Close(_))) | None => {
                            let _ = event_tx.send(WsEvent::Disconnected);
                            reconnect_attempt += 1;
                            break; // Reconnect
                        }
                        Some(Err(e)) => {
                            let _ = event_tx.send(WsEvent::Error {
                                message: format!("WebSocket error: {}", e),
                            });
                            let _ = event_tx.send(WsEvent::Disconnected);
                            reconnect_attempt += 1;
                            break; // Reconnect
                        }
                        _ => {}
                    }
                }
            }
        }
    }
}