//! Headless terminal owner. Clients are replaceable views of this process's state. //! //! A single actor serializes layout and terminal commands. PTY workers parse //! bytes independently; per-client writers keep only the newest unsent grid. use std::{ collections::{HashMap, VecDeque}, fs::{self, File, OpenOptions}, os::{ fd::AsRawFd, unix::{ fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}, net::{UnixListener, UnixStream}, }, }, path::{Path, PathBuf}, sync::{Arc, Condvar, Mutex, mpsc}, thread::{self, JoinHandle}, time::{Duration, Instant}, }; use alacritty_terminal::{ event::Event, grid::{Dimensions, Scroll}, index::{Column, Line, Point, Side}, selection::{Selection, SelectionType}, term::color::COUNT, tty::Shell, }; use anyhow::{Context, Result, ensure}; use crate::{ protocol::{self, *}, session::Session, }; const FRAME_INTERVAL: Duration = Duration::from_millis(8); const CWD_REFRESH_INTERVAL: Duration = Duration::from_millis(500); const MAX_CLIENTS: usize = 64; const MAX_PANES: usize = 64; const MAX_GRID_CELLS: usize = 100_000; struct Pane { session: Session, program_title: Option, manual_title: Option, cwd: String, exited: bool, } impl Pane { fn title(&self) -> String { self.manual_title .as_ref() .or(self.program_title.as_ref()) .cloned() .unwrap_or_else(|| { // Resolve HOME here so SSH clients use the server's home, // while the snapshot's cwd keeps its full filesystem path. let home = std::env::var_os("HOME").map(PathBuf::from); directory_title(&self.cwd, home.as_deref()) }) } } fn directory_title(cwd: &str, home: Option<&Path>) -> String { let relative = home .filter(|home| home.is_absolute()) .and_then(|home| Path::new(cwd).strip_prefix(home).ok()); let title = match relative { Some(path) if path.as_os_str().is_empty() => "~".to_owned(), Some(path) => format!("~/{}", path.display()), None => cwd.to_owned(), }; title .chars() .filter(|c| !c.is_control()) .take(512) .collect() } fn clean_title(title: String) -> Option { let title: String = title .chars() .filter(|c| !c.is_control()) .take(512) .collect(); let title = title.trim(); (!title.is_empty()).then(|| title.to_owned()) } fn single_pane_stack(pane: PaneId) -> StackInfo { StackInfo { panes: vec![StackPaneInfo { id: pane, title: "Shell".into(), }], active_pane: pane, } } fn flatten_panes(tab: &mut TabInfo) { tab.panes = tab .stacks .iter() .flat_map(|stack| stack.panes.iter().map(|pane| pane.id)) .collect(); } struct Client { authenticated: bool, attached: bool, output: Arc, writer: JoinHandle<()>, } enum Action { Connected(u64, UnixStream), Command(u64, ClientMessage), Disconnected(u64), Terminal(PaneId, Event), } #[derive(Default)] struct PendingOutput { reliable: VecDeque, latest: Option>, closed: bool, } #[derive(Default)] struct Outbox { pending: Mutex, ready: Condvar, } impl Outbox { fn reliable(&self, message: ServerMessage) { let mut pending = self.pending.lock().unwrap(); if pending.closed { return; } // Commands from a non-reading peer must not consume unbounded memory. if pending.reliable.len() >= 128 { pending.closed = true; pending.latest = None; } else { pending.reliable.push_back(message); } self.ready.notify_one(); } fn snapshot(&self, snapshot: Arc) { let mut pending = self.pending.lock().unwrap(); if !pending.closed { pending.latest = Some(snapshot); self.ready.notify_one(); } } fn close(&self) { let mut pending = self.pending.lock().unwrap(); pending.closed = true; pending.latest = None; self.ready.notify_one(); } fn next(&self) -> Option { let mut pending = self.pending.lock().unwrap(); loop { if let Some(message) = pending.reliable.pop_front() { return Some(message); } if pending.closed { return None; } if let Some(snapshot) = pending.latest.take() { return Some(ServerMessage::Snapshot((*snapshot).clone())); } pending = self.ready.wait(pending).unwrap(); } } } /// Run the headless server. The caller handles platform-specific window launches. pub fn run(socket: &Path, open_window: impl FnMut(Option) -> Result<()>) -> Result<()> { run_with_shell(socket, open_window, None) } fn run_with_shell( socket: &Path, mut open_window: impl FnMut(Option) -> Result<()>, shell: Option, ) -> Result<()> { let (_socket_guard, listener) = bind_socket(socket)?; let (sender, receiver) = mpsc::sync_channel(1024); let accept_sender = sender.clone(); let accept = thread::Builder::new() .name("psyterm-accept".into()) .spawn(move || { let mut next_client = 1; for accepted in listener.incoming() { let stream = match accepted { Ok(stream) => stream, Err(error) => { log::error!("accept: {error}"); break; } }; if crate::launcher::verify_peer(&stream).is_err() { continue; } let reader = match stream.try_clone() { Ok(stream) => stream, Err(_) => continue, }; let client = next_client; next_client += 1; if accept_sender .send(Action::Connected(client, stream)) .is_err() { break; } let sender = accept_sender.clone(); thread::spawn(move || read_client(client, reader, sender)); } })?; // The listener is woken explicitly on shutdown; the accept thread exits once // the actor channel receiver is dropped. let mut actor = Server { shell, panes: HashMap::new(), tabs: Vec::new(), active_tab: 0, next_id: 1, clients: HashMap::new(), sender, revision: 0, dirty: false, last_frame: Instant::now() - FRAME_INTERVAL, last_cwd_refresh: Instant::now(), }; let result = actor.run(&receiver, &mut open_window); drop(receiver); for client in actor.clients.values() { client.output.reliable(ServerMessage::Closing); client.output.close(); } for (_, client) in actor.clients.drain() { let _ = client.writer.join(); } // Drop sessions while the daemon is alive so their PTYs/children are reaped. actor.panes.clear(); let _ = UnixStream::connect(socket); let _ = accept.join(); result } fn read_client(id: u64, mut stream: UnixStream, sender: mpsc::SyncSender) { // Bound pre-handshake connections. Authenticated peers may remain idle. let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); let mut first = true; loop { let message = match protocol::read_message(&mut stream) { Ok(message) => message, Err(_) => break, }; if first { if !matches!(message, ClientMessage::Hello { .. }) { break; } first = false; let _ = stream.set_read_timeout(None); } let detach = matches!(message, ClientMessage::Detach); if sender.send(Action::Command(id, message)).is_err() { break; } if detach { break; } } let _ = stream.shutdown(std::net::Shutdown::Both); let _ = sender.send(Action::Disconnected(id)); } struct Server { shell: Option, panes: HashMap, tabs: Vec, active_tab: TabId, next_id: u64, clients: HashMap, sender: mpsc::SyncSender, revision: u64, dirty: bool, last_frame: Instant, last_cwd_refresh: Instant, } impl Server { fn run( &mut self, receiver: &mpsc::Receiver, open_window: &mut impl FnMut(Option) -> Result<()>, ) -> Result<()> { loop { let until_cwd = CWD_REFRESH_INTERVAL.saturating_sub(self.last_cwd_refresh.elapsed()); let timeout = if self.dirty { Some( FRAME_INTERVAL .saturating_sub(self.last_frame.elapsed()) .min(until_cwd), ) } else if !self.panes.is_empty() { Some(until_cwd) } else { None }; let action = if let Some(timeout) = timeout { match receiver.recv_timeout(timeout) { Ok(action) => Some(action), Err(mpsc::RecvTimeoutError::Timeout) => None, Err(mpsc::RecvTimeoutError::Disconnected) => break, } } else { match receiver.recv() { Ok(action) => Some(action), Err(_) => break, } }; if let Some(action) = action { match action { Action::Connected(id, stream) => { if let Err(error) = self.add_client(id, stream) { log::warn!("could not attach client: {error}"); } } Action::Disconnected(id) => self.remove_client(id), Action::Terminal(pane, event) => self.terminal_event(pane, event), Action::Command(id, command) => { if matches!(command, ClientMessage::Shutdown) && self .clients .get(&id) .is_some_and(|client| client.authenticated) { break; } if let Err(error) = self.command(id, command, open_window) && let Some(client) = self.clients.get(&id) { client .output .reliable(ServerMessage::Error(format!("{error:#}"))); } } } } if self.last_cwd_refresh.elapsed() >= CWD_REFRESH_INTERVAL { self.refresh_directories(); self.last_cwd_refresh = Instant::now(); } if self.dirty && self.last_frame.elapsed() >= FRAME_INTERVAL { self.publish(); self.dirty = false; self.last_frame = Instant::now(); } } Ok(()) } fn add_client(&mut self, id: u64, mut stream: UnixStream) -> Result<()> { if self.clients.len() >= MAX_CLIENTS { let _ = stream.shutdown(std::net::Shutdown::Both); return Ok(()); } stream.set_write_timeout(Some(Duration::from_secs(5)))?; let output = Arc::new(Outbox::default()); let writer_output = output.clone(); let sender = self.sender.clone(); let writer = thread::Builder::new() .name("psyterm-client-write".into()) .spawn(move || { while let Some(message) = writer_output.next() { if protocol::write_message(&mut stream, &message).is_err() { break; } } let _ = stream.shutdown(std::net::Shutdown::Both); let _ = sender.send(Action::Disconnected(id)); })?; self.clients.insert( id, Client { authenticated: false, attached: false, output, writer, }, ); Ok(()) } fn remove_client(&mut self, id: u64) { if let Some(client) = self.clients.remove(&id) { client.output.close(); } // Deliberately retain every tab, pane, grid and child process. } fn command( &mut self, id: u64, message: ClientMessage, open_window: &mut impl FnMut(Option) -> Result<()>, ) -> Result<()> { let Some(client) = self.clients.get_mut(&id) else { return Ok(()); }; if let ClientMessage::Hello { version } = message { ensure!(!client.authenticated, "handshake already completed"); ensure!( version == VERSION, "protocol version {version} is unsupported (expected {VERSION})" ); client.authenticated = true; client.output.reliable(ServerMessage::Hello { version: VERSION, server_pid: std::process::id(), }); return Ok(()); } ensure!(client.authenticated, "protocol handshake is required"); match message { ClientMessage::Attach => { client.attached = true; if self.tabs.is_empty() { self.new_tab(None)?; } // New attachment receives an authoritative snapshot immediately. self.publish(); self.last_frame = Instant::now(); self.dirty = false; } ClientMessage::Ping => client.output.reliable(ServerMessage::Pong), ClientMessage::List => { let snapshot = self.snapshot(); self.clients[&id] .output .reliable(ServerMessage::Snapshot(snapshot)); } ClientMessage::OpenWindow { target } => { open_window(target)?; self.clients[&id].output.reliable(ServerMessage::Pong); } ClientMessage::Detach => self.remove_client(id), ClientMessage::Input { pane, bytes } => { ensure!(bytes.len() <= 1024 * 1024, "input exceeds one MiB"); let pane = self.pane_mut(pane)?; ensure!(!pane.exited, "the shell has exited"); let changed = { let mut term = pane.session.term.lock(); let changed = term.grid().display_offset() != 0 || term.selection.is_some(); term.scroll_display(Scroll::Bottom); term.selection = None; changed }; pane.session.write(bytes); self.dirty |= changed; } ClientMessage::Resize { pane, columns, lines, cell_width, cell_height, } => { ensure!( columns >= 2 && lines >= 1 && columns as usize * lines as usize <= MAX_GRID_CELLS, "invalid terminal dimensions" ); let siblings = self .tabs .iter() .find(|tab| tab.panes.contains(&pane)) .context("unknown pane")?; let other_cells: usize = siblings .panes .iter() .filter(|id| **id != pane) .filter_map(|id| self.panes.get(id)) .map(|pane| { let size = pane.session.size(); size.num_cols as usize * size.num_lines as usize }) .sum(); ensure!( other_cells + columns as usize * lines as usize <= MAX_GRID_CELLS, "tab grid exceeds {MAX_GRID_CELLS} cells" ); self.pane_mut(pane)?.session.resize( columns as usize, lines as usize, cell_width, cell_height, ); self.dirty = true; } ClientMessage::Scroll { pane, kind } => { let scroll = match kind { ScrollKind::Delta(n) => Scroll::Delta(n), ScrollKind::PageUp => Scroll::PageUp, ScrollKind::PageDown => Scroll::PageDown, ScrollKind::Top => Scroll::Top, ScrollKind::Bottom => Scroll::Bottom, }; self.pane_mut(pane)? .session .term .lock() .scroll_display(scroll); self.dirty = true; } ClientMessage::Selection { pane, selection } => { let pane = self.pane_mut(pane)?; let mut term = pane.session.term.lock(); let location = |column: u16, row: u16| { Point::new( Line( row.min(term.screen_lines() as u16 - 1) as i32 - term.grid().display_offset() as i32, ), Column((column as usize).min(term.columns() - 1)), ) }; let side = |side| match side { SelectionSide::Left => Side::Left, SelectionSide::Right => Side::Right, }; match selection { SelectionCommand::Start { column, row, side: s, kind, } => { let kind = match kind { SelectionKind::Simple => SelectionType::Simple, SelectionKind::Word => SelectionType::Semantic, SelectionKind::Line => SelectionType::Lines, }; term.selection = Some(Selection::new(kind, location(column, row), side(s))); } SelectionCommand::Update { column, row, side: s, } => { let point = location(column, row); if let Some(selection) = &mut term.selection { selection.update(point, side(s)); } } SelectionCommand::Clear => term.selection = None, } drop(term); self.dirty = true; } ClientMessage::Copy { pane } => { let text = self .pane_mut(pane)? .session .term .lock() .selection_to_string(); if let Some(text) = text { self.clients[&id] .output .reliable(ServerMessage::Clipboard(text)); } } ClientMessage::NewTab { cwd } => { self.new_tab(cwd)?; self.dirty = true; } ClientMessage::Split { pane, cwd } => { let (tab_index, stack_index, _) = self.pane_position(pane)?; self.ensure_new_pane_fits(tab_index)?; let pane = self.new_pane(cwd)?; let tab = &mut self.tabs[tab_index]; tab.stacks.insert(stack_index + 1, single_pane_stack(pane)); flatten_panes(tab); tab.active_pane = pane; self.active_tab = tab.id; self.dirty = true; } ClientMessage::NewStackPane { pane, direction, cwd, } => { let pane = pane .or_else(|| { self.tabs .iter() .find(|tab| tab.id == self.active_tab) .map(|tab| tab.active_pane) }) .context("no active pane")?; let (tab_index, stack_index, pane_index) = self.pane_position(pane)?; self.ensure_new_pane_fits(tab_index)?; let pane = self.new_pane(cwd)?; let tab = &mut self.tabs[tab_index]; let stack = &mut tab.stacks[stack_index]; let insert_at = pane_index + usize::from(direction == VerticalDirection::Down); stack.panes.insert( insert_at, StackPaneInfo { id: pane, title: "Shell".into(), }, ); stack.active_pane = pane; tab.active_pane = pane; flatten_panes(tab); self.active_tab = tab.id; self.dirty = true; } ClientMessage::FocusStackPane { pane, direction } => { self.focus_stack_pane(pane, direction)?; } ClientMessage::FocusDirection { direction } => { self.focus_direction(direction)?; } ClientMessage::CycleTab { forward } => self.cycle_tab(forward), ClientMessage::CyclePane { forward } => self.cycle_pane(forward)?, ClientMessage::FocusTab { tab } => { ensure!(self.tabs.iter().any(|entry| entry.id == tab), "unknown tab"); self.active_tab = tab; self.dirty = true; } ClientMessage::FocusPane { pane } => { self.focus_pane(pane)?; } ClientMessage::ClosePane { pane } => { ensure!(self.remove_pane(pane), "unknown pane"); } ClientMessage::RenamePane { pane, name } => { self.pane_mut(pane)?.manual_title = name.and_then(clean_title); self.refresh_directories(); self.dirty = true; } ClientMessage::RenameTab { tab, name } => { self.tabs .iter_mut() .find(|entry| entry.id == tab) .context("unknown tab")? .manual_title = name.and_then(clean_title); self.refresh_directories(); self.dirty = true; } ClientMessage::Hello { .. } | ClientMessage::Shutdown => unreachable!(), } Ok(()) } fn pane_position(&self, pane: PaneId) -> Result<(usize, usize, usize)> { for (tab_index, tab) in self.tabs.iter().enumerate() { for (stack_index, stack) in tab.stacks.iter().enumerate() { if let Some(pane_index) = stack.panes.iter().position(|entry| entry.id == pane) { return Ok((tab_index, stack_index, pane_index)); } } } anyhow::bail!("unknown pane") } fn ensure_new_pane_fits(&self, tab_index: usize) -> Result<()> { let occupied: usize = self.tabs[tab_index] .panes .iter() .filter_map(|id| self.panes.get(id)) .map(|pane| { let size = pane.session.size(); size.num_cols as usize * size.num_lines as usize }) .sum(); ensure!( occupied + 80 * 24 <= MAX_GRID_CELLS, "tab grid exceeds {MAX_GRID_CELLS} cells" ); Ok(()) } fn focus_pane(&mut self, pane: PaneId) -> Result<()> { let (tab_index, stack_index, _) = self.pane_position(pane)?; let tab = &mut self.tabs[tab_index]; tab.stacks[stack_index].active_pane = pane; tab.active_pane = pane; self.active_tab = tab.id; self.dirty = true; Ok(()) } fn focus_stack_pane(&mut self, pane: PaneId, direction: VerticalDirection) -> Result<()> { let (tab_index, stack_index, pane_index) = self.pane_position(pane)?; let stack = &self.tabs[tab_index].stacks[stack_index]; let next = match direction { VerticalDirection::Up => pane_index.checked_sub(1), VerticalDirection::Down => { (pane_index + 1 < stack.panes.len()).then_some(pane_index + 1) } }; if let Some(index) = next { self.focus_pane(stack.panes[index].id)?; } Ok(()) } fn cycle_tab(&mut self, forward: bool) { let Some(index) = self.tabs.iter().position(|tab| tab.id == self.active_tab) else { return; }; let count = self.tabs.len(); let next = if forward { (index + 1) % count } else { (index + count - 1) % count }; self.active_tab = self.tabs[next].id; self.dirty = true; } fn cycle_pane(&mut self, forward: bool) -> Result<()> { let Some(tab) = self.tabs.iter().find(|tab| tab.id == self.active_tab) else { return Ok(()); }; let index = tab .stacks .iter() .position(|stack| stack.active_pane == tab.active_pane) .context("focused pane is not expanded")?; let count = tab.stacks.len(); let next = if forward { (index + 1) % count } else { (index + count - 1) % count }; self.focus_pane(tab.stacks[next].active_pane) } fn focus_direction(&mut self, direction: Direction) -> Result<()> { let Some(tab_index) = self.tabs.iter().position(|tab| tab.id == self.active_tab) else { return Ok(()); }; let pane = self.tabs[tab_index].active_pane; match direction { Direction::Up => self.focus_stack_pane(pane, VerticalDirection::Up), Direction::Down => self.focus_stack_pane(pane, VerticalDirection::Down), Direction::Left | Direction::Right => { let (_, stack_index, _) = self.pane_position(pane)?; let tab = &self.tabs[tab_index]; let next = if direction == Direction::Left { stack_index.checked_sub(1) } else { (stack_index + 1 < tab.stacks.len()).then_some(stack_index + 1) }; if let Some(index) = next { self.focus_pane(tab.stacks[index].active_pane)?; } else { self.cycle_tab(direction == Direction::Right); } Ok(()) } } } /// The same lifecycle path serves explicit close and a shell's natural exit. fn remove_pane(&mut self, pane: PaneId) -> bool { let Some(removed) = self.panes.remove(&pane) else { return false; }; if let Ok((tab_index, stack_index, pane_index)) = self.pane_position(pane) { let tab = &mut self.tabs[tab_index]; let stack = &mut tab.stacks[stack_index]; stack.panes.remove(pane_index); if stack.active_pane == pane { stack.active_pane = stack .panes .get(pane_index.min(stack.panes.len().saturating_sub(1))) .map_or(0, |entry| entry.id); } let replacement = stack.active_pane; if stack.panes.is_empty() { tab.stacks.remove(stack_index); } if tab.active_pane == pane { tab.active_pane = if replacement != 0 { replacement } else { tab.stacks .get(stack_index.min(tab.stacks.len().saturating_sub(1))) .map_or(0, |stack| stack.active_pane) }; } flatten_panes(tab); if tab.stacks.is_empty() { let removed_tab = self.tabs.remove(tab_index); if self.active_tab == removed_tab.id { self.active_tab = self .tabs .get(tab_index.min(self.tabs.len().saturating_sub(1))) .map_or(0, |tab| tab.id); } } } self.dirty = true; // No terminal lock is held here. On Event::Exit the I/O thread has // drained output and will finish, so joining Session cleanup is safe. drop(removed); true } fn refresh_directories(&mut self) { for pane in self.panes.values_mut() { if let Some(directory) = pane.session.working_directory() { let directory = directory.to_string_lossy(); if pane.cwd != directory { pane.cwd = directory.into_owned(); self.dirty = true; } } } } fn pane_mut(&mut self, id: PaneId) -> Result<&mut Pane> { self.panes.get_mut(&id).context("unknown pane") } fn new_pane(&mut self, cwd: Option) -> Result { ensure!( self.panes.len() < MAX_PANES, "at most {MAX_PANES} panes are supported" ); let directory = cwd.map(PathBuf::from); if let Some(directory) = &directory { ensure!(directory.is_dir(), "working directory does not exist"); } let initial_directory = directory .as_ref() .and_then(|path| fs::canonicalize(path).ok()) .or_else(|| std::env::current_dir().ok()) .unwrap_or_else(|| PathBuf::from("/")); let (session, events) = if let Some(shell) = &self.shell { Session::with_shell_and_directory(shell.clone(), directory)? } else { Session::in_directory(directory)? }; let id = self.next_id; self.next_id += 1; let cwd = session .working_directory() .unwrap_or(initial_directory) .to_string_lossy() .into_owned(); self.panes.insert( id, Pane { session, program_title: None, manual_title: None, cwd, exited: false, }, ); let sender = self.sender.clone(); thread::Builder::new() .name(format!("psyterm-events-{id}")) .spawn(move || { while let Ok(event) = events.recv_blocking() { if sender.send(Action::Terminal(id, event)).is_err() { break; } } })?; Ok(id) } fn new_tab(&mut self, cwd: Option) -> Result<()> { let pane = self.new_pane(cwd)?; let id = self.next_id; self.next_id += 1; self.tabs.push(TabInfo { id, title: "Shell".into(), manual_title: None, panes: vec![pane], active_pane: pane, stacks: vec![single_pane_stack(pane)], }); self.active_tab = id; Ok(()) } fn terminal_event(&mut self, id: PaneId, event: Event) { if matches!(event, Event::Exit) { self.remove_pane(id); return; } let Some(pane) = self.panes.get_mut(&id) else { return; }; match event { Event::Wakeup => { // Hidden PTYs still parse output and must rearm their wakeups, // but their grids are absent from the current client snapshot. pane.session.acknowledge_wakeup(); self.dirty |= self .tabs .iter() .find(|tab| tab.id == self.active_tab) .is_some_and(|tab| tab.stacks.iter().any(|stack| stack.active_pane == id)); return; } Event::Title(title) => pane.program_title = clean_title(title), Event::ResetTitle => pane.program_title = None, Event::PtyWrite(text) => pane.session.write(text.into_bytes()), Event::TextAreaSizeRequest(format) => { pane.session.write(format(pane.session.size()).into_bytes()) } Event::ColorRequest(index, format) => { let color = if index < COUNT { pane.session.term.lock().colors()[index] } else { None }; pane.session.write( format(color.unwrap_or_else(|| crate::colors::palette(index))).into_bytes(), ); } // ChildExit precedes output draining; remove only on Event::Exit. Event::ChildExit(_) => { pane.exited = true; return; } // Desktop clipboard belongs to the client and OSC 52 remains disabled. _ => {} } self.dirty = true; } fn snapshot(&mut self) -> Snapshot { self.revision += 1; for tab in &mut self.tabs { tab.title = tab .manual_title .clone() .or_else(|| self.panes.get(&tab.active_pane).map(Pane::title)) .unwrap_or_else(|| "Shell".into()); for stack in &mut tab.stacks { for entry in &mut stack.panes { if let Some(pane) = self.panes.get(&entry.id) { entry.title = pane.title(); } } } } let visible = self .tabs .iter() .find(|tab| tab.id == self.active_tab) .map(|tab| { tab.stacks .iter() .map(|stack| stack.active_pane) .collect::>() }) .unwrap_or_default(); let panes = visible .into_iter() .filter_map(|id| { self.panes.get(&id).map(|pane| { let term = pane.session.term.lock(); let content = term.renderable_content(); let size = pane.session.size(); let mut cells = Vec::with_capacity(size.num_cols as usize * size.num_lines as usize); let mut selected = Vec::with_capacity(cells.capacity()); for indexed in content.display_iter { let mut cell = indexed.cell.clone(); // Hyperlinks are not displayed by this client version. Avoid // repeating arbitrary OSC 8 URI payloads in every grid cell. if cell.hyperlink().is_some() { cell.set_hyperlink(None); } cells.push(cell); selected.push( content .selection .is_some_and(|selection| selection.contains(indexed.point)), ); } PaneSnapshot { id, title: pane.title(), manual_title: pane.manual_title.clone(), cwd: pane.cwd.clone(), columns: size.num_cols, lines: size.num_lines, cell_width: size.cell_width, cell_height: size.cell_height, cells, selected, colors: (0..COUNT).map(|index| content.colors[index]).collect(), cursor: Cursor { column: content.cursor.point.column.0 as u16, row: content.cursor.point.line.0 + content.display_offset as i32, shape: content.cursor.shape.into(), }, display_offset: content.display_offset as u32, mode: content.mode.bits(), exited: pane.exited, } }) }) .collect(); Snapshot { revision: self.revision, tabs: self.tabs.clone(), active_tab: self.active_tab, panes, } } fn publish(&mut self) { if !self.clients.values().any(|client| client.attached) { return; } let snapshot = Arc::new(self.snapshot()); for client in self.clients.values().filter(|client| client.attached) { client.output.snapshot(snapshot.clone()); } } } struct SocketGuard { socket: PathBuf, _lock: File, } impl Drop for SocketGuard { fn drop(&mut self) { let _ = fs::remove_file(&self.socket); } } fn bind_socket(socket: &Path) -> Result<(SocketGuard, UnixListener)> { let parent = socket.parent().context("socket has no parent directory")?; if !parent.exists() { fs::create_dir_all(parent)?; fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?; } let lock = OpenOptions::new() .create(true) .truncate(false) .read(true) .write(true) .mode(0o600) .custom_flags(libc::O_NOFOLLOW) .open(socket.with_extension("lock"))?; // SAFETY: flock operates on our live owned file descriptor. ensure!( unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, "another server owns this socket" ); if let Ok(metadata) = fs::symlink_metadata(socket) { // SAFETY: geteuid has no preconditions. ensure!( metadata.file_type().is_socket() && metadata.uid() == unsafe { libc::geteuid() }, "refusing to replace an unowned/non-socket path" ); ensure!( UnixStream::connect(socket).is_err(), "server is already running" ); fs::remove_file(socket)?; } let listener = UnixListener::bind(socket).context("bind terminal server socket")?; fs::set_permissions(socket, fs::Permissions::from_mode(0o600))?; Ok(( SocketGuard { socket: socket.to_owned(), _lock: lock, }, listener, )) } #[cfg(test)] mod tests { use super::*; use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_TEST: AtomicU64 = AtomicU64::new(1); struct TestServer { socket: PathBuf, thread: Option>>, } impl TestServer { fn start() -> Self { let directory = std::env::temp_dir().join(format!( "pt-s-{:x}-{:x}", std::process::id(), NEXT_TEST.fetch_add(1, Ordering::Relaxed) )); fs::create_dir(&directory).unwrap(); fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); let socket = directory.join("server.sock"); let address = socket.clone(); let thread = thread::spawn(move || { run_with_shell( &address, |_| Ok(()), Some(Shell::new("/bin/sh".into(), Vec::new())), ) }); let test = Self { socket, thread: Some(thread), }; let deadline = Instant::now() + Duration::from_secs(5); while UnixStream::connect(&test.socket).is_err() { assert!(Instant::now() < deadline); thread::sleep(Duration::from_millis(2)); } test } fn client(&self) -> UnixStream { let mut stream = UnixStream::connect(&self.socket).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); protocol::write_message(&mut stream, &ClientMessage::Hello { version: VERSION }) .unwrap(); assert!(matches!( protocol::read_message::(&mut stream).unwrap(), ServerMessage::Hello { version: VERSION, .. } )); stream } } impl Drop for TestServer { fn drop(&mut self) { if let Ok(mut stream) = UnixStream::connect(&self.socket) { let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); let _ = protocol::write_message( &mut stream, &ClientMessage::Hello { version: VERSION }, ); let _ = protocol::read_message::(&mut stream); let _ = protocol::write_message(&mut stream, &ClientMessage::Shutdown); let _ = protocol::read_message::(&mut stream); } if let Some(thread) = self.thread.take() { thread.join().unwrap().unwrap(); } let _ = fs::remove_dir_all(self.socket.parent().unwrap()); } } fn snapshot(stream: &mut UnixStream, accept: impl Fn(&Snapshot) -> bool) -> Snapshot { loop { match protocol::read_message(stream).unwrap() { ServerMessage::Snapshot(snapshot) if accept(&snapshot) => return snapshot, ServerMessage::Error(error) => panic!("server error: {error}"), _ => {} } } } fn send(stream: &mut UnixStream, message: ClientMessage) { protocol::write_message(stream, &message).unwrap(); } fn contains(snapshot: &Snapshot, text: &str) -> bool { snapshot.panes.iter().any(|pane| { pane.cells .iter() .map(|cell| cell.c) .collect::() .contains(text) }) } #[test] fn detached_client_keeps_shell_and_grid_and_server_owns_layout() { let server = TestServer::start(); let mut first = server.client(); send(&mut first, ClientMessage::Attach); let initial = snapshot(&mut first, |snapshot| snapshot.panes.len() == 1); let pane = initial.panes[0].id; let tab = initial.active_tab; send( &mut first, ClientMessage::Input { pane, bytes: b"export PSYTERM_TEST_STATE=retained; printf '\\033[2J\\033[HREADY_STATE\\n'\n" .to_vec(), }, ); snapshot(&mut first, |snapshot| contains(snapshot, "READY_STATE")); send(&mut first, ClientMessage::Detach); drop(first); let mut second = server.client(); send(&mut second, ClientMessage::Attach); let reattached = snapshot(&mut second, |snapshot| contains(snapshot, "READY_STATE")); assert_eq!(reattached.active_tab, tab); assert_eq!(reattached.panes[0].id, pane); send( &mut second, ClientMessage::Resize { pane, columns: 100, lines: 30, cell_width: 9, cell_height: 20, }, ); snapshot(&mut second, |snapshot| { snapshot.panes[0].columns == 100 && snapshot.panes[0].lines == 30 }); send( &mut second, ClientMessage::Input { pane, bytes: b"printf '\\033[2J\\033[HSTATE=%s\\n' \"$PSYTERM_TEST_STATE\"; stty size\n" .to_vec(), }, ); snapshot(&mut second, |snapshot| { contains(snapshot, "STATE=retained") && contains(snapshot, "30 100") }); send( &mut second, ClientMessage::Selection { pane, selection: SelectionCommand::Start { column: 0, row: 0, side: SelectionSide::Left, kind: SelectionKind::Simple, }, }, ); send( &mut second, ClientMessage::Selection { pane, selection: SelectionCommand::Update { column: 13, row: 0, side: SelectionSide::Right, }, }, ); send(&mut second, ClientMessage::Copy { pane }); loop { if let ServerMessage::Clipboard(text) = protocol::read_message(&mut second).unwrap() { assert_eq!(text, "STATE=retained"); break; } } send(&mut second, ClientMessage::Split { pane, cwd: None }); let split = snapshot(&mut second, |snapshot| snapshot.panes.len() == 2); assert_eq!(split.tabs[0].panes.len(), 2); assert_ne!(split.tabs[0].active_pane, pane); send(&mut second, ClientMessage::NewTab { cwd: None }); let new_tab = snapshot(&mut second, |snapshot| snapshot.tabs.len() == 2); assert_ne!(new_tab.active_tab, tab); assert_eq!(new_tab.panes.len(), 1); send(&mut second, ClientMessage::FocusTab { tab }); let focused = snapshot(&mut second, |snapshot| snapshot.active_tab == tab); assert_eq!(focused.panes.len(), 2); assert!(contains(&focused, "STATE=retained")); } #[test] fn handshake_and_size_validation_and_control_clients_do_not_attach() { let server = TestServer::start(); let mut client = server.client(); send(&mut client, ClientMessage::Ping); assert!(matches!( protocol::read_message::(&mut client).unwrap(), ServerMessage::Pong )); send(&mut client, ClientMessage::OpenWindow { target: None }); assert!(matches!( protocol::read_message::(&mut client).unwrap(), ServerMessage::Pong )); send(&mut client, ClientMessage::List); let empty = snapshot(&mut client, |_| true); assert!(empty.tabs.is_empty()); assert!(empty.panes.is_empty()); send(&mut client, ClientMessage::Attach); let state = snapshot(&mut client, |snapshot| !snapshot.panes.is_empty()); send( &mut client, ClientMessage::Resize { pane: state.panes[0].id, columns: 0, lines: 0, cell_width: 0, cell_height: 0, }, ); loop { if matches!( protocol::read_message::(&mut client).unwrap(), ServerMessage::Error(_) ) { break; } } let mode = fs::metadata(&server.socket).unwrap().permissions().mode(); assert_eq!(mode & 0o777, 0o600); } fn input(stream: &mut UnixStream, pane: PaneId, command: &str) { send( stream, ClientMessage::Input { pane, bytes: command.as_bytes().to_vec(), }, ); } fn active_tab(snapshot: &Snapshot) -> &TabInfo { snapshot .tabs .iter() .find(|tab| tab.id == snapshot.active_tab) .unwrap() } fn list_after_commands(client: &mut UnixStream) -> Snapshot { // A round trip separates older queued snapshots from this inspection. send(client, ClientMessage::Ping); loop { match protocol::read_message::(client).unwrap() { ServerMessage::Pong => break, ServerMessage::Error(error) => panic!("server error: {error}"), _ => {} } } send(client, ClientMessage::List); snapshot(client, |_| true) } #[test] fn collapsed_output_rearms_wakeups_without_publishing_unchanged_grids() { let (sender, receiver) = mpsc::sync_channel(1024); let mut actor = Server { shell: Some(Shell::new("/bin/sh".into(), Vec::new())), panes: HashMap::new(), tabs: Vec::new(), active_tab: 0, next_id: 1, clients: HashMap::new(), sender, revision: 0, dirty: false, last_frame: Instant::now(), last_cwd_refresh: Instant::now(), }; actor.new_tab(None).unwrap(); let hidden = actor.tabs[0].active_pane; let visible = actor.new_pane(None).unwrap(); let tab = &mut actor.tabs[0]; tab.stacks[0].panes.push(StackPaneInfo { id: visible, title: "Visible".into(), }); tab.stacks[0].active_pane = visible; tab.active_pane = visible; flatten_panes(tab); // Drive actual PTY/parser events directly so absence of a publish is // tested through its dirty flag, without timing-dependent socket gaps. let output = |actor: &mut Server, suffix: &str, expect_dirty: bool| { actor.panes[&hidden] .session .write(format!("printf 'HIDDEN_%s\\n' '{suffix}'\n").into_bytes()); let needle = format!("HIDDEN_{suffix}"); let deadline = Instant::now() + Duration::from_secs(5); loop { let event = receiver .recv_timeout(deadline.saturating_duration_since(Instant::now())) .unwrap(); if let Action::Terminal(id, event) = event { let target_wakeup = id == hidden && matches!(event, Event::Wakeup); actor.dirty = false; actor.terminal_event(id, event); if target_wakeup { assert_eq!(actor.dirty, expect_dirty); let term = actor.panes[&hidden].session.term.lock(); let text = term .renderable_content() .display_iter .map(|cell| cell.cell.c) .collect::(); if text.contains(&needle) { break; } } } } }; output(&mut actor, "FIRST", false); // A second burst verifies the first suppressed wakeup was acknowledged. output(&mut actor, "SECOND", false); let hidden_snapshot = actor.snapshot(); assert_eq!(hidden_snapshot.panes.len(), 1); assert_eq!(hidden_snapshot.panes[0].id, visible); actor.focus_pane(hidden).unwrap(); assert!(actor.dirty); assert!(contains(&actor.snapshot(), "HIDDEN_SECOND")); output(&mut actor, "VISIBLE", true); } #[test] fn stacks_insert_in_both_directions_and_only_expand_one_grid() { let server = TestServer::start(); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let first = initial.panes[0].id; input( &mut client, first, "stty -echo; printf '\\033[2J\\033[HSTACK_STATE\\n'\n", ); snapshot(&mut client, |s| contains(s, "STACK_STATE")); send( &mut client, ClientMessage::NewStackPane { pane: Some(first), direction: VerticalDirection::Down, cwd: None, }, ); let second = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); let bottom = active_tab(&second).active_pane; assert_eq!(active_tab(&second).panes, [first, bottom]); assert_eq!(active_tab(&second).stacks.len(), 1); assert_eq!(second.panes.len(), 1); assert_eq!(second.panes[0].id, bottom); send( &mut client, ClientMessage::RenamePane { pane: first, name: Some("Collapsed source".into()), }, ); snapshot(&mut client, |s| { active_tab(s).stacks[0].panes[0].title == "Collapsed source" }); send( &mut client, ClientMessage::NewStackPane { pane: Some(bottom), direction: VerticalDirection::Up, cwd: None, }, ); let third = snapshot(&mut client, |s| active_tab(s).panes.len() == 3); let middle = active_tab(&third).active_pane; assert_eq!(active_tab(&third).panes, [first, middle, bottom]); assert_eq!(third.panes.len(), 1); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Up, }, ); let top = snapshot(&mut client, |s| active_tab(s).active_pane == first); assert!(contains(&top, "STACK_STATE")); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Up, }, ); assert_eq!( active_tab(&list_after_commands(&mut client)).active_pane, first ); send( &mut client, ClientMessage::FocusStackPane { pane: first, direction: VerticalDirection::Down, }, ); snapshot(&mut client, |s| active_tab(s).active_pane == middle); send(&mut client, ClientMessage::FocusPane { pane: bottom }); snapshot(&mut client, |s| active_tab(s).active_pane == bottom); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Down, }, ); assert_eq!( active_tab(&list_after_commands(&mut client)).active_pane, bottom ); } #[test] fn relative_commands_preserve_bursts_without_intermediate_snapshots() { let server = TestServer::start(); // A control client does not attach, so the only snapshots are the // explicit List responses after each complete command burst. let mut client = server.client(); let inspect = |client: &mut UnixStream| { send(client, ClientMessage::List); snapshot(client, |_| true) }; for _ in 0..3 { send(&mut client, ClientMessage::NewTab { cwd: None }); } let initial = inspect(&mut client); let first_tab = initial.tabs[0].id; let last_tab = initial.tabs[2].id; let first_pane = initial.tabs[0].active_pane; send(&mut client, ClientMessage::FocusTab { tab: first_tab }); send(&mut client, ClientMessage::CycleTab { forward: true }); send(&mut client, ClientMessage::CycleTab { forward: true }); assert_eq!(inspect(&mut client).active_tab, last_tab); send(&mut client, ClientMessage::CycleTab { forward: false }); send(&mut client, ClientMessage::CycleTab { forward: false }); assert_eq!(inspect(&mut client).active_tab, first_tab); send(&mut client, ClientMessage::CycleTab { forward: false }); assert_eq!(inspect(&mut client).active_tab, last_tab); send(&mut client, ClientMessage::FocusTab { tab: first_tab }); for _ in 0..2 { send( &mut client, ClientMessage::NewStackPane { pane: None, direction: VerticalDirection::Down, cwd: None, }, ); } let down = inspect(&mut client); let order = &active_tab(&down).panes; assert_eq!(order.len(), 3); assert_eq!(order[0], first_pane); // Pane IDs grow with creation order: repeated Down appends in that // order, rather than repeatedly inserting after the stale first pane. assert!(order[1] < order[2]); let last_down = order[2]; assert_eq!(active_tab(&down).active_pane, last_down); for _ in 0..2 { send( &mut client, ClientMessage::NewStackPane { pane: None, direction: VerticalDirection::Up, cwd: None, }, ); } let up = inspect(&mut client); let order = &active_tab(&up).panes; assert_eq!(order.len(), 5); assert_eq!(order[4], last_down); assert!(order[2] > order[3]); let expanded = order[2]; assert_eq!(active_tab(&up).active_pane, expanded); send( &mut client, ClientMessage::Split { pane: expanded, cwd: None, }, ); let middle = active_tab(&inspect(&mut client)).active_pane; send( &mut client, ClientMessage::Split { pane: middle, cwd: None, }, ); let right = active_tab(&inspect(&mut client)).active_pane; send(&mut client, ClientMessage::FocusPane { pane: expanded }); send(&mut client, ClientMessage::CyclePane { forward: true }); send(&mut client, ClientMessage::CyclePane { forward: true }); assert_eq!(active_tab(&inspect(&mut client)).active_pane, right); send(&mut client, ClientMessage::CyclePane { forward: true }); assert_eq!(active_tab(&inspect(&mut client)).active_pane, expanded); send(&mut client, ClientMessage::CyclePane { forward: false }); send(&mut client, ClientMessage::CyclePane { forward: false }); assert_eq!(active_tab(&inspect(&mut client)).active_pane, middle); } #[test] fn horizontal_navigation_moves_between_columns_and_then_tabs() { let server = TestServer::start(); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let first = initial.panes[0].id; let first_tab = initial.active_tab; send( &mut client, ClientMessage::NewStackPane { pane: Some(first), direction: VerticalDirection::Down, cwd: None, }, ); let stacked = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); let expanded = active_tab(&stacked).active_pane; send( &mut client, ClientMessage::Split { pane: first, cwd: None, }, ); let split = snapshot(&mut client, |s| s.panes.len() == 2); let right = active_tab(&split).active_pane; assert_eq!(active_tab(&split).panes, [first, expanded, right]); assert_eq!(active_tab(&split).stacks.len(), 2); assert_eq!( split.panes.iter().map(|pane| pane.id).collect::>(), [expanded, right] ); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Left, }, ); snapshot(&mut client, |s| active_tab(s).active_pane == expanded); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Up, }, ); snapshot(&mut client, |s| active_tab(s).active_pane == first); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Right, }, ); snapshot(&mut client, |s| active_tab(s).active_pane == right); send(&mut client, ClientMessage::NewTab { cwd: None }); let next_tab = snapshot(&mut client, |s| s.tabs.len() == 2); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Left, }, ); let restored = snapshot(&mut client, |s| s.active_tab == first_tab); assert_eq!(active_tab(&restored).active_pane, right); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Right, }, ); snapshot(&mut client, |s| s.active_tab == next_tab.active_tab); send( &mut client, ClientMessage::FocusDirection { direction: Direction::Right, }, ); snapshot(&mut client, |s| s.active_tab == first_tab); } #[test] fn stack_state_and_collapsed_shells_survive_clients_and_exit_cleanly() { let server = TestServer::start(); let mut first_client = server.client(); send(&mut first_client, ClientMessage::Attach); let initial = snapshot(&mut first_client, |s| s.panes.len() == 1); let top = initial.panes[0].id; send( &mut first_client, ClientMessage::NewStackPane { pane: Some(top), direction: VerticalDirection::Down, cwd: None, }, ); let stacked = snapshot(&mut first_client, |s| active_tab(s).panes.len() == 2); let middle = active_tab(&stacked).active_pane; send( &mut first_client, ClientMessage::NewStackPane { pane: Some(middle), direction: VerticalDirection::Down, cwd: None, }, ); let three = snapshot(&mut first_client, |s| active_tab(s).panes.len() == 3); let bottom = active_tab(&three).active_pane; let mut other_client = server.client(); send(&mut other_client, ClientMessage::Attach); let mirrored = snapshot(&mut other_client, |s| active_tab(s).panes.len() == 3); assert_eq!(active_tab(&mirrored).panes, [top, middle, bottom]); send(&mut other_client, ClientMessage::FocusPane { pane: middle }); snapshot(&mut other_client, |s| active_tab(s).active_pane == middle); snapshot(&mut first_client, |s| active_tab(s).active_pane == middle); send(&mut first_client, ClientMessage::Detach); send(&mut other_client, ClientMessage::Detach); drop(first_client); drop(other_client); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let reattached = snapshot(&mut client, |s| active_tab(s).panes.len() == 3); assert_eq!(reattached.active_tab, initial.active_tab); assert_eq!(active_tab(&reattached).stacks[0].active_pane, middle); assert_eq!(reattached.panes[0].id, middle); // A collapsed shell's exit leaves the focused/expanded pane alone. input(&mut client, top, "exit\n"); let collapsed_exit = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); assert_eq!(active_tab(&collapsed_exit).panes, [middle, bottom]); assert_eq!(collapsed_exit.panes[0].id, middle); // Explicit close uses the same adjacent fallback as natural exit. send(&mut client, ClientMessage::ClosePane { pane: middle }); let closed = snapshot(&mut client, |s| active_tab(s).panes.len() == 1); assert_eq!(closed.panes[0].id, bottom); send( &mut client, ClientMessage::Split { pane: bottom, cwd: None, }, ); let split = snapshot(&mut client, |s| s.panes.len() == 2); let other = active_tab(&split).active_pane; input(&mut client, bottom, "exit\n"); let removed_column = snapshot(&mut client, |s| active_tab(s).stacks.len() == 1); assert_eq!(removed_column.panes[0].id, other); input(&mut client, other, "exit\n"); let empty = snapshot(&mut client, |s| s.tabs.is_empty()); assert!(empty.panes.is_empty()); } #[test] fn natural_shell_exit_removes_panes_and_empty_tabs_without_stealing_focus() { let server = TestServer::start(); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let original = initial.panes[0].id; let original_tab = initial.active_tab; send( &mut client, ClientMessage::Split { pane: original, cwd: None, }, ); let split = snapshot(&mut client, |s| s.panes.len() == 2); let second = split.tabs[0].active_pane; assert_ne!(second, original); input(&mut client, second, "exit\n"); let single = snapshot(&mut client, |s| { s.panes.len() == 1 && s.tabs[0].active_pane == original }); assert_eq!(single.active_tab, original_tab); assert_eq!(single.panes[0].id, original); send(&mut client, ClientMessage::NewTab { cwd: None }); let other = snapshot(&mut client, |s| s.tabs.len() == 2); let other_tab = other.active_tab; let other_pane = other.panes[0].id; input(&mut client, original, "exit\n"); let preserved = snapshot(&mut client, |s| s.tabs.len() == 1); assert_eq!(preserved.active_tab, other_tab); assert_eq!(preserved.panes[0].id, other_pane); input(&mut client, other_pane, "exit\n"); let empty = snapshot(&mut client, |s| s.tabs.is_empty()); assert!(empty.panes.is_empty()); assert_eq!(empty.active_tab, 0); // Removing the final shell leaves this GUI attached to a live server. send(&mut client, ClientMessage::Ping); loop { if matches!( protocol::read_message::(&mut client).unwrap(), ServerMessage::Pong ) { break; } } send(&mut client, ClientMessage::NewTab { cwd: None }); let reopened = snapshot(&mut client, |s| s.panes.len() == 1); assert_ne!(reopened.panes[0].id, original); } #[test] fn exiting_active_tab_selects_the_adjacent_surviving_tab() { let server = TestServer::start(); let mut client = server.client(); send(&mut client, ClientMessage::Attach); snapshot(&mut client, |s| s.tabs.len() == 1); send(&mut client, ClientMessage::NewTab { cwd: None }); let middle = snapshot(&mut client, |s| s.tabs.len() == 2); let middle_tab = middle.active_tab; let middle_pane = middle.panes[0].id; send(&mut client, ClientMessage::NewTab { cwd: None }); let last = snapshot(&mut client, |s| s.tabs.len() == 3); send(&mut client, ClientMessage::FocusTab { tab: middle_tab }); snapshot(&mut client, |s| s.active_tab == middle_tab); input(&mut client, middle_pane, "exit\n"); let remaining = snapshot(&mut client, |s| s.tabs.len() == 2); assert_eq!(remaining.active_tab, last.active_tab); assert!(!remaining.tabs.iter().any(|tab| tab.id == middle_tab)); } #[test] fn cwd_program_and_manual_names_follow_precedence_and_survive_detach() { let server = TestServer::start(); // The OS reports the physical cwd; macOS TMPDIR typically starts with the /var symlink. let parent = fs::canonicalize(server.socket.parent().unwrap()).unwrap(); let first_dir = parent.join("first"); let second_dir = parent.join("second"); fs::create_dir(&first_dir).unwrap(); fs::create_dir(&second_dir).unwrap(); let mut client = server.client(); send( &mut client, ClientMessage::NewTab { cwd: Some(first_dir.to_string_lossy().into_owned()), }, ); send(&mut client, ClientMessage::Attach); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let pane = initial.panes[0].id; assert_eq!(initial.panes[0].title, first_dir.to_string_lossy()); assert_eq!(initial.panes[0].cwd, first_dir.to_string_lossy()); assert!(initial.panes[0].manual_title.is_none()); // Disable echo and prompts: a subsequent idle `cd` produces no PTY // output, so the server's directory watcher must publish this update. input( &mut client, pane, "stty -echo; PS1=; printf '\\033[22;0t\\033]2;Codex\\007'\n", ); let titled = snapshot(&mut client, |s| s.panes[0].title == "Codex"); assert_eq!(titled.tabs[0].title, "Codex"); send( &mut client, ClientMessage::RenamePane { pane, name: Some("My work".into()), }, ); snapshot(&mut client, |s| s.panes[0].title == "My work"); input(&mut client, pane, "printf '\\033]2;Compiler\\007'\n"); // A fresh client receives the override rather than reconstructing it. send(&mut client, ClientMessage::Detach); drop(client); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let reattached = snapshot(&mut client, |s| !s.panes.is_empty()); assert_eq!(reattached.panes[0].manual_title.as_deref(), Some("My work")); assert_eq!(reattached.panes[0].title, "My work"); send(&mut client, ClientMessage::RenamePane { pane, name: None }); snapshot(&mut client, |s| s.panes[0].title == "Compiler"); input(&mut client, pane, "printf '\\033]2;\\007'\n"); snapshot(&mut client, |s| { s.panes[0].title == first_dir.to_string_lossy() }); input(&mut client, pane, "printf '\\033]2;Temporary\\007'\n"); snapshot(&mut client, |s| s.panes[0].title == "Temporary"); // Restoring the initially absent title exercises Event::ResetTitle, // distinct from an empty OSC title above. input(&mut client, pane, "printf '\\033[23;0t'\n"); snapshot(&mut client, |s| { s.panes[0].title == first_dir.to_string_lossy() }); input( &mut client, pane, &format!("cd '{}'\n", second_dir.display()), ); let moved = snapshot(&mut client, |s| { s.panes[0].cwd == second_dir.to_string_lossy() }); assert_eq!(moved.panes[0].title, second_dir.to_string_lossy()); send( &mut client, ClientMessage::RenamePane { pane, name: Some("Pinned".into()), }, ); snapshot(&mut client, |s| s.panes[0].title == "Pinned"); send( &mut client, ClientMessage::RenamePane { pane, name: Some(" \n\t".into()), }, ); let automatic = snapshot(&mut client, |s| { s.panes[0].title == second_dir.to_string_lossy() }); assert!(automatic.panes[0].manual_title.is_none()); } #[test] fn manual_tab_names_override_selected_panes_and_survive_clients_and_exit() { let server = TestServer::start(); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let tab = initial.active_tab; let first = initial.panes[0].id; assert!(active_tab(&initial).manual_title.is_none()); assert_eq!(active_tab(&initial).title, initial.panes[0].title); input(&mut client, first, "printf '\\033]2;Codex\\007'\n"); snapshot(&mut client, |s| active_tab(s).title == "Codex"); send( &mut client, ClientMessage::NewStackPane { pane: None, direction: VerticalDirection::Down, cwd: None, }, ); let stacked = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); let second = active_tab(&stacked).active_pane; send( &mut client, ClientMessage::RenamePane { pane: second, name: Some("Build".into()), }, ); snapshot(&mut client, |s| active_tab(s).title == "Build"); send( &mut client, ClientMessage::RenameTab { tab, name: Some(" Pro\nject\t\u{7} ".into()), }, ); let named = snapshot(&mut client, |s| active_tab(s).title == "Project"); assert_eq!(active_tab(&named).manual_title.as_deref(), Some("Project")); assert_eq!(named.panes[0].title, "Build"); send(&mut client, ClientMessage::FocusPane { pane: first }); input(&mut client, first, "printf '\\033]2;Editor\\007'\n"); let changed = snapshot(&mut client, |s| s.panes[0].title == "Editor"); assert_eq!(active_tab(&changed).title, "Project"); send(&mut client, ClientMessage::FocusPane { pane: second }); input(&mut client, second, "exit\n"); let exited = snapshot(&mut client, |s| active_tab(s).panes.len() == 1); assert_eq!(active_tab(&exited).active_pane, first); assert_eq!(active_tab(&exited).title, "Project"); send(&mut client, ClientMessage::NewTab { cwd: None }); let another = snapshot(&mut client, |s| s.tabs.len() == 2); let other_tab = another.active_tab; assert!(active_tab(&another).manual_title.is_none()); assert_eq!(active_tab(&another).title, another.panes[0].title); // An independent client can rename an inactive tab without stealing // focus. All attached views receive the server's name immediately. let mut other = server.client(); send( &mut other, ClientMessage::RenameTab { tab, name: Some("Server name".into()), }, ); let renamed = snapshot(&mut client, |s| { s.tabs .iter() .any(|entry| entry.id == tab && entry.title == "Server name") }); assert_eq!(renamed.active_tab, other_tab); send(&mut client, ClientMessage::Detach); drop(client); let mut client = server.client(); send(&mut client, ClientMessage::Attach); let reattached = snapshot(&mut client, |s| s.tabs.len() == 2); let saved = reattached .tabs .iter() .find(|entry| entry.id == tab) .unwrap(); assert_eq!(saved.title, "Server name"); assert_eq!(saved.manual_title.as_deref(), Some("Server name")); send(&mut client, ClientMessage::FocusTab { tab }); send( &mut client, ClientMessage::RenameTab { tab, name: Some(" \n\t ".into()), }, ); let automatic = snapshot(&mut client, |s| active_tab(s).title == "Editor"); assert!(active_tab(&automatic).manual_title.is_none()); input(&mut client, first, "printf '\\033]2;Changed\\007'\n"); snapshot(&mut client, |s| active_tab(s).title == "Changed"); send( &mut client, ClientMessage::RenamePane { pane: first, name: Some("Pane override".into()), }, ); snapshot(&mut client, |s| active_tab(s).title == "Pane override"); send( &mut client, ClientMessage::RenameTab { tab, name: Some("Pinned again".into()), }, ); snapshot(&mut client, |s| active_tab(s).title == "Pinned again"); send(&mut client, ClientMessage::RenameTab { tab, name: None }); let automatic = snapshot(&mut client, |s| active_tab(s).title == "Pane override"); assert!(active_tab(&automatic).manual_title.is_none()); } #[test] fn displayed_titles_are_bounded_single_line_text() { assert_eq!( clean_title(" Codex\n\r\t\u{7} ".into()).as_deref(), Some("Codex") ); assert_eq!(clean_title(" \n\u{7} ".into()), None); assert_eq!(clean_title("界".repeat(600)).unwrap().chars().count(), 512); } #[test] fn directory_names_abbreviate_only_the_server_home_directory() { let home = Some(Path::new("/home/al")); assert_eq!(directory_title("/home/al", home), "~"); assert_eq!(directory_title("/home/al/src/界", home), "~/src/界"); assert_eq!(directory_title("/home/alice/src", home), "/home/alice/src"); assert_eq!(directory_title("/home/al/src", None), "/home/al/src"); assert_eq!( directory_title("/home/al/src", Some(Path::new("/home/al/"))), "~/src" ); assert_eq!(directory_title("/", Some(Path::new("/"))), "~"); assert_eq!(directory_title("/src", Some(Path::new("/"))), "~/src"); assert_eq!( directory_title("/home/al/src", Some(Path::new(""))), "/home/al/src" ); } #[test] fn slow_client_retains_only_latest_snapshot() { let output = Outbox::default(); for revision in 1..=1000 { output.snapshot(Arc::new(Snapshot { revision, tabs: Vec::new(), active_tab: 0, panes: Vec::new(), })); } output.reliable(ServerMessage::Pong); assert!(matches!(output.next(), Some(ServerMessage::Pong))); assert!(matches!( output.next(), Some(ServerMessage::Snapshot(Snapshot { revision: 1000, .. })) )); output.close(); assert!(output.next().is_none()); } }