From d23d4692902211327515285c297cbf0699889688 Mon Sep 17 00:00:00 2001 From: ReaperMaga Date: Sun, 15 Nov 2026 04:35:11 +0100 Subject: [PATCH] feat(tui): end a terminal from its panel with Alt+X Co-Authored-By: Claude Opus 5.5 --- crates/berth-page/src/app.rs | 12 +- crates/berth-page/src/remote.rs | 10 + crates/berth-tui/src/host.rs | 216 +++++++++++++++++++++ crates/berth-tui/src/screen.rs | 65 ++++++- crates/berth/src/remote.rs | 7 + crates/berth/src/ui.rs | 8 +- docs/content/docs/(guide)/use/overview.mdx | 3 +- 7 files changed, 300 insertions(+), 21 deletions(-) diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index fa4080b..b1a34d7 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -367,15 +367,9 @@ impl App { if let Some(note) = self.host.pump() { self.status = note; } - // A shell that was left needs no key to close its panel. - if self - .host - .view - .as_ref() - .is_some_and(|view| view.shell && view.outcome() == Some(true)) - { - self.host.close(true); - } + // A shell that was left, or a session ended from its panel, needs + // no key to close its panel. + self.host.close_left(); let (width, height) = self.size; self.host.resize( height.saturating_sub(4).max(4), diff --git a/crates/berth-page/src/remote.rs b/crates/berth-page/src/remote.rs index 0229636..5a05f1a 100644 --- a/crates/berth-page/src/remote.rs +++ b/crates/berth-page/src/remote.rs @@ -245,6 +245,16 @@ impl Transport for Remote { }, ); } + Request::Signal(id, signal) => self.call( + "sessions.signal", + json!({"id": id}), + json!({"signal": signal}), + |result, events| { + if let Err(error) = result { + events.borrow_mut().push_back(Event::Error(error)); + } + }, + ), Request::Choices { task, argument } => { let args = json!({"name": task, "argument": argument}); self.call("tasks.choices", args, Value::Null, move |result, events| { diff --git a/crates/berth-tui/src/host.rs b/crates/berth-tui/src/host.rs index 23ac5a3..c21fa68 100644 --- a/crates/berth-tui/src/host.rs +++ b/crates/berth-tui/src/host.rs @@ -16,6 +16,8 @@ pub const NEEDS_API: u32 = 1; const POLL: Duration = Duration::from_secs(10); /// Lines of a process session's transcript kept for scrolling back. const HISTORY: usize = 5000; +/// How long a session that was hung up has to end before it is killed. +const HANG_UP: Duration = Duration::from_secs(5); /// The way to one host. Requests are answered later, as events. pub trait Transport { @@ -44,6 +46,8 @@ pub enum Request { Resize(u16, u16), Close, Delete(String), + /// Send a signal, such as `HUP`, to what a session runs. + Signal(String, String), Choices { task: String, argument: String, @@ -91,6 +95,21 @@ pub struct View { pub shell: bool, /// The last bytes of output, for a question that arrives in two pieces. tail: Vec, + /// Whether it was asked to end from the panel. + pub exit: Exit, +} + +/// Ending a session from its panel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Exit { + /// Nobody asked it to end. + No, + /// The exit key was pressed, and the panel asks first. + Asked, + /// It was hung up then; it is killed when it runs on too long after. + HungUp(Instant), + /// It ran on after the hangup and was killed. + Killed, } impl View { @@ -105,6 +124,7 @@ impl View { ours, shell, tail: vec![], + exit: Exit::No, } } @@ -120,6 +140,7 @@ impl View { ours: true, shell: false, tail: vec![], + exit: Exit::No, } } @@ -136,6 +157,21 @@ impl View { self.ended.map(|code| code == Some(0)) } + /// Whether the panel offers to end it: a running terminal, which has + /// no other way out than what runs in it. + pub fn can_exit(&self) -> bool { + self.terminal && self.running() && !self.id.is_empty() + } + + /// Whether it has ended in a way that needs no key to close its panel: + /// a shell that was left, or a session ended from the panel. + pub fn left(&self) -> bool { + match self.exit { + Exit::HungUp(_) | Exit::Killed => !self.running(), + Exit::No | Exit::Asked => self.shell && self.outcome() == Some(true), + } + } + /// Take in output. Returns what a terminal answers by itself: programs /// ask where the cursor is and wait, and with a viewer attached the host /// leaves the answer to the viewer. @@ -438,6 +474,31 @@ impl HostView { } } + /// Close the panel once its session was left. Returns whether it closed. + pub fn close_left(&mut self) -> bool { + let Some(view) = &self.view else { + return false; + }; + if !view.left() { + return false; + } + // A session ended from its panel is forgotten as Enter would. + let forget = view.exit == Exit::No || view.ours; + self.close(forget); + true + } + + /// End the session in the panel: hang it up, as closing a terminal + /// window would, and kill it if it runs on. + pub fn end(&mut self) { + let Some(view) = self.view.as_mut().filter(|view| view.can_exit()) else { + return; + }; + view.exit = Exit::HungUp(Instant::now()); + let id = view.id.clone(); + self.send(Request::Signal(id, "HUP".into())); + } + /// Type into the session in the panel. pub fn input(&self, bytes: Vec) { if !bytes.is_empty() && self.view.as_ref().is_some_and(View::running) { @@ -541,6 +602,15 @@ impl HostView { } } } + if let Some(view) = self.view.as_mut() + && let Exit::HungUp(since) = view.exit + && view.running() + && since.elapsed() >= HANG_UP + { + view.exit = Exit::Killed; + let id = view.id.clone(); + self.send(Request::Signal(id, "KILL".into())); + } if self.view.is_none() && matches!(self.state, State::Ready(_)) && self.polled.elapsed() >= POLL @@ -743,6 +813,152 @@ pub fn session_help(host: &HostView, index: usize) -> String { #[cfg(test)] mod tests { use super::*; + use crate::event::{Click, Code, Event as Input, Mouse}; + use crate::screen::{Platform, draw_view, hint_at, hint_click, view_event}; + use ratatui::{Terminal, backend::TestBackend}; + use std::{cell::RefCell, collections::VecDeque, rc::Rc}; + + /// A host that keeps what it was asked and answers with what a test gives it. + #[derive(Clone, Default)] + struct Fake { + sent: Rc>>, + events: Rc>>, + } + + impl Transport for Fake { + fn send(&self, request: Request) { + let said = match request { + Request::Signal(id, signal) => format!("signal {id} {signal}"), + Request::Delete(id) => format!("delete {id}"), + Request::Input(bytes) => format!("input {}", String::from_utf8_lossy(&bytes)), + Request::Close => "close".into(), + _ => return, + }; + self.sent.borrow_mut().push(said); + } + fn next(&self) -> Option { + self.events.borrow_mut().pop_front() + } + } + + struct Nowhere; + + impl Platform for Nowhere { + fn copy(&mut self, _: &str) -> bool { + false + } + fn paste(&mut self) -> Option { + None + } + fn open(&mut self, _: &str) -> Result<(), String> { + Ok(()) + } + } + + /// The panel as drawn, a row a line. + fn drawn(host: &HostView) -> String { + let mut terminal = Terminal::new(TestBackend::new(160, 30)).unwrap(); + terminal + .draw(|frame| { + draw_view(frame, host.view.as_ref().unwrap(), "", "Alt+Q"); + }) + .unwrap(); + let buffer = terminal.backend().buffer().clone(); + (0..30) + .map(|y| { + (0..160) + .map(|x| buffer[(x, y)].symbol().to_owned()) + .collect::() + + "\n" + }) + .collect() + } + + fn press(host: &mut HostView, event: Input) { + view_event(host, &vec![], &vec![], &hint_click(event), &mut Nowhere); + } + + fn key(code: Code) -> Input { + Input::Key(Key::plain(code)) + } + + #[test] + fn a_terminal_is_ended_from_its_panel_after_a_yes() { + let fake = Fake::default(); + let mut host = HostView { + size: (20, 100), + ..HostView::default() + }; + host.connect(Box::new(fake.clone())); + host.starting = Some(true); + let session: api::Session = serde_json::from_value(json!({ + "id": "s1", "kind": "terminal", "title": "agent on studio", + "command": ["bash", "-l"], "user": "agent", + "started_by": {"level": "host", "uid": 0}, "started": "2026-11-12T10:00:00Z", + })) + .unwrap(); + fake.events + .borrow_mut() + .push_back(Event::Opened(Box::new(session))); + host.pump(); + assert!(host.view.as_ref().is_some_and(View::can_exit)); + + // The footer offers it, and a click on the hint is the key. + let text = drawn(&host); + assert!( + text.contains("Alt+Q leave it running Alt+X exit"), + "{text}" + ); + let exit = crate::screen::hint_key("Alt+X").unwrap(); + let (column, row) = (0..30) + .flat_map(|row| (0..160).map(move |column| (column, row))) + .find(|(column, row)| hint_at(*column, *row) == Some(exit)) + .unwrap(); + press( + &mut host, + Input::Mouse(Mouse { + click: Click::Left, + column, + row, + }), + ); + assert_eq!(host.view.as_ref().unwrap().exit, Exit::Asked); + assert!(drawn(&host).contains("End the session \"agent on studio\"?")); + + // While it asks, typing goes nowhere, and no takes it back. + press(&mut host, key(Code::Char('a'))); + press(&mut host, key(Code::Char('n'))); + assert_eq!(host.view.as_ref().unwrap().exit, Exit::No); + assert!(fake.sent.borrow().is_empty()); + + // Yes hangs it up. + press( + &mut host, + Input::Key(Key { + alt: true, + ..Key::plain(Code::Char('x')) + }), + ); + press(&mut host, key(Code::Char('y'))); + assert_eq!(*fake.sent.borrow(), ["signal s1 HUP"]); + assert!(drawn(&host).contains("Ending the session…")); + + // One that runs on after the hangup is killed. + host.view.as_mut().unwrap().exit = + Exit::HungUp(Instant::now().checked_sub(HANG_UP).unwrap()); + host.pump(); + assert_eq!(host.view.as_ref().unwrap().exit, Exit::Killed); + assert_eq!(fake.sent.borrow().last().unwrap(), "signal s1 KILL"); + + // Once it has ended, its panel closes and, started here, it is forgotten. + fake.events + .borrow_mut() + .push_back(Event::Exited("s1".into(), Some(137))); + host.pump(); + assert!(host.close_left()); + assert!(host.view.is_none()); + assert_eq!(fake.sent.borrow()[2..], ["close", "delete s1"]); + } #[test] fn berths_own_actions_follow_the_tasks_and_say_when_they_cannot_run() { diff --git a/crates/berth-tui/src/screen.rs b/crates/berth-tui/src/screen.rs index 12255b9..1e627e5 100644 --- a/crates/berth-tui/src/screen.rs +++ b/crates/berth-tui/src/screen.rs @@ -3,7 +3,7 @@ use crate::{ event::{Click, Code, Event, Key, edit, paste}, - host::{Arguments, HostView, View, argument_label}, + host::{Arguments, Exit, HostView, View, argument_label}, theme, }; use ratatui::{ @@ -316,15 +316,27 @@ pub fn words(line: &str) -> Vec<(u16, String)> { found } +/// The key that ends a running terminal from its panel. A shell has no use +/// for it, as it has none for Alt+Q. +pub const EXIT: &str = "Alt+X"; + +/// Whether `key` is [`EXIT`]. +fn is_exit(key: &Key) -> bool { + key.alt && !key.ctrl && matches!(key.code, Code::Char('x' | 'X')) +} + /// Draw a session of the host: the same panel, with what leaving it means /// there. `leave` is the key that leaves a running one: `Ctrl+Q`, or `Alt+Q` /// where Ctrl+Q is not the page's to take. pub fn draw_view(frame: &mut Frame, view: &View, note: &str, leave: &str) -> (Spots, Spots) { - let running = match view.terminal { - true => format!( - " Ctrl+V paste · {leave} leave it running · Click opens a link · Right-click copies · Wheel scrolls " + let running = match (view.terminal, view.exit) { + (true, Exit::HungUp(_) | Exit::Killed) => { + format!(" Ending the session… · {leave} leave it running ") + } + (true, _) => format!( + " Ctrl+V paste · {leave} leave it running · {EXIT} exit · Click opens a link · Right-click copies · Wheel scrolls " ), - false => format!( + (false, _) => format!( " {leave} leave it running · Click opens a link · Right-click copies · Wheel scrolls " ), }; @@ -335,14 +347,25 @@ pub fn draw_view(frame: &mut Frame, view: &View, note: &str, leave: &str) -> (Sp (Some(true), false) => " ✓ Done · Enter close · d forget it ", (Some(false), false) => " ✗ It did not finish · Enter close · d forget it ", }; - draw_panel( + let spots = draw_panel( frame, &view.title, view.screen(), view.outcome(), keys, note, - ) + ); + if view.exit == Exit::Asked && view.can_exit() { + draw_question( + frame, + &format!( + "End the session \"{}\"? This stops whatever runs in it.", + view.title + ), + ); + return (vec![], vec![]); + } + spots } /// The terminal panel: a screen, in a box coloured by how the command fared. @@ -647,6 +670,13 @@ pub fn view_event( event: &Event, platform: &mut dyn Platform, ) -> Option { + if host + .view + .as_ref() + .is_some_and(|view| view.exit == Exit::Asked && view.can_exit()) + { + return exit_question_event(host, event); + } if let Some(said) = spot_event(links, words, event, platform) { return (!said.is_empty()).then_some(said); } @@ -679,6 +709,10 @@ pub fn view_event( }); } else if !view.terminal { // A transcript takes no typing. + } else if is_exit(key) { + if view.can_exit() && view.exit == Exit::No { + view.exit = Exit::Asked; + } } else if key.is_ctrl('v') { // Terminals that keep Ctrl+V to themselves paste by their own means. return Some(match platform.paste() { @@ -699,6 +733,23 @@ pub fn view_event( None } +/// Keys of the question before a session is ended from its panel. +fn exit_question_event(host: &mut HostView, event: &Event) -> Option { + let Event::Key(key) = event else { + return None; + }; + match key.code { + Code::Char('y' | 'Y') => host.end(), + Code::Char('n' | 'N') | Code::Esc => { + if let Some(view) = &mut host.view { + view.exit = Exit::No; + } + } + _ => {} + } + None +} + /// Keys of the dialog that asks for a task's arguments. Returns whether the /// value was accepted, for the caller to go on with. pub fn arguments_event( diff --git a/crates/berth/src/remote.rs b/crates/berth/src/remote.rs index 100801b..c879049 100644 --- a/crates/berth/src/remote.rs +++ b/crates/berth/src/remote.rs @@ -193,6 +193,13 @@ async fn worker( } refresh(link, events, false, None).await; })), + Request::Signal(id, signal) => drop(tokio::spawn(async move { + let path = format!("/v1/sessions/{id}/signal"); + let body = json!({ "signal": signal }); + if let Err(error) = link.post::(&path, &body).await { + let _ = events.send(Event::Error(error.to_string())); + } + })), Request::Choices { task, argument } => drop(tokio::spawn(async move { let path = format!( "/v1/tasks/{}/choices/{}", diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs index f0540fa..249b05b 100644 --- a/crates/berth/src/ui.rs +++ b/crates/berth/src/ui.rs @@ -3190,10 +3190,10 @@ pub fn run( session_event(app, &event); continue; } - if let Some(view) = &app.host.view { - // A shell that was left needs no key to close its panel. - if view.shell && view.outcome() == Some(true) { - app.host.close(true); + if app.host.view.is_some() { + // A shell that was left, or a session ended from its panel, + // needs no key to close its panel. + if app.host.close_left() { continue; } if !crate::keys::poll(std::time::Duration::from_millis(40))? { diff --git a/docs/content/docs/(guide)/use/overview.mdx b/docs/content/docs/(guide)/use/overview.mdx index 7bc13cc..7b72e3c 100644 --- a/docs/content/docs/(guide)/use/overview.mdx +++ b/docs/content/docs/(guide)/use/overview.mdx @@ -50,7 +50,8 @@ The terminal and sign-ins run in a panel inside berth. | Ctrl+V | Pastes | | Mouse wheel | Scrolls back | | Ctrl+Q | Leaves the panel; a terminal keeps running | -| `exit` or Ctrl+D | Ends a terminal | +| Alt+X | Ends a terminal and closes the panel, after a yes. A click on its hint does the same | +| `exit` or Ctrl+D | Ends a terminal from inside it | A long web address that runs over several rows is one link, even when the program in the panel breaks it into lines of its own. Clicking it, copying it and its QR code all take the whole address.