Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,13 @@ small front-door menu that gets you to the common tasks:
- **Chat** — talk to a local or API-backed model
- **Open full dashboard →** — escalate into the live dashboard (`rocm dash`)

Pick a row with the arrow keys and `Enter`; press `q` to quit. On a
non-interactive terminal (or piped output), `rocm` prints a one-shot status
summary instead of opening the launcher.
Pick a row with the arrow keys and `Enter`; press `q` — or `Ctrl-C`, which quits
from the launcher and the dashboard alike and restores your terminal — to quit.
The one exception is the dashboard's console for a **running** job, where
`Ctrl-C` keeps its existing meaning of "cancel this job" and does not quit; once
that job finishes, `Ctrl-C` quits there too. On a non-interactive terminal (or
piped output), `rocm` prints a one-shot status summary instead of opening the
launcher.

## Interactive interfaces

Expand Down
34 changes: 34 additions & 0 deletions apps/rocm/src/dash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,40 @@ pub fn run_launcher(chat_mock: bool) -> Result<()> {
let paths = AppPaths::discover()?;
let config = RocmCliConfig::load(&paths).unwrap_or_default();
let theme = config.dashboard.tui.theme;

// Bare `rocm` is a persistent hub: it outlives each session's Tokio runtime
// and returns to a synchronous, raw-mode launcher menu between flows. Each
// session builds and drops its own runtime, and Tokio never unregisters the
// libc signal handler it installs — so once a session's runtime is dropped
// nothing drains the signal pipe and a per-session watcher goes deaf. The
// menu would then hold the terminal in raw mode while SIGTERM/SIGINT are
// caught-and-discarded: an unkillable, worse form of the very bug this
// fixes. Keep ONE runtime alive for the whole hub and spawn a single
// process-lifetime watcher on it, so every window — the menu and each
// session alike — has a live reactor to restore the terminal and exit
// `128 + signo`. The watcher is registered before the first menu paint, so
// even the very first launcher screen is covered.
let signal_rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.context("building the launcher signal runtime")?;
// Register + spawn inside the runtime context; the returned watcher handle is
// dropped on purpose (dropping a `JoinHandle` detaches the task, it does not
// abort it), so the hub keeps `signal_rt`'s worker draining the signal pipe
// for the whole loop below and the watcher lives for the process.
//
// This watcher deliberately COEXISTS with the one `app::run` installs when a
// flow escalates into a full dashboard session. Tokio's signal registry is
// process-global, so a single `kill` wakes both. That is safe because the
// watcher body arbitrates on a process-global latch: only the first one
// through restores the terminal and exits, so the two never race
// unsynchronised stdout writes or concurrent `process::exit` calls. See
// `spawn_termination_watcher`.
let _watcher = signal_rt
.block_on(async { rocm_dash_tui::app::spawn_termination_watcher() })
.map_err(|e| anyhow::anyhow!("installing launcher termination-signal handlers: {e}"))?;

loop {
// Re-read the managed-service registry on each pass so the front door
// reflects models started (or stopped) during a prior flow. This is a
Expand Down
6 changes: 6 additions & 0 deletions crates/rocm-dash-tui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,9 @@ rig = { package = "rig-core", version = "=0.38.1", default-features = false, fea
# same 0.13 line Rig already pulls in (TUI crate only) so the tree keeps one
# reqwest version; `json` for response parsing, `rustls-tls` to match Rig's stack.
reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] }

# Test-only, Unix-only: `raise(3)` lets the termination-watcher unit tests drive
# a real SIGTERM/SIGINT through Tokio's signal registry in-process. Not a runtime
# dependency — the production signal path goes through `tokio::signal`.
[target.'cfg(unix)'.dev-dependencies]
libc.workspace = true
1,083 changes: 1,063 additions & 20 deletions crates/rocm-dash-tui/src/app/mod.rs

Large diffs are not rendered by default.

208 changes: 200 additions & 8 deletions crates/rocm-dash-tui/src/ui/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ fn draw_menu(f: &mut Frame, area: Rect, state: &AppState, sel: usize, theme: &Th
]));
lines.push(Line::raw(""));
lines.push(Line::from(Span::styled(
"↑↓←→ move Enter select d dashboard q quit",
"↑↓←→ move Enter select d dashboard q / Ctrl-C quit",
Style::default().fg(theme.muted),
)));
f.render_widget(Paragraph::new(lines), area);
Expand Down Expand Up @@ -287,9 +287,7 @@ pub fn run_launcher(
serving: Vec<Instance>,
) -> std::io::Result<Option<LauncherChoice>> {
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use crossterm::terminal::{
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use crossterm::terminal::{EnterAlternateScreen, enable_raw_mode};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;

Expand All @@ -304,13 +302,27 @@ pub fn run_launcher(

let mut sel = 0usize;
let result = loop {
terminal.draw(|f| draw(f, f.area(), &state, sel, &theme))?;
draw_menu_unless_shutting_down(
&mut terminal,
&state,
sel,
&theme,
&crate::app::SHUTTING_DOWN,
)?;
let Event::Key(k) = event::read()? else {
continue;
};
if k.kind != KeyEventKind::Press {
continue;
}
// Raw mode delivers a typed Ctrl-C as a key event, not a signal, so the
// hub's termination watcher never sees it. This menu is the second of
// the process's two key loops; route it through the same
// restore-and-exit path a real SIGINT takes, so the gesture cannot mean
// one thing inside a session and nothing at all at the front door.
if crate::app::is_ctrl_c(k) {
crate::app::exit_on_ctrl_c();
}
match k.code {
KeyCode::Char('q') | KeyCode::Esc => break None,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ctrl-C is now a first-class quit gesture in both loops, but it isn't documented on any key-hint surface. These all still list just q quit:

  • ui/modal.rs:88 and :604 (the ? help modals)
  • the footer in ui/mod.rs
  • the launcher hint line at ui/launcher.rs:251
  • README.md:158

(Anchored here because none of those lines are in this PR's diff.)

KeyCode::Char('d') => break Some(LauncherChoice::OpenDashboard),
Expand All @@ -325,12 +337,48 @@ pub fn run_launcher(
}
};

disable_raw_mode()?;
crossterm::execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
// One shared teardown for the whole crate. This used to be an open-coded
// `disable_raw_mode` + `LeaveAlternateScreen` + `show_cursor` — a second
// restore implementation that could (and would) drift from the one the
// signal watcher and the typed-Ctrl-C path run. `restore_terminal` is
// best-effort by design: a vanished controlling terminal must not turn a
// clean launcher exit into an `Err`, which the `?`s here previously did.
crate::app::restore_terminal();
Ok(result)
}

/// Draw one launcher frame, unless a shutdown has already been claimed on
/// `latch`.
///
/// The hub's signal watcher runs on its own runtime while this menu loop owns
/// the main thread, so a termination can be in flight concurrently: the terminal
/// is being restored, and this frame must not land after the restore and undo
/// it. See the ordering note on `crate::app::restore_terminal`.
///
/// As in the dashboard's gate, the latch read is done *under*
/// `crate::app::lock_terminal_writer`, which is then held for the whole frame:
/// the lock stops a restore splicing into (or being overtaken by) this frame, and
/// the latch read under it stops a frame that a restore already beat to the lock.
/// Neither half is sufficient alone.
///
/// Parameterised over the backend and the latch so the gate is testable against
/// a `TestBackend` — inlined in the loop it was reachable only from a real
/// terminal, and deleting it turned no test red.
fn draw_menu_unless_shutting_down<B: ratatui::backend::Backend>(
terminal: &mut ratatui::Terminal<B>,
state: &AppState,
sel: usize,
theme: &Theme,
latch: &std::sync::atomic::AtomicBool,
) -> Result<(), <B as ratatui::backend::Backend>::Error> {
let _writer = crate::app::lock_terminal_writer();
if crate::app::shutdown_claimed_on(latch) {
return Ok(());
}
terminal.draw(|f| draw(f, f.area(), state, sel, theme))?;
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -352,6 +400,150 @@ mod tests {
.collect()
}

#[test]
fn a_claimed_shutdown_stops_the_launcher_painting_another_frame() {
// Same gate as the dashboard's, on the crate's *other* key loop. The hub
// menu runs on the main thread while the hub's signal watcher runs on its
// own runtime, so a frame started after `restore_terminal()` would hide
// the cursor again and repaint the menu over the restored screen.
// Local latch, `TestBackend`: asserts painted cells, not the predicate.
use std::sync::atomic::AtomicBool;

let painted = |term: &Terminal<TestBackend>| -> String {
term.backend()
.buffer()
.content()
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim()
.to_string()
};

let state = base();
let theme = state.theme;

// Control: an unclaimed latch must let the frame through, or the
// assertion below would hold for a helper that simply never draws.
let open = AtomicBool::new(false);
let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, &open)
.expect("drawing to a TestBackend cannot fail");
assert!(
!painted(&term).is_empty(),
"with no shutdown claimed the launcher must paint its menu"
);

let claimed = AtomicBool::new(true);
let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, &claimed)
.expect("the gate must not turn a suppressed frame into an error");
assert_eq!(
painted(&term),
"",
"once the shutdown is claimed the launcher must stop painting — a \
late frame lands after `restore_terminal()` and undoes it"
);
}

#[test]
fn a_menu_frame_cannot_paint_while_a_teardown_owns_the_terminal() {
// The launcher's half of the fix for the partial restore the WSL2 E2E
// lane caught (`alternate_screen=false, cursor_hidden=true`): reading the
// latch cannot stop a frame that already passed the gate, and that
// frame's trailing `Hide` undoes the restore's `Show`. The menu loop must
// therefore take `lock_terminal_writer()` first and read the latch under
// it. See the twin test in `app::tests`, which carries the full analysis.
use std::sync::atomic::AtomicBool;

let painted = |term: &Terminal<TestBackend>| -> String {
term.backend()
.buffer()
.content()
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim()
.to_string()
};

let state = base();
let theme = state.theme;
let latch = AtomicBool::new(false);
let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
let (held_tx, held_rx) = std::sync::mpsc::channel::<()>();
let (drawing_tx, drawing_rx) = std::sync::mpsc::channel::<()>();

std::thread::scope(|scope| {
// `mpsc::Receiver` is `Send` but not `Sync`, so the halves the
// teardown thread uses are moved into it; the latch is shared as a
// plain reference (the whole point is that both threads see it).
let latch = &latch;
scope.spawn(move || {
// Stands in for `crate::app::restore_terminal()`, which takes this
// same lock around its escape bytes.
let guard = crate::app::lock_terminal_writer();
held_tx.send(()).expect("the drawing thread is alive");
drawing_rx.recv().expect("the drawing thread is alive");
// Only to make the unfixed code reliably red; the fixed path is
// correct for any duration, including zero.
std::thread::sleep(std::time::Duration::from_millis(200));
latch.store(true, std::sync::atomic::Ordering::SeqCst);
drop(guard);
});

held_rx.recv().expect("the teardown thread is alive");
drawing_tx.send(()).expect("the teardown thread is alive");
draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, latch)
.expect("the gate must not turn a suppressed frame into an error");
});

assert_eq!(
painted(&term),
"",
"a menu frame asked for while a teardown owned the terminal must not \
paint — its trailing `Hide` would land after the restore's `Show` and \
leave the user on the normal screen with an invisible cursor"
);
}

#[test]
fn the_front_door_comes_back_after_a_session_ends_cleanly() {
// The launcher-hub regression, at the seam the e2e scenario
// `dash-launcher-sigterm-restores-terminal-across-a-session` exercises
// end to end: open a session, quit back to the menu, and the front door
// must be there. `app::run`'s clean-quit teardown used to CLAIM the
// process-exit latch, which nothing ever releases — so the gate above
// suppressed every frame for the rest of the process and the user got a
// blank terminal instead of the menu.
//
// This is the cheap version of a 30-second PTY scenario: run the real
// teardown, then ask the real gate for a frame.
use std::sync::atomic::AtomicBool;

let latch = AtomicBool::new(false);
let restored = std::cell::Cell::new(false);
crate::app::restore_after_session(&latch, || restored.set(true));
assert!(restored.get(), "the session must restore the terminal");

let state = base();
let theme = state.theme;
let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, &latch)
.expect("drawing to a TestBackend cannot fail");
let painted: String = term
.backend()
.buffer()
.content()
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect();
assert!(
painted.contains("Set up this system"),
"the launcher front door must repaint once a session returns:\n{painted}"
);
}

fn base() -> AppState {
let mut s = AppState::new("t".into(), "default-dark".into());
s.latest = Some(Snapshot {
Expand Down
Loading
Loading