pitchfork-cli 2.12.0

Daemons with DX
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
mod app;
mod event;
mod ui;

use crate::Result;
use crate::daemon_id::DaemonId;
use crate::daemon_list::DaemonListEntry;
use crate::ipc::batch::{StartOptions, StartResult, StopResult};
use crate::ipc::client::IpcClient;
use crate::settings::settings;
use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use log::LevelFilter;
use miette::IntoDiagnostic;
use ratatui::prelude::*;
use std::io;
use std::sync::Arc;

pub use app::App;

/// Results sent back from background IPC tasks to the main loop.
enum TaskResult {
    Start {
        id: DaemonId,
        result: crate::Result<StartResult>,
    },
    Stop {
        id: DaemonId,
        result: crate::Result<bool>,
    },
    Restart {
        id: DaemonId,
        result: crate::Result<StartResult>,
    },
    Enable {
        id: DaemonId,
        result: crate::Result<bool>,
    },
    Disable {
        id: DaemonId,
        result: crate::Result<bool>,
    },
    BatchStart {
        count: usize,
        result: crate::Result<StartResult>,
    },
    BatchStop {
        count: usize,
        result: crate::Result<StopResult>,
    },
    BatchRestart {
        count: usize,
        result: crate::Result<StartResult>,
    },
    BatchEnable {
        count: usize,
    },
    BatchDisable {
        count: usize,
    },
    Refresh {
        result: crate::Result<Vec<DaemonListEntry>>,
        /// Whether this refresh completing should clear `in_flight`.
        /// True only when the refresh was spawned as the final step of an IPC
        /// operation (start/stop/etc.) or a manual refresh (Action::Refresh).
        /// False for background auto-refresh and local-only actions (SaveConfig,
        /// DeleteDaemon) so they cannot prematurely reset the flag while an IPC
        /// operation is still in flight.
        clears_in_flight: bool,
    },
    RefreshNetwork(Vec<listeners::Listener>),
}

pub async fn run() -> Result<()> {
    // Suppress terminal logging while TUI is active (logs still go to file)
    let prev_log_level = log::max_level();
    log::set_max_level(LevelFilter::Off);

    // Setup terminal
    enable_raw_mode().into_diagnostic()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture).into_diagnostic()?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend).into_diagnostic()?;

    // Run with cleanup guaranteed
    let result = run_with_cleanup(&mut terminal).await;

    // Restore terminal (always runs)
    let _ = disable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    );
    let _ = terminal.show_cursor();

    // Restore log level
    log::set_max_level(prev_log_level);

    result
}

async fn run_with_cleanup(terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) -> Result<()> {
    // Connect to supervisor (auto-start if needed)
    let client = Arc::new(IpcClient::connect(true).await?);

    // Create app state
    let mut app = App::new();
    app.refresh(&client).await?;

    // Run main loop
    run_app(terminal, &mut app, &client).await
}

