ralph-tui 2.9.3

Terminal UI for Ralph Orchestrator using ratatui
Documentation
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Bridges RPC v1 stream events into TUI state updates.
//!
//! Connects to a ralph-api server via WebSocket subscription and translates
//! stream events into the same `TuiState` mutations that the in-process
//! observer produces. This makes the TUI work identically whether embedded
//! in the orchestration process or attached remotely.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use anyhow::{Context, Result};
use futures::{SinkExt, StreamExt};
use ratatui::text::Line;
use serde_json::Value;
use tokio::sync::watch;
use tracing::{debug, info, warn};

use crate::rpc_client::{RpcClient, StreamEvent};
use crate::state::{TaskCounts, TaskSummary, TuiState};
use crate::state_mutations::{
    append_error_line, apply_loop_completed, apply_task_active, apply_task_close,
};

/// Topics the TUI subscribes to via the RPC stream.
const TUI_STREAM_TOPICS: &[&str] = &[
    "task.log.line",
    "task.status.changed",
    "loop.status.changed",
    "loop.merge.progress",
    "system.heartbeat",
    "system.lifecycle",
    "error.raised",
    "stream.keepalive",
];

/// Runs the RPC bridge: subscribes to the stream, processes events, and
/// updates TuiState until the cancellation signal fires.
///
/// On WebSocket disconnect, automatically reconnects with the last known
/// cursor for seamless replay.
pub async fn run_rpc_bridge(
    client: RpcClient,
    state: Arc<Mutex<TuiState>>,
    mut cancel_rx: watch::Receiver<bool>,
) -> Result<()> {
    // Fetch initial state via HTTP
    if let Err(e) = seed_initial_state(&client, &state).await {
        warn!(error = %e, "Failed to seed initial state from RPC — continuing with defaults");
    }

    // Subscribe to stream
    let sub = client
        .stream_subscribe(TUI_STREAM_TOPICS, None)
        .await
        .context("failed to create stream subscription")?;

    info!(
        subscription_id = %sub.subscription_id,
        topics = ?sub.accepted_topics,
        cursor = %sub.cursor,
        "TUI subscribed to RPC stream"
    );

    let mut cursor = sub.cursor.clone();
    let subscription_id = sub.subscription_id.clone();
    let mut reconnect_delay = Duration::from_millis(500);
    let max_reconnect_delay = Duration::from_secs(15);

    loop {
        // Connect WebSocket
        let ws_url = client.stream_ws_url(&subscription_id)?;
        debug!(url = %ws_url, "Connecting TUI WebSocket");

        let ws_result = tokio_tungstenite::connect_async(&ws_url).await;
        let (ws, _response) = match ws_result {
            Ok(pair) => {
                reconnect_delay = Duration::from_millis(500); // reset on success
                pair
            }
            Err(e) => {
                warn!(error = %e, delay_ms = reconnect_delay.as_millis(), "WebSocket connect failed, retrying");
                tokio::select! {
                    _ = tokio::time::sleep(reconnect_delay) => {}
                    _ = cancel_rx.changed() => {
                        if *cancel_rx.borrow() { return Ok(()); }
                    }
                }
                reconnect_delay = (reconnect_delay * 2).min(max_reconnect_delay);
                continue;
            }
        };

        info!("TUI WebSocket connected");

        let (mut ws_tx, mut ws_rx) = ws.split();

        // Process messages until disconnect or cancel
        loop {
            tokio::select! {
                biased;

                _ = cancel_rx.changed() => {
                    if *cancel_rx.borrow() {
                        debug!("RPC bridge cancelled");
                        let _ = ws_tx.close().await;
                        return Ok(());
                    }
                }

                msg = ws_rx.next() => {
                    match msg {
                        Some(Ok(tungstenite::Message::Text(text))) => {
                            match serde_json::from_str::<StreamEvent>(&text) {
                                Ok(event) => {
                                    cursor = event.cursor.clone();
                                    apply_stream_event(&event, &state);
                                }
                                Err(e) => {
                                    debug!(error = %e, "Failed to parse stream event");
                                }
                            }
                        }
                        Some(Ok(tungstenite::Message::Ping(data))) => {
                            let _ = ws_tx.send(tungstenite::Message::Pong(data)).await;
                        }
                        Some(Ok(tungstenite::Message::Close(_))) | None => {
                            info!("WebSocket closed, will reconnect");
                            break; // reconnect loop
                        }
                        Some(Err(e)) => {
                            warn!(error = %e, "WebSocket error, will reconnect");
                            break; // reconnect loop
                        }
                        _ => {} // Pong, Binary, Frame — ignore
                    }
                }
            }
        }

        // Ack the last cursor before reconnecting so replay skips already-seen events
        if let Err(e) = client.stream_ack(&subscription_id, &cursor).await {
            debug!(error = %e, "Failed to ack cursor before reconnect");
        }

        // Brief delay before reconnect
        tokio::select! {
            _ = tokio::time::sleep(reconnect_delay) => {}
            _ = cancel_rx.changed() => {
                if *cancel_rx.borrow() { return Ok(()); }
            }
        }
        reconnect_delay = (reconnect_delay * 2).min(max_reconnect_delay);
    }
}

