A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
perf(mux): replace pane output sockets with a bounded buffer
RoversX08765235ad77
diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex a2650f50..153ce8f4 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -7,9 +7,8 @@ use anyhow::{anyhow, Context, Error};use config::keyassignment::SpawnTabDomain;use config::{configuration, ExitBehavior, GuiPosition};use domain::{Domain, DomainId, DomainState, SplitSource};-use filedescriptor::{poll, pollfd, socketpair, AsRawSocketDescriptor, FileDescriptor, POLLIN};#[cfg(unix)]-use libc::{c_int, SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};+use filedescriptor::{poll, pollfd, AsRawSocketDescriptor, FileDescriptor, POLLIN};use log::error;use metrics::histogram;use parking_lot::{@@ -20,8 +19,6 @@ use portable_pty::{CommandBuilder, ExitStatus, PtySize};use std::collections::{HashMap, HashSet};use std::convert::TryInto;use std::io::{Read, Write};-#[cfg(windows)]-use std::os::raw::c_int;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Weak};use std::thread;@@ -34,8 +31,6 @@ use wezterm_term::color::ColorPalette;use wezterm_term::{Clipboard, ClipboardSelection, DownloadHandler, TerminalConfiguration, TerminalSize,};-#[cfg(windows)]-use winapi::um::winsock2::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};pub mod activity;pub mod agent_status;@@ -49,6 +44,7 @@ pub mod foreground_program;pub mod geometrytrace;pub mod kept_output;pub mod localpane;+mod output_buffer;pub mod pane;mod parse_watchdog;pub mod renderable;@@ -675,12 +671,10 @@ impl Drop for TabGeometryTransaction<'_> {}}-const BUFSIZE: usize = 1024 * 1024;-/// Size of the per-pane pty read buffer. This lives for the lifetime of the/// pane's reader thread, so it is sized for what a single read() can actually/// return (the kernel tty buffer is far smaller than this) rather than-/// BUFSIZE, which would pin 1MB per pane.+/// a large parser batch, which would pin excess memory per pane.const PTY_READ_BUFSIZE: usize = 64 * 1024;/// Bytes of external kitty payloads one flush may read into memory. A@@ -809,25 +803,16 @@ fn release_action_buffer(actions: &Vec<Action>, read_capacity: usize, more_to_reactions.capacity() > 0 && (!more_to_read || actions.capacity() > read_capacity)}-/// Whether `fd` has data to read right now, without waiting for any.-fn readable_now(fd: &FileDescriptor) -> bool {- let mut pfd = [pollfd {- fd: fd.as_socket_descriptor(),- events: POLLIN,- revents: 0,- }];- matches!(poll(&mut pfd, Some(Duration::ZERO)), Ok(1))-}-fn parse_buffered_data(pane: Weak<dyn Pane>,pane_id: PaneId,dead: &Arc<AtomicBool>,- mut rx: FileDescriptor,+ mut rx: output_buffer::OutputReceiver,heartbeat: Arc<parse_watchdog::ParseHeartbeat>,control: Option<Arc<ReaderControl>>,) {- let mut buf = vec![0; configuration().mux_output_parser_buffer_size];+ let mut read_capacity = configuration().mux_output_parser_buffer_size;+ let mut buf = Vec::new();// Bytes read and not yet turned into applied actions; settled against// the reader's count whenever nothing is left waiting to be sent.let mut unapplied = 0usize;@@ -841,12 +826,12 @@ fn parse_buffered_data(loop {if actions.is_empty() && actions.capacity() > 0 {- let more_to_read = readable_now(&rx);- if release_action_buffer(&actions, buf.len(), more_to_read) {+ let more_to_read = rx.readable_now();+ if release_action_buffer(&actions, read_capacity, more_to_read) {actions = Vec::new();}}- match rx.read(&mut buf) {+ match rx.read_buffered(&mut buf, read_capacity) {Ok(size) if size == 0 => {dead.store(true, Ordering::Relaxed);break;@@ -901,7 +886,7 @@ fn parse_buffered_data(action_size = 0;}});- // The poll() wait below is idle time, so busy work is+ // The receive wait below is idle time, so busy work is// recorded here (the parse, including any mid-parse flushes// into the terminal) and separately around the flush below.heartbeat.add(work_started.elapsed(), size);@@ -911,7 +896,7 @@ fn parse_buffered_data(// pause for a short while to increase the chances// that we coalesce a full "frame" from an unoptimized// TUI program- if action_size < buf.len() {+ if action_size < read_capacity {let poll_delay = match deadline {None => {deadline.replace(Instant::now() + delay);@@ -919,13 +904,8 @@ fn parse_buffered_data(}Some(target) => target.checked_duration_since(Instant::now()),};- if poll_delay.is_some() {- let mut pfd = [pollfd {- fd: rx.as_socket_descriptor(),- events: POLLIN,- revents: 0,- }];- if let Ok(1) = poll(&mut pfd, poll_delay) {+ if let Some(poll_delay) = poll_delay {+ if rx.wait_readable(poll_delay) {// We can read now without blocking, so accumulate// more data into actionscontinue;@@ -945,7 +925,7 @@ fn parse_buffered_data(}let config = configuration();- buf.resize(config.mux_output_parser_buffer_size, 0);+ read_capacity = config.mux_output_parser_buffer_size;delay = Duration::from_millis(config.mux_output_parser_coalesce_delay_ms);if actions.is_empty() {@@ -976,36 +956,6 @@ fn parse_buffered_data(parse_watchdog::unregister(pane_id);}-fn set_socket_buffer(fd: &mut FileDescriptor, option: i32, size: usize) -> anyhow::Result<()> {- let size = size as c_int;- let socklen = std::mem::size_of_val(&size);- unsafe {- let res = libc::setsockopt(- fd.as_socket_descriptor(),- SOL_SOCKET,- option,- &size as *const c_int as *const _,- socklen as _,- );- if res == 0 {- Ok(())- } else {- Err(std::io::Error::last_os_error()).context("setsockopt")- }- }-}--fn allocate_socketpair() -> anyhow::Result<(FileDescriptor, FileDescriptor)> {- let (mut tx, mut rx) = socketpair().context("socketpair")?;- set_socket_buffer(&mut tx, SO_SNDBUF, BUFSIZE)- .context("SO_SNDBUF")- .ok();- set_socket_buffer(&mut rx, SO_RCVBUF, BUFSIZE)- .context("SO_RCVBUF")- .ok();- Ok((tx, rx))-}-/// A pane's reader thread, from the outside. A takeover hands the pty to/// another process, and while it does nothing here may read it; the/// control lets the reader be parked and says when everything it read@@ -1202,8 +1152,8 @@ pub fn pause_pane_reader(pane_id: PaneId, timeout: Duration) -> anyhow::Result<P/// This function is run in a separate thread; its purpose is to perform/// blocking reads from the pty (non-blocking reads are not portable to-/// all platforms) and to feed the bytes to the parser thread over a-/// socketpair. With a pty file descriptor to poll, the reader can also be+/// all platforms) and to feed the bytes to the parser thread through a+/// bounded byte buffer. With a pty file descriptor to poll, the reader can also be/// parked; see [`pause_pane_reader`].fn read_from_pane_pty(pane: Weak<dyn Pane>,@@ -1220,20 +1170,7 @@ fn read_from_pane_pty(None => return,};- let (mut tx, rx) = match allocate_socketpair() {- Ok(pair) => pair,- Err(err) => {- log::error!("read_from_pane_pty: Unable to allocate a socketpair: {err:#}");- localpane::emit_output_for_pane(- pane_id,- &format!(- "⚠️ ThinkTerm: read_from_pane_pty: \- Unable to allocate a socketpair: {err:#}"- ),- );- return;- }- };+ let (mut tx, rx) = output_buffer::channel();// The wake pipe and the control exist only when the pty can be polled;// without them the loop below is the plain blocking read.diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex 414ec20c..cd4961cf 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -3328,4 +3328,71 @@ mod summary_tests {std::thread::sleep(Duration::from_millis(150));assert_eq!(title(&pane), "second", "a kept pause never resumes");}++ #[cfg(unix)]+ #[test]+ fn synchronized_output_survives_reader_pause_and_eof() {+ use std::os::unix::io::AsRawFd;+ use std::sync::atomic::Ordering;+ ensure_scheduler();+ let pipe = filedescriptor::Pipe::new().unwrap();+ let mut program = pipe.write;+ let raw = pipe.read.as_raw_fd();+ let (_exit_tx, exit_rx) = std::sync::mpsc::channel();+ let terminal = Terminal::new(+ size(80, 24),+ Arc::new(config::TermConfig::new()),+ "ThinkTerm",+ "test",+ Box::new(Vec::new()),+ );+ let pane: Arc<dyn Pane> = Arc::new(LocalPane::new(+ 4243,+ terminal,+ Box::new(SleepingChild(exit_rx)),+ Box::new(PipePty { read: pipe.read }),+ Box::new(Vec::new()),+ 0,+ "test".into(),+ ));+ let reader = pane.reader().unwrap().unwrap();+ let weak = Arc::downgrade(&pane);+ let reader_thread =+ std::thread::spawn(move || crate::read_from_pane_pty(weak, None, reader, Some(raw)));+ let title = |pane: &Arc<dyn Pane>| pane.summary_without_waiting().title;+ let wait_for = |want: &str| {+ let deadline = Instant::now() + Duration::from_secs(5);+ while title(&pane) != want && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(5));+ }+ assert_eq!(title(&pane), want);+ };++ program.write_all(b"\x1b]0;initial\x07").unwrap();+ wait_for("initial");+ program.write_all(b"\x1b[?2026h").unwrap();+ program.write_all(&vec![b'x'; 256 * 1024 + 17]).unwrap();+ program.write_all(b"\x1b]0;held\x07").unwrap();+ let control = crate::PANE_READERS.lock().get(&4243).cloned().unwrap();+ let deadline = Instant::now() + Duration::from_secs(5);+ while !control.holding.load(Ordering::SeqCst) && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(5));+ }+ assert!(control.holding.load(Ordering::SeqCst));+ let paused = crate::pause_pane_reader(4243, Duration::from_secs(2)).unwrap();+ assert_eq!(title(&pane), "initial");+ program.write_all(b"\x1b[?2026l").unwrap();+ drop(paused);+ wait_for("held");++ program.write_all(b"\x1b[?2026h\x1b]0;final\x07").unwrap();+ drop(program);+ wait_for("final");+ reader_thread.join().unwrap();+ let deadline = Instant::now() + Duration::from_secs(5);+ while control.pending_bytes() != 0 && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(5));+ }+ assert_eq!(control.pending_bytes(), 0);+ }}diff --git a/mux/src/output_buffer.rs b/mux/src/output_buffer.rsnew file mode 100644index 00000000..42f55677--- /dev/null+++ b/mux/src/output_buffer.rs@@ -0,0 +1,478 @@+use parking_lot::{Condvar, Mutex, MutexGuard};+use std::collections::VecDeque;+use std::io::{self, Read, Write};+use std::sync::Arc;+use std::time::{Duration, Instant};++const MAX_CAPACITY: usize = 1024 * 1024;+const IDLE_RELEASE: Duration = Duration::from_millis(100);+/// One PTY read. A parser that keeps the queue this short is keeping up.+const KEPT_CAPACITY: usize = 64 * 1024;++struct State {+ bytes: VecDeque<u8>,+ /// When the parser last found more queued than `KEPT_CAPACITY`.+ last_backlog: Instant,+ writer_open: bool,+ reader_open: bool,+}++impl State {+ /// Storage left by a burst the parser finished a while ago. Output that+ /// never stops for `IDLE_RELEASE` would otherwise hold it indefinitely.+ fn outlived_burst(&mut self) -> bool {+ if self.bytes.len() > KEPT_CAPACITY {+ self.last_backlog = Instant::now();+ return false;+ }+ self.bytes.capacity() > KEPT_CAPACITY && self.last_backlog.elapsed() >= IDLE_RELEASE+ }+}++struct Shared {+ state: Mutex<State>,+ readable: Condvar,+ writable: Condvar,+ capacity: usize,+}++pub(crate) struct OutputSender(Arc<Shared>);+pub(crate) struct OutputReceiver(Arc<Shared>);++pub(crate) fn channel() -> (OutputSender, OutputReceiver) {+ channel_with_capacity(MAX_CAPACITY)+}++fn channel_with_capacity(capacity: usize) -> (OutputSender, OutputReceiver) {+ let shared = Arc::new(Shared {+ state: Mutex::new(State {+ bytes: VecDeque::new(),+ last_backlog: Instant::now(),+ writer_open: true,+ reader_open: true,+ }),+ readable: Condvar::new(),+ writable: Condvar::new(),+ capacity: capacity.clamp(1, MAX_CAPACITY),+ });+ (OutputSender(Arc::clone(&shared)), OutputReceiver(shared))+}++impl Write for OutputSender {+ fn write(&mut self, data: &[u8]) -> io::Result<usize> {+ if data.is_empty() {+ return Ok(0);+ }+ let shared = &self.0;+ let mut state = shared.state.lock();+ while state.bytes.len() == shared.capacity && state.reader_open {+ shared.writable.wait(&mut state);+ }+ if !state.reader_open {+ return Err(io::Error::new(+ io::ErrorKind::BrokenPipe,+ "pane parser stopped",+ ));+ }+ let len = data.len().min(shared.capacity - state.bytes.len());+ let needed = state.bytes.len() + len;+ if needed > state.bytes.capacity() {+ // Grow only for queued output. The one-MiB limit is independent+ // of the parser batch size, as the socket buffer limit was.+ let capacity = needed.next_power_of_two().min(shared.capacity);+ let additional = capacity - state.bytes.len();+ state.bytes.reserve_exact(additional);+ }+ let was_empty = state.bytes.is_empty();+ state.bytes.extend(data[..len].iter().copied());+ drop(state);+ if was_empty {+ shared.readable.notify_one();+ }+ Ok(len)+ }++ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+}++impl Read for OutputReceiver {+ fn read(&mut self, data: &mut [u8]) -> io::Result<usize> {+ if data.is_empty() {+ return Ok(0);+ }+ let state = self.wait_for_data(|| {});+ Ok(self.copy_bytes(state, data))+ }+}++impl OutputReceiver {+ /// Allocate the parser's buffer only when output arrives. Release it+ /// with the byte ring after an idle wait, or once a burst is over and+ /// only sparse output follows; queued actions own their text.+ pub(crate) fn read_buffered(&mut self, data: &mut Vec<u8>, limit: usize) -> io::Result<usize> {+ if limit == 0 {+ return Ok(0);+ }+ let mut state = self.wait_for_data(|| *data = Vec::new());+ if state.bytes.is_empty() {+ return Ok(0);+ }+ if state.outlived_burst() {+ state.bytes.shrink_to_fit();+ *data = Vec::new();+ }+ let len = limit.min(state.bytes.len());+ if data.len() < len {+ data.resize(len, 0);+ }+ Ok(self.copy_bytes(state, &mut data[..len]))+ }++ fn wait_for_data(&self, mut release_buffer: impl FnMut()) -> MutexGuard<'_, State> {+ let shared = &self.0;+ let mut state = shared.state.lock();+ while state.bytes.is_empty() && state.writer_open {+ if shared+ .readable+ .wait_for(&mut state, IDLE_RELEASE)+ .timed_out()+ && state.bytes.is_empty()+ {+ // A busy pane keeps its buffers. An idle pane gives the+ // storage back before sleeping until its next output.+ state.bytes = VecDeque::new();+ release_buffer();+ while state.bytes.is_empty() && state.writer_open {+ shared.readable.wait(&mut state);+ }+ }+ }+ state+ }++ fn copy_bytes(&self, mut state: MutexGuard<'_, State>, data: &mut [u8]) -> usize {+ let len = data.len().min(state.bytes.len());+ let (first, second) = state.bytes.as_slices();+ let first_len = len.min(first.len());+ data[..first_len].copy_from_slice(&first[..first_len]);+ data[first_len..len].copy_from_slice(&second[..len - first_len]);+ let was_full = state.bytes.len() == self.0.capacity;+ state.bytes.drain(..len);+ drop(state);+ if was_full {+ self.0.writable.notify_one();+ }+ len+ }++ pub(crate) fn readable_now(&self) -> bool {+ let state = self.0.state.lock();+ !state.bytes.is_empty() || !state.writer_open+ }++ pub(crate) fn wait_readable(&self, timeout: Duration) -> bool {+ let deadline = Instant::now() + timeout;+ let mut state = self.0.state.lock();+ while state.bytes.is_empty() && state.writer_open {+ if self.0.readable.wait_until(&mut state, deadline).timed_out() {+ break;+ }+ }+ !state.bytes.is_empty() || !state.writer_open+ }+}++impl Drop for OutputSender {+ fn drop(&mut self) {+ self.0.state.lock().writer_open = false;+ self.0.readable.notify_one();+ }+}++impl Drop for OutputReceiver {+ fn drop(&mut self) {+ self.0.state.lock().reader_open = false;+ self.0.writable.notify_one();+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::mpsc;+ use std::thread;++ #[test]+ fn output_keeps_order_across_wrap_partial_reads_and_eof() {+ let (mut tx, mut rx) = channel_with_capacity(127);+ let expected: Vec<u8> = (0..MAX_CAPACITY * 2 + 17).map(|n| n as u8).collect();+ let input = expected.clone();+ let writer = thread::spawn(move || {+ for bytes in input.chunks(43) {+ tx.write_all(bytes).unwrap();+ }+ });+ let mut received = Vec::new();+ let mut bytes = [0; 211];+ let mut limit = 1;+ loop {+ let len = rx.read(&mut bytes[..limit]).unwrap();+ if len == 0 {+ break;+ }+ received.extend_from_slice(&bytes[..len]);+ limit = (limit * 3) % bytes.len() + 1;+ }+ writer.join().unwrap();+ assert_eq!(received, expected);+ }++ #[test]+ fn small_writes_are_coalesced_and_capacity_is_bounded() {+ let (mut tx, mut rx) = channel_with_capacity(20);+ tx.write_all(b"short ").unwrap();+ tx.write_all(b"command").unwrap();+ assert!(rx.readable_now());+ assert!(rx.wait_readable(Duration::ZERO));+ let mut bytes = [0; 32];+ assert_eq!(rx.read(&mut bytes).unwrap(), 13);+ assert_eq!(&bytes[..13], b"short command");+ assert_eq!(rx.0.state.lock().bytes.capacity(), 16);+ assert!(!rx.wait_readable(Duration::ZERO));+ drop(tx);+ assert!(rx.wait_readable(Duration::ZERO));+ assert_eq!(rx.read(&mut bytes).unwrap(), 0);+ assert_eq!(+ channel_with_capacity(usize::MAX).0 .0.capacity,+ MAX_CAPACITY+ );+ assert_eq!(channel_with_capacity(0).0 .0.capacity, 1);+ }++ #[test]+ fn blocked_writer_is_released_when_parser_closes() {+ let (mut tx, rx) = channel_with_capacity(1);+ tx.write_all(b"a").unwrap();+ let (done, result) = mpsc::channel();+ let writer = thread::spawn(move || done.send(tx.write_all(b"b")).unwrap());+ assert!(result.recv_timeout(Duration::from_millis(20)).is_err());+ drop(rx);+ assert_eq!(+ result+ .recv_timeout(Duration::from_secs(2))+ .unwrap()+ .unwrap_err()+ .kind(),+ io::ErrorKind::BrokenPipe+ );+ writer.join().unwrap();+ }++ #[test]+ fn idle_releases_storage_and_later_output_wakes_reader() {+ let (mut tx, mut rx) = channel_with_capacity(128);+ tx.write_all(b"a").unwrap();+ let mut byte = [0];+ assert_eq!(rx.read(&mut byte).unwrap(), 1);+ let shared = Arc::clone(&rx.0);+ let reader = thread::spawn(move || {+ assert_eq!(rx.read(&mut byte).unwrap(), 1);+ assert_eq!(&byte, b"b");+ assert_eq!(rx.read(&mut byte).unwrap(), 0);+ });+ let deadline = Instant::now() + Duration::from_secs(2);+ while shared.state.lock().bytes.capacity() > 0 && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(5));+ }+ assert_eq!(shared.state.lock().bytes.capacity(), 0);+ tx.write_all(b"b").unwrap();+ drop(tx);+ reader.join().unwrap();+ }++ #[test]+ fn production_write_credit_is_one_mib_and_allocated_only_as_needed() {+ let (mut tx, mut rx) = channel();+ assert_eq!(tx.0.capacity, 1024 * 1024);+ assert_eq!(tx.0.state.lock().bytes.capacity(), 0);+ tx.write_all(b"x").unwrap();+ assert!(tx.0.state.lock().bytes.capacity() <= 8);+ let input = vec![b'y'; MAX_CAPACITY - 1];+ tx.write_all(&input).unwrap();+ assert_eq!(tx.0.state.lock().bytes.len(), MAX_CAPACITY);+ assert_eq!(tx.0.state.lock().bytes.capacity(), MAX_CAPACITY);+ let (started, ready) = mpsc::channel();+ let (done, result) = mpsc::channel();+ let writer = thread::spawn(move || {+ started.send(()).unwrap();+ done.send(tx.write_all(b"z")).unwrap();+ });+ ready.recv().unwrap();+ assert!(result.recv_timeout(Duration::from_millis(20)).is_err());+ let mut head = [0; 1];+ assert_eq!(rx.read(&mut head).unwrap(), 1);+ assert_eq!(&head, b"x");+ result+ .recv_timeout(Duration::from_secs(2))+ .unwrap()+ .unwrap();+ writer.join().unwrap();+ let mut rest = Vec::new();+ rx.read_to_end(&mut rest).unwrap();+ assert_eq!(&rest[..input.len()], input.as_slice());+ assert_eq!(rest.last(), Some(&b'z'));+ }++ #[test]+ fn growth_after_wrap_preserves_bytes_and_never_exceeds_the_bound() {+ let (mut tx, mut rx) = channel_with_capacity(1024);+ for initial in [3, 5, 31, 129] {+ let prefix: Vec<u8> = (0..initial).map(|n| n as u8).collect();+ tx.write_all(&prefix).unwrap();+ let mut removed = [0; 2];+ assert_eq!(rx.read(&mut removed).unwrap(), 2);+ assert_eq!(&removed, &prefix[..2]);+ let next: Vec<u8> = (0..initial * 2 + 7).map(|n| (n + 101) as u8).collect();+ tx.write_all(&next).unwrap();+ assert!(rx.0.state.lock().bytes.capacity() <= 1024);+ let mut actual = vec![0; prefix.len() - 2 + next.len()];+ rx.read_exact(&mut actual).unwrap();+ assert_eq!(actual, [&prefix[2..], next.as_slice()].concat());+ }+ }+ #[test]+ fn buffered_read_defers_allocation_until_data_and_preserves_read_limits() {+ let (tx, mut rx) = channel();+ let mut buffer = Vec::new();+ drop(tx);+ assert_eq!(rx.read_buffered(&mut buffer, 128 * 1024).unwrap(), 0);+ assert_eq!(buffer.capacity(), 0, "EOF needs no parser buffer");++ let (mut tx, mut rx) = channel_with_capacity(127);+ let expected: Vec<u8> = (0..127).collect();+ tx.write_all(&expected).unwrap();+ drop(tx);+ let mut actual = Vec::new();+ for limit in [7, 17, 3, 64, 128] {+ let len = rx.read_buffered(&mut buffer, limit).unwrap();+ assert!(len <= limit);+ actual.extend_from_slice(&buffer[..len]);+ }+ assert_eq!(actual, expected);+ assert_eq!(rx.read_buffered(&mut buffer, 128).unwrap(), 0);+ assert!(buffer.capacity() <= 128);+ }++ #[test]+ fn sparse_output_does_not_allocate_the_configured_batch_size() {+ let (mut tx, mut rx) = channel();+ let mut buffer = Vec::new();+ tx.write_all(b"ready").unwrap();+ assert_eq!(rx.read_buffered(&mut buffer, 128 * 1024).unwrap(), 5);+ assert_eq!(&buffer[..5], b"ready");+ assert!(buffer.capacity() <= 64);++ let expected = vec![b'x'; 128 * 1024 + 17];+ tx.write_all(&expected).unwrap();+ drop(tx);+ let mut received = Vec::new();+ loop {+ let len = rx.read_buffered(&mut buffer, 128 * 1024).unwrap();+ if len == 0 {+ break;+ }+ received.extend_from_slice(&buffer[..len]);+ }+ assert_eq!(received, expected);+ assert!(buffer.capacity() <= 128 * 1024);+ }++ #[test]+ fn burst_storage_is_released_while_sparse_output_continues() {+ const BATCH: usize = 128 * 1024;+ let (mut tx, mut rx) = channel();+ let mut buffer = Vec::new();+ tx.write_all(&vec![b'x'; MAX_CAPACITY]).unwrap();+ let mut drained = 0;+ while drained < MAX_CAPACITY {+ drained += rx.read_buffered(&mut buffer, BATCH).unwrap();+ }+ assert_eq!(rx.0.state.lock().bytes.capacity(), MAX_CAPACITY);+ assert!(buffer.capacity() >= BATCH);++ // Straight after the burst the pane still counts as busy.+ rx.0.state.lock().last_backlog = Instant::now() + Duration::from_secs(60);+ tx.write_all(b"tick").unwrap();+ assert_eq!(rx.read_buffered(&mut buffer, BATCH).unwrap(), 4);+ assert_eq!(rx.0.state.lock().bytes.capacity(), MAX_CAPACITY);+ assert!(buffer.capacity() >= BATCH);++ // Output never stopped, so no idle wait ran, but the burst is over.+ // Queued bytes survive, including those a short read leaves behind.+ rx.0.state.lock().last_backlog = Instant::now() - IDLE_RELEASE;+ tx.write_all(b"tock").unwrap();+ assert_eq!(rx.read_buffered(&mut buffer, 2).unwrap(), 2);+ assert_eq!(&buffer[..2], b"to");+ assert!(buffer.capacity() <= 8);+ assert_eq!(rx.0.state.lock().bytes.capacity(), 4);+ assert_eq!(rx.read_buffered(&mut buffer, BATCH).unwrap(), 2);+ assert_eq!(&buffer[..2], b"ck");+ }++ #[test]+ fn a_deep_queue_counts_as_a_burst_however_old_the_last_one() {+ let (mut tx, mut rx) = channel();+ let mut buffer = Vec::new();+ tx.write_all(&vec![b'x'; KEPT_CAPACITY + 1]).unwrap();+ let capacity = rx.0.state.lock().bytes.capacity();+ assert!(capacity > KEPT_CAPACITY);+ let stale = Instant::now() - IDLE_RELEASE;+ rx.0.state.lock().last_backlog = stale;+ assert_eq!(rx.read_buffered(&mut buffer, 1).unwrap(), 1);+ assert_eq!(rx.0.state.lock().bytes.capacity(), capacity);+ assert!(rx.0.state.lock().last_backlog > stale);+ }++ #[test]+ fn one_pty_read_of_storage_stays_for_the_next_output() {+ let (mut tx, mut rx) = channel();+ let mut buffer = Vec::new();+ tx.write_all(&vec![b'x'; KEPT_CAPACITY]).unwrap();+ assert_eq!(+ rx.read_buffered(&mut buffer, KEPT_CAPACITY).unwrap(),+ KEPT_CAPACITY+ );+ rx.0.state.lock().last_backlog = Instant::now() - IDLE_RELEASE;+ tx.write_all(b"tick").unwrap();+ assert_eq!(rx.read_buffered(&mut buffer, KEPT_CAPACITY).unwrap(), 4);+ assert_eq!(rx.0.state.lock().bytes.capacity(), KEPT_CAPACITY);+ assert_eq!(buffer.len(), KEPT_CAPACITY);+ }++ #[test]+ fn idle_eof_releases_the_parser_buffer_and_byte_ring() {+ let (mut tx, mut rx) = channel_with_capacity(128);+ tx.write_all(b"ready").unwrap();+ let shared = Arc::clone(&rx.0);+ let (primed, ready) = mpsc::channel();+ let reader = thread::spawn(move || {+ let mut buffer = Vec::new();+ assert_eq!(rx.read_buffered(&mut buffer, 64).unwrap(), 5);+ assert_eq!(&buffer[..5], b"ready");+ assert!(buffer.capacity() > 0 && buffer.capacity() <= 64);+ primed.send(()).unwrap();+ assert_eq!(rx.read_buffered(&mut buffer, 64).unwrap(), 0);+ assert_eq!(buffer.capacity(), 0);+ });+ ready.recv().unwrap();+ let deadline = Instant::now() + Duration::from_secs(2);+ while shared.state.lock().bytes.capacity() > 0 && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(5));+ }+ assert_eq!(shared.state.lock().bytes.capacity(), 0);+ drop(tx);+ reader.join().unwrap();+ }+}