async fn run_app(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    client: &Arc<IpcClient>,
) -> Result<()> {
    let s = settings();
    let tick_rate = s.tui_tick_rate();
    let refresh_rate = s.tui_refresh_rate();
    let mut last_refresh = std::time::Instant::now();

    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<TaskResult>();
    // True while an IPC operation (start/stop/etc.) is in flight.
    // Used to prevent overlapping operations. Navigation and other local
    // actions are always allowed.
    let mut in_flight = false;

    loop {
        // Draw UI
        terminal.draw(|f| ui::draw(f, app)).into_diagnostic()?;

        // Drain completed background task results
        while let Ok(result) = rx.try_recv() {
            match result {
                TaskResult::Start { id, result } => {
                    app.stop_loading();
                    in_flight = false;
                    match result {
                        Ok(r) if r.any_failed => {
                            app.set_message(format!("Failed to start {id}"));
                        }
                        Ok(r) if !r.started.is_empty() => {
                            app.set_message(format!("Started {id}"));
                        }
                        Ok(_) => {
                            app.set_message(format!("No daemons were started for {id}"));
                        }
                        Err(e) => {
                            app.set_message(format!("Failed to start {id}: {e}"));
                        }
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::Stop { id, result } => {
                    app.stop_loading();
                    in_flight = false;
                    match result {
                        Ok(true) => app.set_message(format!("Stopped {id}")),
                        Ok(false) => app.set_message(format!("Daemon {id} was not running")),
                        Err(e) => app.set_message(format!("Failed to stop {id}: {e}")),
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::Restart { id, result } => {
                    app.stop_loading();
                    in_flight = false;
                    match result {
                        Ok(r) if r.any_failed => {
                            app.set_message(format!("Failed to restart {id}"));
                        }
                        Ok(_) => {
                            app.set_message(format!("Restarted {id}"));
                        }
                        Err(e) => {
                            app.set_message(format!("Failed to restart {id}: {e}"));
                        }
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::Enable { id, result } => {
                    app.stop_loading();
                    in_flight = false;
                    match result {
                        Ok(_) => app.set_message(format!("Enabled {id}")),
                        Err(e) => app.set_message(format!("Failed to enable {id}: {e}")),
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::Disable { id, result } => {
                    app.stop_loading();
                    in_flight = false;
                    match result {
                        Ok(_) => app.set_message(format!("Disabled {id}")),
                        Err(e) => app.set_message(format!("Failed to disable {id}: {e}")),
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::BatchStart { count, result } => {
                    app.stop_loading();
                    in_flight = false;
                    app.clear_selection();
                    match result {
                        Ok(r) => {
                            let started = r.started.len();
                            if r.any_failed {
                                app.set_message(format!(
                                    "Started {started}/{count} daemons (some failed)"
                                ));
                            } else {
                                app.set_message(format!("Started {started} daemons"));
                            }
                        }
                        Err(e) => {
                            app.set_message(format!("Failed to start daemons: {e}"));
                        }
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::BatchStop { count, result } => {
                    app.stop_loading();
                    in_flight = false;
                    app.clear_selection();
                    match result {
                        Ok(r) if r.any_failed => {
                            app.set_message(format!("Stopped {count} daemons (some failed)"));
                        }
                        Ok(_) => {
                            app.set_message(format!("Stopped {count} daemons"));
                        }
                        Err(e) => {
                            app.set_message(format!("Failed to stop daemons: {e}"));
                        }
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::BatchRestart { count, result } => {
                    app.stop_loading();
                    in_flight = false;
                    app.clear_selection();
                    match result {
                        Ok(r) => {
                            let restarted = r.started.len();
                            if r.any_failed {
                                app.set_message(format!(
                                    "Restarted {restarted}/{count} daemons (some failed)"
                                ));
                            } else {
                                app.set_message(format!("Restarted {restarted} daemons"));
                            }
                        }
                        Err(e) => {
                            app.set_message(format!("Failed to restart daemons: {e}"));
                        }
                    }
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::BatchEnable { count } => {
                    app.stop_loading();
                    in_flight = false;
                    app.clear_selection();
                    app.set_message(format!("Enabled {count} daemons"));
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::BatchDisable { count } => {
                    app.stop_loading();
                    in_flight = false;
                    app.clear_selection();
                    app.set_message(format!("Disabled {count} daemons"));
                    spawn_refresh(Arc::clone(client), tx.clone(), false);
                }
                TaskResult::Refresh {
                    result,
                    clears_in_flight,
                } => {
                    if clears_in_flight {
                        app.stop_loading();
                        in_flight = false;
                    }
                    match result {
                        Ok(entries) => app.apply_refresh(entries),
                        Err(e) => app.set_message(format!("Refresh failed: {e}")),
                    }
                    last_refresh = std::time::Instant::now();
                }
                TaskResult::RefreshNetwork(listeners) => {
                    app.apply_network_refresh(listeners);
                }
            }
        }

        // Handle events with timeout
        if crossterm::event::poll(tick_rate).into_diagnostic()?
            && let Some(action) = event::handle_event(app)?
        {
            match action {
                event::Action::Quit => break,
                event::Action::Start(id) if !in_flight => {
                    in_flight = true;
                    app.start_loading(format!("Starting {id}..."));
                    let client = Arc::clone(client);
                    let tx = tx.clone();
                    tokio::spawn(async move {
                        let result = client
                            .start_daemons(
                                std::slice::from_ref(&id),
                                StartOptions {
                                    quiet: true,
                                    ..StartOptions::default()
                                },
                            )
                            .await;
                        let _ = tx.send(TaskResult::Start { id, result });
                    });
                }
                event::Action::Enable(id) if !in_flight => {
                    in_flight = true;
                    app.start_loading(format!("Enabling {id}..."));
                    let client = Arc::clone(client);
                    let tx = tx.clone();
                    tokio::spawn(async move {
                        let result = client.enable(id.clone()).await;
                        let _ = tx.send(TaskResult::Enable { id, result });
                    });
                }
                event::Action::BatchStart(ids) if !in_flight => {
                    let count = ids.len();
                    in_flight = true;
                    app.start_loading(format!("Starting {count} daemons..."));
                    let client = Arc::clone(client);
                    let tx = tx.clone();
                    tokio::spawn(async move {
                        let result = client
                            .start_daemons(
                                &ids,
                                StartOptions {
                                    quiet: true,
                                    ..StartOptions::default()
                                },
                            )
                            .await;
                        let _ = tx.send(TaskResult::BatchStart { count, result });
                    });
                }
                event::Action::BatchEnable(ids) if !in_flight => {
                    let count = ids.len();
                    in_flight = true;
                    app.start_loading(format!("Enabling {count} daemons..."));
                    let client = Arc::clone(client);
                    let tx = tx.clone();
                    tokio::spawn(async move {
                        for id in &ids {
                            let _ = client.enable(id.clone()).await;
                        }
                        let _ = tx.send(TaskResult::BatchEnable { count });
                    });
                }
                event::Action::Refresh if !in_flight => {
                    in_flight = true;
                    app.start_loading("Refreshing...");
                    spawn_refresh(Arc::clone(client), tx.clone(), true);
                }
                event::Action::OpenEditorNew => {
                    app.open_file_selector();
                }
                event::Action::OpenEditorEdit(id) => {
                    app.open_editor_edit(&id);
                }
                event::Action::SaveConfig => {
                    app.start_loading("Saving...");
                    match app.save_editor_config() {
                        Ok(true) => {
                            app.stop_loading();
                            app.close_editor();
                            spawn_refresh(Arc::clone(client), tx.clone(), false);
                        }
                        Ok(false) => {
                            app.stop_loading();
                        }
                        Err(e) => {
                            app.stop_loading();
                            app.set_message(format!("Save failed: {e}"));
                        }
                    }
                }
                event::Action::DeleteDaemon { id, config_path } => {
                    app.confirm_action(app::PendingAction::DeleteDaemon { id, config_path });
                }
                event::Action::ConfirmPending if !in_flight => {
                    if let Some(pending) = app.take_pending_action() {
                        match pending {
                            app::PendingAction::Stop(id) => {
                                in_flight = true;
                                app.start_loading(format!("Stopping {id}..."));
                                let client = Arc::clone(client);
                                let tx = tx.clone();
                                tokio::spawn(async move {
                                    let result = client.stop(id.clone()).await;
                                    let _ = tx.send(TaskResult::Stop { id, result });
                                });
                            }
                            app::PendingAction::Restart(id) => {
                                in_flight = true;
                                app.start_loading(format!("Restarting {id}..."));
                                let client = Arc::clone(client);
                                let tx = tx.clone();
                                tokio::spawn(async move {
                                    let opts = StartOptions {
                                        force: true,
                                        quiet: true,
                                        ..Default::default()
                                    };
                                    let result =
                                        client.start_daemons(std::slice::from_ref(&id), opts).await;
                                    let _ = tx.send(TaskResult::Restart { id, result });
                                });
                            }
                            app::PendingAction::Disable(id) => {
                                in_flight = true;
                                app.start_loading(format!("Disabling {id}..."));
                                let client = Arc::clone(client);
                                let tx = tx.clone();
                                tokio::spawn(async move {
                                    let result = client.disable(id.clone()).await;
                                    let _ = tx.send(TaskResult::Disable { id, result });
                                });
                            }
                            app::PendingAction::BatchStop(ids) => {
                                let count = ids.len();
                                in_flight = true;
                                app.start_loading(format!("Stopping {count} daemons..."));
                                let client = Arc::clone(client);
                                let tx = tx.clone();
                                tokio::spawn(async move {
                                    let result = client.stop_daemons(&ids).await;
                                    let _ = tx.send(TaskResult::BatchStop { count, result });
                                });
                            }
                            app::PendingAction::BatchRestart(ids) => {
                                let count = ids.len();
                                in_flight = true;
                                app.start_loading(format!("Restarting {count} daemons..."));
                                let client = Arc::clone(client);
                                let tx = tx.clone();
                                tokio::spawn(async move {
                                    let opts = StartOptions {
                                        force: true,
                                        quiet: true,
                                        ..Default::default()
                                    };
                                    let result = client.start_daemons(&ids, opts).await;
                                    let _ = tx.send(TaskResult::BatchRestart { count, result });
                                });
                            }
                            app::PendingAction::BatchDisable(ids) => {
                                let count = ids.len();
                                in_flight = true;
                                app.start_loading(format!("Disabling {count} daemons..."));
                                let client = Arc::clone(client);
                                let tx = tx.clone();
                                tokio::spawn(async move {
                                    for id in &ids {
                                        let _ = client.disable(id.clone()).await;
                                    }
                                    let _ = tx.send(TaskResult::BatchDisable { count });
                                });
                            }
                            app::PendingAction::DeleteDaemon { id, config_path } => {
                                app.start_loading(format!("Deleting {id}..."));
                                match app.delete_daemon_from_config(&id, &config_path) {
                                    Ok(true) => {
                                        app.stop_loading();
                                        app.close_editor();
                                        app.set_message(format!("Deleted {id}"));
                                    }
                                    Ok(false) => {
                                        app.stop_loading();
                                        app.set_message(format!(
                                            "Daemon '{id}' not found in config"
                                        ));
                                    }
                                    Err(e) => {
                                        app.stop_loading();
                                        app.set_message(format!("Delete failed: {e}"));
                                    }
                                }
                                spawn_refresh(Arc::clone(client), tx.clone(), false);
                            }
                            app::PendingAction::DiscardEditorChanges => {
                                app.close_editor();
                            }
                        }
                    }
                }
                // Ignore IPC actions when in_flight (navigation/local actions fall through)
                _ => {}
            }
        }

        // Auto-refresh daemon list (skip if IPC operation in flight)
        if last_refresh.elapsed() >= refresh_rate && !in_flight {
            let is_network = app.view == app::View::Network;
            let client_ref = Arc::clone(client);
            let tx_ref = tx.clone();
            tokio::spawn(async move {
                let entries = App::fetch_daemon_data(&client_ref).await;
                let _ = tx_ref.send(TaskResult::Refresh {
                    result: entries,
                    clears_in_flight: false,
                });
                if is_network {
                    let listeners = tokio::task::spawn_blocking(|| {
                        listeners::get_all()
                            .map(|set| set.into_iter().collect::<Vec<_>>())
                            .unwrap_or_default()
                    })
                    .await
                    .unwrap_or_default();
                    let _ = tx_ref.send(TaskResult::RefreshNetwork(listeners));
                }
            });
            // Optimistically advance the timer so we don't spam refreshes
            last_refresh = std::time::Instant::now();
        }
    }

    Ok(())
}

fn spawn_refresh(
    client: Arc<IpcClient>,
    tx: tokio::sync::mpsc::UnboundedSender<TaskResult>,
    clears_in_flight: bool,
) {
    tokio::spawn(async move {
        let entries = App::fetch_daemon_data(&client).await;
        let _ = tx.send(TaskResult::Refresh {
            result: entries,
            clears_in_flight,
        });
    });
}