// ---------------------------------------------------------------------------
// Initial state seeding
// ---------------------------------------------------------------------------

async fn seed_initial_state(client: &RpcClient, state: &Arc<Mutex<TuiState>>) -> Result<()> {
    // Fetch tasks for task counts
    let tasks = client.task_list().await.unwrap_or_default();
    let total = tasks.len();
    let open = tasks.iter().filter(|t| t.status == "open").count();
    let closed = tasks.iter().filter(|t| t.status == "closed").count();
    let ready = tasks
        .iter()
        .filter(|t| t.status == "open" || t.status == "ready")
        .count();

    let active_task = tasks
        .iter()
        .find(|t| t.status == "running" || t.status == "open")
        .map(|t| TaskSummary::new(&t.id, &t.title, &t.status));

    // Fetch config for max_iterations
    let config = client.config_get().await.ok();
    let max_iterations = config
        .as_ref()
        .and_then(|c| c.get("config"))
        .and_then(|c| c.get("event_loop"))
        .and_then(|el| el.get("max_iterations"))
        .and_then(Value::as_u64)
        .map(|n| n as u32);

    // Apply to state
    if let Ok(mut s) = state.lock() {
        s.set_task_counts(TaskCounts::new(total, open, closed, ready));
        s.set_active_task(active_task);
        if let Some(max) = max_iterations {
            s.max_iterations = Some(max);
        }
    }

    debug!(
        tasks = total,
        max_iterations = ?max_iterations,
        "Seeded TUI state from RPC"
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Stream event → TuiState translation
// ---------------------------------------------------------------------------

fn apply_stream_event(event: &StreamEvent, state: &Arc<Mutex<TuiState>>) {
    let Ok(mut s) = state.lock() else { return };

    match event.topic.as_str() {
        "task.log.line" => {
            apply_log_line(event, &mut s);
        }
        "task.status.changed" => {
            apply_task_status_change(event, &mut s);
        }
        "loop.status.changed" => {
            apply_loop_status_change(event, &mut s);
        }
        "system.lifecycle" => {
            apply_lifecycle(event, &mut s);
        }
        "error.raised" => {
            apply_error(event, &mut s);
        }
        "stream.keepalive" | "system.heartbeat" | "loop.merge.progress" => {
            // Update liveness indicator
            s.last_event = Some(event.topic.clone());
            s.last_event_at = Some(std::time::Instant::now());
        }
        _ => {
            debug!(topic = %event.topic, "Unhandled stream topic in TUI bridge");
        }
    }
}

/// Append a log line to the current iteration buffer.
///
/// Payload shape: `{ "line": "text...", "iteration": 3, "hat": "Builder" }`
fn apply_log_line(event: &StreamEvent, state: &mut TuiState) {
    let text = event
        .payload
        .get("line")
        .and_then(Value::as_str)
        .unwrap_or("");
    let iteration = event
        .payload
        .get("iteration")
        .and_then(Value::as_u64)
        .unwrap_or(0) as u32;
    let hat = event
        .payload
        .get("hat")
        .and_then(Value::as_str)
        .map(String::from);
    let backend = event
        .payload
        .get("backend")
        .and_then(Value::as_str)
        .map(String::from);

    // Ensure we have an iteration buffer for this iteration
    while state.total_iterations() < iteration as usize {
        state.start_new_iteration_with_metadata(hat.clone(), backend.clone());
    }

    // Append line to the latest iteration buffer
    if let Some(handle) = state.latest_iteration_lines_handle()
        && let Ok(mut lines) = handle.lock()
    {
        lines.push(Line::from(text.to_string()));
    }

    state.last_event = Some("task.log.line".to_string());
    state.last_event_at = Some(std::time::Instant::now());
}

/// Handle task status transitions → update task counts and active task.
///
/// Payload: `{ "from": "open", "to": "running" }`
fn apply_task_status_change(event: &StreamEvent, state: &mut TuiState) {
    let to = event
        .payload
        .get("to")
        .and_then(Value::as_str)
        .unwrap_or("");
    let task_id = &event.resource.id;

    match to {
        "running" => {
            apply_task_active(state, task_id, task_id, "running");
        }
        "closed" | "done" => {
            apply_task_close(state, task_id);
        }
        _ => {}
    }

    state.last_event = Some("task.status.changed".to_string());
    state.last_event_at = Some(std::time::Instant::now());
}

/// Handle loop status transitions → iteration boundary + completion.
///
/// Payload: `{ "loopId": "...", "status": "running"|"completed"|"failed", "iteration": 3 }`
fn apply_loop_status_change(event: &StreamEvent, state: &mut TuiState) {
    let status = event
        .payload
        .get("status")
        .and_then(Value::as_str)
        .unwrap_or("");
    let hat = event
        .payload
        .get("hat")
        .and_then(Value::as_str)
        .map(String::from);
    let backend = event
        .payload
        .get("backend")
        .and_then(Value::as_str)
        .map(String::from);

    match status {
        "iteration_started" => {
            state.start_new_iteration_with_metadata(hat, backend);
            state.iteration_started = Some(std::time::Instant::now());
        }
        "iteration_completed" => {
            state.prev_iteration = state.iteration;
            state.iteration += 1;
            state.finish_latest_iteration();
        }
        "completed" | "terminated" => {
            apply_loop_completed(state);
        }
        _ => {}
    }

    state.last_event = Some("loop.status.changed".to_string());
    state.last_event_at = Some(std::time::Instant::now());
}

/// Handle system lifecycle events (loop started, terminated).
fn apply_lifecycle(event: &StreamEvent, state: &mut TuiState) {
    let phase = event
        .payload
        .get("phase")
        .and_then(Value::as_str)
        .unwrap_or("");

    if phase == "started" {
        state.loop_started = Some(std::time::Instant::now());
    } else if phase == "terminated" {
        apply_loop_completed(state);
    }

    state.last_event = Some("system.lifecycle".to_string());
    state.last_event_at = Some(std::time::Instant::now());
}

/// Surface errors in the TUI content area.
fn apply_error(event: &StreamEvent, state: &mut TuiState) {
    let message = event
        .payload
        .get("message")
        .and_then(Value::as_str)
        .unwrap_or("unknown error");
    let code = event
        .payload
        .get("code")
        .and_then(Value::as_str)
        .unwrap_or("UNKNOWN");

    append_error_line(state, code, message);

    state.last_event = Some("error.raised".to_string());
    state.last_event_at = Some(std::time::Instant::now());
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rpc_client::{StreamReplay, StreamResource};
    use serde_json::json;

    fn make_state() -> Arc<Mutex<TuiState>> {
        Arc::new(Mutex::new(TuiState::new()))
    }

    fn make_event(topic: &str, payload: Value) -> StreamEvent {
        StreamEvent {
            api_version: "v1".to_string(),
            stream: "events.v1".to_string(),
            topic: topic.to_string(),
            cursor: "1234-0".to_string(),
            sequence: 0,
            ts: "2026-02-26T00:00:00Z".to_string(),
            resource: StreamResource {
                kind: "task".to_string(),
                id: "task-1".to_string(),
            },
            replay: StreamReplay {
                mode: "live".to_string(),
                requested_cursor: None,
                batch: None,
            },
            payload,
        }
    }

    #[test]
    fn log_line_creates_iteration_and_appends() {
        let state = make_state();
        let event = make_event(
            "task.log.line",
            json!({ "line": "Hello world", "iteration": 1 }),
        );

        apply_stream_event(&event, &state);

        let s = state.lock().unwrap();
        assert_eq!(s.total_iterations(), 1);
        let lines = s.iterations[0].lines.lock().unwrap();
        assert_eq!(lines.len(), 1);
    }

    #[test]
    fn task_status_running_sets_active() {
        let state = make_state();
        let event = make_event(
            "task.status.changed",
            json!({ "from": "open", "to": "running" }),
        );

        apply_stream_event(&event, &state);

        let s = state.lock().unwrap();
        assert!(s.get_active_task().is_some());
    }

    #[test]
    fn task_status_closed_increments_count() {
        let state = make_state();
        {
            let mut s = state.lock().unwrap();
            s.set_task_counts(TaskCounts::new(5, 3, 2, 3));
        }

        let event = make_event(
            "task.status.changed",
            json!({ "from": "running", "to": "closed" }),
        );
        apply_stream_event(&event, &state);

        let s = state.lock().unwrap();
        assert_eq!(s.task_counts.closed, 3);
        assert_eq!(s.task_counts.open, 2);
    }

    #[test]
    fn loop_status_completed_marks_completion() {
        let state = make_state();
        let event = make_event("loop.status.changed", json!({ "status": "completed" }));

        apply_stream_event(&event, &state);

        let s = state.lock().unwrap();
        assert!(s.loop_completed);
    }

    #[test]
    fn lifecycle_started_sets_timer() {
        let state = make_state();
        // Clear the default timer to test
        {
            let mut s = state.lock().unwrap();
            s.loop_started = None;
        }

        let event = make_event("system.lifecycle", json!({ "phase": "started" }));
        apply_stream_event(&event, &state);

        let s = state.lock().unwrap();
        assert!(s.loop_started.is_some());
    }

    #[test]
    fn error_event_appends_line() {
        let state = make_state();
        // Create an iteration first
        {
            let mut s = state.lock().unwrap();
            s.start_new_iteration();
        }

        let event = make_event(
            "error.raised",
            json!({ "code": "TIMEOUT", "message": "request timed out" }),
        );
        apply_stream_event(&event, &state);

        let s = state.lock().unwrap();
        let lines = s.iterations[0].lines.lock().unwrap();
        assert_eq!(lines.len(), 1);
    }
}