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
10 changes: 10 additions & 0 deletions crates/berth-page/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 { action, argument } => {
let args = json!({"action": action, "argument": argument});
self.call(
Expand Down
2 changes: 1 addition & 1 deletion crates/berth-tui/src/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub const OFFERS: &[(&str, &str, &str)] = &[
(
"terminal",
"Terminal",
"A shell on the host, in a panel here. Space switches between the agent account, with its tools on the PATH and the virtual desktop as its display, and the SSH user. It is a session of the host: Ctrl+Q leaves it running and it can be opened again from Sessions; exit or Ctrl+D ends it. The mouse wheel scrolls back. From the command line: `berth session attach HOST`.",
"A shell on the host, in a panel here. Space switches between the agent account, with its tools on the PATH and the virtual desktop as its display, and the SSH user. It is a session of the host: Ctrl+Q leaves it running and it can be opened again from Sessions; exit, Ctrl+D or Alt+X ends it. The mouse wheel scrolls back. From the command line: `berth session attach HOST`.",
),
(
"apply",
Expand Down
50 changes: 50 additions & 0 deletions crates/berth-tui/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub use berth_api::compat::NEEDS_HOST_API as NEEDS_API;
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 terminal ended from its panel has after the hangup before it is killed.
const END_PATIENCE: Duration = Duration::from_secs(5);

/// The way to one host. Requests are answered later, as events.
pub trait Transport {
Expand Down Expand Up @@ -49,6 +51,8 @@ pub enum Request {
action: String,
argument: String,
},
/// Send a session a signal: `INT`, `TERM`, `HUP` or `KILL`.
Signal(String, &'static str),
}

pub enum Event {
Expand Down Expand Up @@ -78,6 +82,18 @@ pub enum Event {
Error(String),
}

/// How far ending a terminal from its panel has got.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Ending {
No,
/// The panel asks whether to end it.
Asked,
/// It was sent a hangup, as closing a terminal window does, at that time.
HungUp(Instant),
/// It outlived the hangup and was killed.
Killed,
}

/// A session of the host shown in the terminal panel.
pub struct View {
pub id: String,
Expand All @@ -90,6 +106,7 @@ pub struct View {
pub ours: bool,
/// A shell: its panel closes by itself when it is left.
pub shell: bool,
pub ending: Ending,
/// The last bytes of output, for a question that arrives in two pieces.
tail: Vec<u8>,
}
Expand All @@ -105,6 +122,7 @@ impl View {
ended: None,
ours,
shell,
ending: Ending::No,
tail: vec![],
}
}
Expand All @@ -120,6 +138,7 @@ impl View {
ended: None,
ours: true,
shell: false,
ending: Ending::No,
tail: vec![],
}
}
Expand Down Expand Up @@ -460,6 +479,21 @@ impl HostView {
}
}

/// End the terminal in the panel: a hangup now, and a kill if it is
/// still running after [`END_PATIENCE`]. Its panel closes once it has ended.
pub fn end(&mut self) {
let Some(view) = self
.view
.as_mut()
.filter(|view| view.terminal && view.running())
else {
return;
};
view.ending = Ending::HungUp(Instant::now());
let id = view.id.clone();
self.send(Request::Signal(id, "HUP"));
}

/// Type into the session in the panel.
pub fn input(&self, bytes: Vec<u8>) {
if !bytes.is_empty() && self.view.as_ref().is_some_and(View::running) {
Expand Down Expand Up @@ -563,6 +597,22 @@ impl HostView {
}
}
}
if let Some(view) = self.view.as_mut() {
match view.ending {
Ending::HungUp(when) if view.running() && when.elapsed() >= END_PATIENCE => {
view.ending = Ending::Killed;
let id = view.id.clone();
self.send(Request::Signal(id, "KILL"));
}
// Ended from its panel: there is nothing left to look at.
Ending::HungUp(_) | Ending::Killed if !view.running() => {
let (ours, title) = (view.ours, view.title.clone());
self.close(ours);
note = Some(format!("{title} ended"));
}
_ => {}
}
}
if self.view.is_none()
&& matches!(self.state, State::Ready(_))
&& self.polled.elapsed() >= POLL
Expand Down
141 changes: 135 additions & 6 deletions crates/berth-tui/src/screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::{
event::{Click, Code, Event, Key, edit, paste},
host::{Arguments, HostView, View, argument_label},
host::{Arguments, Ending, HostView, View, argument_label},
theme,
};
use ratatui::{
Expand Down Expand Up @@ -355,13 +355,15 @@ pub fn words(line: &str) -> Vec<(u16, String)> {
}

/// Draw a session of the host: the same panel, with what leaving it means
/// there. Ctrl+Q leaves a running one.
/// there. Ctrl+Q leaves a running one, and Alt+X ends a running terminal.
pub fn draw_view(frame: &mut Frame, view: &View, note: &str) -> (Spots, Spots) {
let running = match view.terminal {
true => {
" Ctrl+V paste · Ctrl+Q leave it running · Click opens a link · Right-click copies · Wheel scrolls "
let running = match (view.terminal, view.ending) {
(true, Ending::No) => {
" Ctrl+Q leave it running · Alt+X end it · Ctrl+V paste · Click opens a link · Right-click copies · Wheel scrolls "
}
false => {
(true, Ending::Asked) => " End the session? It stops whatever runs in it · y yes · n no ",
(true, _) => " Ending the session… · Ctrl+Q leave it running ",
(false, _) => {
" Ctrl+Q leave it running · Click opens a link · Right-click copies · Wheel scrolls "
}
};
Expand Down Expand Up @@ -716,6 +718,20 @@ pub fn view_event(
});
} else if !view.terminal {
// A transcript takes no typing.
} else if view.ending == Ending::Asked {
// While it asks, keys answer it and do not reach the shell.
match key.code {
Code::Char('y' | 'Y') => {
host.end();
return Some("Ending the session".into());
}
Code::Char('n' | 'N') | Code::Esc => view.ending = Ending::No,
_ => {}
}
} else if view.ending != Ending::No {
// It is being ended; typing would go nowhere useful.
} else if key.alt && !key.ctrl && matches!(key.code, Code::Char('x' | 'X')) {
view.ending = Ending::Asked;
} else if key.is_ctrl('v') {
// Terminals that keep Ctrl+V to themselves paste by their own means.
return Some(match platform.paste() {
Expand Down Expand Up @@ -793,7 +809,120 @@ pub fn action_arguments_event(
#[cfg(test)]
mod tests {
use super::*;
use crate::host::{Event as HostEvent, Request, Transport};
use ratatui::{Terminal, backend::TestBackend};
use std::{cell::RefCell, collections::VecDeque, rc::Rc};

/// A host that keeps what it was asked and answers what it is given.
#[derive(Clone, Default)]
struct Recorder {
asked: Rc<RefCell<Vec<String>>>,
answers: Rc<RefCell<VecDeque<HostEvent>>>,
}

impl Transport for Recorder {
fn send(&self, request: Request) {
let said = match request {
Request::Signal(id, signal) => format!("signal {id} {signal}"),
Request::Input(bytes) => format!("input {}", String::from_utf8_lossy(&bytes)),
Request::Delete(id) => format!("delete {id}"),
Request::Close => "close".into(),
_ => return,
};
self.asked.borrow_mut().push(said);
}
fn next(&self) -> Option<HostEvent> {
self.answers.borrow_mut().pop_front()
}
}

struct Nowhere;

impl Platform for Nowhere {
fn copy(&mut self, _: &str) -> bool {
false
}
fn paste(&mut self) -> Option<String> {
None
}
fn open(&mut self, _: &str) -> Result<(), String> {
Ok(())
}
}

#[test]
fn a_terminal_is_ended_from_its_panel_after_a_yes() {
let recorder = Recorder::default();
let mut host = HostView::default();
host.connect(Box::new(recorder.clone()));
let session: berth_api::Session = serde_json::from_value(serde_json::json!({
"id": "s1", "kind": "terminal", "title": "agent on studio", "command": ["bash"],
"user": "agent", "started_by": {"level": "agent", "uid": 1000},
"started": "2026-01-01T00:00:00Z",
}))
.unwrap();
host.view = Some(View::new(&session, 10, 100, true, true));
let press = |host: &mut HostView, key: Key| {
view_event(host, &vec![], &vec![], &Event::Key(key), &mut Nowhere)
};
let alt_x = Key {
alt: true,
..Key::plain(Code::Char('x'))
};
// The footer offers it, and a click on the hint is the key.
let mut terminal = Terminal::new(TestBackend::new(110, 14)).unwrap();
terminal
.draw(|frame| {
draw_view(frame, host.view.as_ref().unwrap(), "");
})
.unwrap();
let buffer = terminal.backend().buffer();
let footer: String = (0..14)
.map(|y| {
(0..110)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
})
.find(|row| row.contains("Ctrl+Q"))
.unwrap_or_default();
assert!(footer.contains("Alt+X end it"), "{footer}");
assert_eq!(hint_key("Alt+X"), Some(alt_x));

// It asks first, and while it asks no key reaches the shell; no leaves it running.
press(&mut host, alt_x);
assert_eq!(host.view.as_ref().unwrap().ending, Ending::Asked);
press(&mut host, Key::plain(Code::Char('a')));
press(&mut host, Key::plain(Code::Char('n')));
assert_eq!(host.view.as_ref().unwrap().ending, Ending::No);
assert!(recorder.asked.borrow().is_empty());

// Yes hangs it up, and one still running after the patience is killed.
press(&mut host, alt_x);
press(&mut host, Key::plain(Code::Char('y')));
assert_eq!(*recorder.asked.borrow(), ["signal s1 HUP"]);
host.pump();
assert_eq!(recorder.asked.borrow().len(), 1);
host.view.as_mut().unwrap().ending =
Ending::HungUp(std::time::Instant::now() - std::time::Duration::from_secs(6));
host.pump();
assert_eq!(
*recorder.asked.borrow(),
["signal s1 HUP", "signal s1 KILL"]
);

// Once it has ended its panel closes, and a session started from the panel is forgotten.
recorder
.answers
.borrow_mut()
.push_back(HostEvent::Exited("s1".into(), None));
let note = host.pump();
assert!(host.view.is_none());
assert_eq!(note.as_deref(), Some("agent on studio ended"));
assert_eq!(
*recorder.asked.borrow(),
["signal s1 HUP", "signal s1 KILL", "close", "delete s1"]
);
}

fn screen(width: u16, height: u16, status: &str) -> Vec<String> {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
Expand Down
1 change: 1 addition & 0 deletions docs/content/docs/(guide)/use/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ The terminal and sign-ins run in a panel inside berth.
| 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 from the panel, after a yes. Whatever runs in it gets a hangup, and is killed if it still runs 5 seconds later |

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.

Expand Down
Loading