the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: reject oversized canonical input on macos (#4988)
Eric Yuebe0e73f724f2
diff --git a/docs/next/website/src/content/docs/ja/socket-api.mdx b/docs/next/website/src/content/docs/ja/socket-api.mdxindex a03c52ce1..eb693a51f 100644--- a/docs/next/website/src/content/docs/ja/socket-api.mdx+++ b/docs/next/website/src/content/docs/ja/socket-api.mdx@@ -119,6 +119,8 @@ CLI の `herdr api snapshot` は、クライアントやエージェントが簡`pane.send_keys` と `pane.send_input.keys` は Herdr のキーコンボ文字列を受け付けます: 通常の印字可能キー、`enter` や `esc` のような特殊キー、`ctrl+h`、`control+j`、`alt+x`、`shift+tab` のような修飾キーコード、`f1` のようなファンクションキー、`minus` や `plus` のような名前付き記号です。`prefix+` のバインド文字列は受け付けません。+macOS では、`pane.send_input`(`pane run` が使用)と `agent.start` は、コマンドを入力キューに受け入れる前に、ターミナルの現在のカノニカルモードの入力上限を確認します。Enter を含むエンコード済みの行が上限を超える場合、入力全体を拒否します。シェルプロンプトが表示されてから再試行してください。複数の短い行と raw モードの入力は引き続き使用できます。成功応答はキューへの受け入れを示し、コマンドの実行完了を意味しません。この確認は今回の送信だけを対象とし、以前の未完了行を検査したり、キューで待機中にターミナルモードが変わらないことを保証したりするものではありません。+```json{"id":"req_current","method":"pane.current","params":{"caller_pane_id":"w1:p1"}}{"id":"req_layout","method":"pane.layout","params":{"pane_id":"w1:p1"}}diff --git a/docs/next/website/src/content/docs/socket-api.mdx b/docs/next/website/src/content/docs/socket-api.mdxindex 5becbd8ea..547415a60 100644--- a/docs/next/website/src/content/docs/socket-api.mdx+++ b/docs/next/website/src/content/docs/socket-api.mdx@@ -138,6 +138,8 @@ like `ctrl+h`, `control+j`, `alt+x`, and `shift+tab`, function keys like`f1`, and named punctuation like `minus` and `plus`. They do not accept`prefix+` binding strings.+On macOS, `pane.send_input` (used by `pane run`) and `agent.start` check the terminal's current canonical input limit before accepting a command into the input queue. An oversized encoded line, including Enter, is rejected in full; wait for the shell prompt and retry. Multiple short lines and raw-mode input remain supported. Successful responses still acknowledge queue admission, not command execution. This check covers the current submission only: it cannot inspect an earlier incomplete line or guarantee the terminal mode will remain unchanged while input is queued.+```json{"id":"req_current","method":"pane.current","params":{"caller_pane_id":"w1:p1"}}{"id":"req_layout","method":"pane.layout","params":{"pane_id":"w1:p1"}}diff --git a/docs/next/website/src/content/docs/zh-cn/socket-api.mdx b/docs/next/website/src/content/docs/zh-cn/socket-api.mdxindex de5c7e7e7..1e54f14e2 100644--- a/docs/next/website/src/content/docs/zh-cn/socket-api.mdx+++ b/docs/next/website/src/content/docs/zh-cn/socket-api.mdx@@ -119,6 +119,8 @@ CLI 的 `herdr api snapshot` 会把当前 `session.snapshot` 响应输出为 JSO`pane.send_keys` 和 `pane.send_input.keys` 接受 Herdr 组合键字符串: 普通可打印键、`enter` 和 `esc` 这类特殊键、`ctrl+h`、`control+j`、`alt+x`、`shift+tab` 这类修饰组合键、`f1` 这类功能键,以及 `minus` 和 `plus` 这类命名标点。它们不接受 `prefix+` 绑定字符串。+在 macOS 上,`pane.send_input`(由 `pane run` 使用)和 `agent.start` 会在命令进入输入队列前,检查终端当前规范模式的输入长度限制。编码后的行(包括 Enter)超限时,整条输入会被拒绝;请等待 shell 提示符出现后重试。多条短行和原始模式输入仍受支持。成功响应仍只表示已接受入队,不表示命令已执行。检查仅覆盖本次提交:它无法检查此前尚未完成的输入行,也无法保证排队期间终端模式不会改变。+```json{"id":"req_current","method":"pane.current","params":{"caller_pane_id":"w1:p1"}}{"id":"req_layout","method":"pane.layout","params":{"pane_id":"w1:p1"}}diff --git a/src/app/agents.rs b/src/app/agents.rsindex 0aa26fb21..89625f008 100644--- a/src/app/agents.rs+++ b/src/app/agents.rs@@ -208,6 +208,10 @@ impl App {return Err(AgentStartError::InvalidTimeout);}+ runtime+ .validate_input_submission(&bytes)+ .map_err(|err| AgentStartError::InputFailed(err.to_string()))?;+let now = Instant::now();let terminal = self.statediff --git a/src/app/api/panes.rs b/src/app/api/panes.rsindex 435ecdc00..b5f3baf67 100644--- a/src/app/api/panes.rs+++ b/src/app/api/panes.rs@@ -1946,6 +1946,9 @@ impl App {Ok(bytes) => bytes,Err(key) => return encode_error(id, "invalid_key", format!("unsupported key {key}")),};+ if let Err(err) = runtime.validate_input_submission(&bytes) {+ return encode_error(id, "pane_send_failed", err.to_string());+ }if let Err(err) = runtime.try_send_bytes(Bytes::from(bytes)) {return encode_error(id, "pane_send_failed", err.to_string());}diff --git a/src/pane.rs b/src/pane.rsindex b0bceae36..f80baeb82 100644--- a/src/pane.rs+++ b/src/pane.rs@@ -3674,6 +3674,21 @@ impl PaneRuntime {self.io.try_send_bytes(bytes)}+ /// Preflight a complete API command without changing input queue semantics.+ pub(crate) fn validate_input_submission(&self, bytes: &[u8]) -> std::io::Result<()> {+ match &self.io {+ #[cfg(unix)]+ PaneRuntimeIo::Actor(actor) => actor.validate_input_submission(bytes),+ #[cfg(windows)]+ PaneRuntimeIo::Actor(_) => {+ let _ = bytes;+ Ok(())+ }+ #[cfg(test)]+ PaneRuntimeIo::TestChannel { .. } => Ok(()),+ }+ }+pub fn queue_user_input_submission(&self,text: Bytes,@@ -3885,6 +3900,13 @@ impl PaneRuntime {Self::test_with_channel_and_scrollback_bytes(cols, rows, 0, &[], 4)}+ #[cfg(unix)]+ pub(crate) fn test_with_actor(actor: PtyIoActorHandle) -> Self {+ let (mut runtime, _) = Self::test_with_channel(80, 24);+ runtime.io = PaneRuntimeIo::Actor(actor);+ runtime+ }+pub(crate) fn test_with_channel_capacity(cols: u16,rows: u16,diff --git a/src/platform/macos.rs b/src/platform/macos.rsindex a4c174659..484ed1cbe 100644--- a/src/platform/macos.rs+++ b/src/platform/macos.rs@@ -32,6 +32,12 @@ pub(crate) use shutdown::monitor_host_shutdown;#[cfg(test)]mod config_file_tests;+#[cfg(test)]+mod input_tests;++mod input;+pub(crate) use input::PtyInputGuard;+pub(crate) fn config_file_link_count(path: &Path) -> std::io::Result<u64> {use std::os::unix::fs::MetadataExt;Ok(std::fs::metadata(path)?.nlink())diff --git a/src/platform/macos/input.rs b/src/platform/macos/input.rsnew file mode 100644index 000000000..ec80f5248--- /dev/null+++ b/src/platform/macos/input.rs@@ -0,0 +1,143 @@+//! Preflight for submissions that overflow Darwin's canonical line discipline.++use std::os::fd::RawFd;+use std::sync::{Arc, Weak};++/// Samples the actor's terminal without keeping its master descriptor open.+#[derive(Clone, Default)]+pub(crate) struct PtyInputGuard(Weak<std::fs::File>);++impl PtyInputGuard {+ pub(crate) fn new(master: &Arc<std::fs::File>) -> Self {+ Self(Arc::downgrade(master))+ }++ /// Check the current terminal mode before an API command enters the queue.+ pub(crate) fn validate(&self, bytes: &[u8]) -> std::io::Result<()> {+ use std::os::fd::AsRawFd;++ let master = self.0.upgrade().ok_or_else(|| {+ std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pty actor closed")+ })?;+ validate_pty_submission(master.as_raw_fd(), bytes, &[])+ }+}++/// Validate encoded input against the terminal mode sampled at admission.+/// This bounds the current submission, not earlier incomplete input or later+/// mode changes while accepted input waits in the actor's existing queue.+pub(crate) fn validate_pty_submission(fd: RawFd, text: &[u8], enter: &[u8]) -> std::io::Result<()> {+ let mut termios = std::mem::MaybeUninit::<libc::termios>::uninit();+ if unsafe { libc::tcgetattr(fd, termios.as_mut_ptr()) } != 0 {+ let err = std::io::Error::last_os_error();+ // Non-terminal transports have no canonical line discipline.+ return if matches!(err.raw_os_error(), Some(libc::ENOTTY | libc::EOPNOTSUPP)) {+ Ok(())+ } else {+ Err(err)+ };+ }+ let termios = unsafe { termios.assume_init() };+ if termios.c_lflag & libc::ICANON == 0 {+ return Ok(());+ }+ let limit = unsafe { libc::fpathconf(fd, libc::_PC_MAX_CANON) };+ if limit <= 0 {+ return Err(std::io::Error::other(+ "could not determine canonical input capacity",+ ));+ }+ let line_len = longest_canonical_line(&termios, text.iter().chain(enter).copied());+ if line_len > limit as usize {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ format!("input contains a {line_len}-byte line but the terminal is in canonical mode with a {limit}-byte limit; wait for the shell prompt and retry"),+ ));+ }+ Ok(())+}++/// Count an upper bound between effective delimiters. Editing controls do not+/// reduce the bound: this is a preflight, not a shadow of the kernel's queue.+fn longest_canonical_line(termios: &libc::termios, input: impl Iterator<Item = u8>) -> usize {+ let iflag = termios.c_iflag;+ let lflag = termios.c_lflag;+ let extproc = lflag & libc::EXTPROC != 0;+ let extended = lflag & libc::IEXTEN != 0;+ let matches_control =+ |byte: u8, index: usize| byte != libc::_POSIX_VDISABLE && byte == termios.c_cc[index];+ let mut quoted = false;+ let mut line_len = 0usize;+ let mut longest = 0;+ for mut byte in input {+ if iflag & libc::ISTRIP != 0 {+ byte &= 0x7f;+ }+ let was_quoted = std::mem::take(&mut quoted);+ let mut delimiter = false;+ if !extproc && !was_quoted {+ if extended && matches_control(byte, libc::VLNEXT) {+ quoted = true;+ continue;+ }+ // Controls consumed before CR translation / line-break detection+ // cannot become delimiters, even with custom control characters.+ let consumed = (extended && matches_control(byte, libc::VDISCARD))+ || (lflag & libc::ISIG != 0+ && [libc::VINTR, libc::VQUIT, libc::VSUSP]+ .into_iter()+ .any(|index| matches_control(byte, index)))+ || (iflag & libc::IXON != 0+ && [libc::VSTART, libc::VSTOP]+ .into_iter()+ .any(|index| matches_control(byte, index)));+ if consumed {+ continue;+ }+ if byte == b'\r' {+ if iflag & libc::IGNCR != 0 {+ continue;+ }+ if iflag & libc::ICRNL != 0 {+ byte = b'\n';+ }+ } else if byte == b'\n' && iflag & libc::INLCR != 0 {+ byte = b'\r';+ }+ }+ if !was_quoted {+ let editing = !extproc+ && ([libc::VERASE, libc::VKILL]+ .into_iter()+ .any(|index| matches_control(byte, index))+ || (extended+ && [libc::VWERASE, libc::VREPRINT, libc::VSTATUS]+ .into_iter()+ .any(|index| matches_control(byte, index))));+ if editing {+ continue;+ }+ delimiter = byte == b'\n'+ || matches_control(byte, libc::VEOF)+ || matches_control(byte, libc::VEOL)+ || (extended && matches_control(byte, libc::VEOL2));+ }+ // Darwin escapes an unstripped 0xff when PARMRK is active.+ let width = if !was_quoted+ && byte == 0xff+ && iflag & libc::PARMRK != 0+ && iflag & libc::ISTRIP == 0+ && iflag & (libc::IGNBRK | libc::IGNPAR) != (libc::IGNBRK | libc::IGNPAR)+ {+ 2+ } else {+ 1+ };+ line_len = line_len.saturating_add(width);+ longest = longest.max(line_len);+ if delimiter {+ line_len = 0;+ }+ }+ longest+}diff --git a/src/platform/macos/input_tests.rs b/src/platform/macos/input_tests.rsnew file mode 100644index 000000000..5d73c248d--- /dev/null+++ b/src/platform/macos/input_tests.rs@@ -0,0 +1,387 @@+use std::io::{Read, Write};+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};+use std::sync::mpsc;+use std::time::Duration;++use bytes::Bytes;++use crate::api::schema::{AgentStartParams, Method, PaneSendInputParams, Request};+use crate::app::{App, AppPolicy, AppState};+use crate::pty::actor::{PtyIoActor, PtyIoActorConfig, PtyReadResult};+use crate::terminal::{TerminalId, TerminalRuntime};++fn pty_pair() -> (OwnedFd, std::fs::File) {+ let mut master = -1;+ let mut slave = -1;+ assert_eq!(+ unsafe {+ libc::openpty(+ &mut master,+ &mut slave,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ )+ },+ 0+ );+ (+ unsafe { OwnedFd::from_raw_fd(master) },+ std::fs::File::from(unsafe { OwnedFd::from_raw_fd(slave) }),+ )+}++fn set_canonical(slave: &std::fs::File, canonical: bool) {+ let mut termios = std::mem::MaybeUninit::<libc::termios>::uninit();+ assert_eq!(+ unsafe { libc::tcgetattr(slave.as_raw_fd(), termios.as_mut_ptr()) },+ 0+ );+ let mut termios = unsafe { termios.assume_init() };+ termios.c_lflag &= !(libc::ICANON | libc::ECHO);+ if canonical {+ termios.c_lflag |= libc::ICANON;+ }+ termios.c_cc[libc::VMIN] = 0;+ termios.c_cc[libc::VTIME] = 20;+ assert_eq!(+ unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &termios) },+ 0+ );+}++fn read_line(slave: &mut std::fs::File) -> Vec<u8> {+ let mut poll = libc::pollfd {+ fd: slave.as_raw_fd(),+ events: libc::POLLIN,+ revents: 0,+ };+ assert_eq!(unsafe { libc::poll(&mut poll, 1, 2000) }, 1);+ let mut received = vec![0; 2048];+ let count = slave.read(&mut received).unwrap();+ received.truncate(count);+ received+}++fn app_with_actor(handle: crate::pty::actor::PtyIoActorHandle) -> (App, String, TerminalId) {+ let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(+ &crate::config::Config::default(),+ AppPolicy::TEST,+ None,+ api_rx,+ crate::api::EventHub::default(),+ );+ app.state = AppState::test_with_adversarial_identity_state();+ let pane = app.state.workspaces[0].tabs[0].root_pane;+ let terminal_id = app.state.workspaces[0].terminal_id(pane).unwrap().clone();+ app.terminal_runtimes.insert(+ terminal_id.clone(),+ TerminalRuntime::test_with_actor(handle),+ );+ let pane_id = app.public_pane_id(0, pane).unwrap();+ app.state.assert_invariants_for_test();+ (app, pane_id, terminal_id)+}++fn start_request(pane_id: &str, argument: &str) -> Request {+ Request {+ id: "start".into(),+ method: Method::AgentStart(AgentStartParams {+ name: "worker".into(),+ kind: "codex".into(),+ pane_id: pane_id.into(),+ args: vec!["resume".into(), argument.into()],+ timeout_ms: Some(10_000),+ }),+ }+}++fn pane_request(pane_id: &str, text: &str) -> Request {+ Request {+ id: "input".into(),+ method: Method::PaneSendInput(PaneSendInputParams {+ pane_id: pane_id.into(),+ text: text.into(),+ keys: vec!["enter".into()],+ }),+ }+}++#[tokio::test]+async fn canonical_api_rejection_writes_nothing_and_allows_same_name_retry() {+ for agent_start in [false, true] {+ let (master, mut slave) = pty_pair();+ set_canonical(&slave, true);+ let limit = unsafe { libc::fpathconf(slave.as_raw_fd(), libc::_PC_MAX_CANON) } as usize;+ assert_eq!(limit, 1024);+ let handle = PtyIoActor::spawn(PtyIoActorConfig {+ pane_id: 1,+ master_fd: master,+ initially_quiesced: false,+ on_read: Box::new(|_| PtyReadResult::empty()),+ on_reader_exit: None,+ })+ .unwrap();+ let (mut app, pane_id, terminal_id) = app_with_actor(handle);+ // Check encoded bytes, including Enter, and reject the entire input even+ // when a preceding line would fit. Agent arguments cannot contain LF.+ let rejected = if agent_start {+ vec!["é".repeat(limit / 2)]+ } else {+ vec![+ "é".repeat(limit / 2),+ "x".repeat(limit),+ format!("first line\n{}", "x".repeat(limit)),+ ]+ };+ for text in rejected {+ let request = if agent_start {+ start_request(&pane_id, &text)+ } else {+ pane_request(&pane_id, &text)+ };+ let response: serde_json::Value =+ serde_json::from_str(&app.handle_api_request(request)).unwrap();+ assert_eq!(+ response["error"]["code"],+ if agent_start {+ "agent_start_input_failed"+ } else {+ "pane_send_failed"+ }+ );+ assert!(response["error"]["message"]+ .as_str()+ .unwrap()+ .contains("canonical mode"));+ let terminal = &app.state.terminals[&terminal_id];+ assert!(terminal.agent_name.is_none());+ assert!(terminal.managed_agent_kind().is_none());+ assert!(terminal.persisted_agent_session.is_none());+ app.state.assert_invariants_for_test();+ }+ let request = if agent_start {+ start_request(&pane_id, "retry")+ } else {+ pane_request(&pane_id, "retry")+ };+ let response: serde_json::Value =+ serde_json::from_str(&app.handle_api_request(request)).unwrap();+ assert!(response.get("error").is_none(), "{response}");+ let received = String::from_utf8(read_line(&mut slave)).unwrap();+ assert!(received.contains("retry"));+ assert!(!received.contains("first line") && !received.contains('é'));+ if agent_start {+ assert_eq!(+ app.state.terminals[&terminal_id].agent_name.as_deref(),+ Some("worker")+ );+ } else {+ assert_eq!(received, "retry\n");+ let text = "x".repeat(limit - 1);+ let response: serde_json::Value =+ serde_json::from_str(&app.handle_api_request(pane_request(&pane_id, &text)))+ .unwrap();+ assert!(response.get("error").is_none(), "{response}");+ assert_eq!(read_line(&mut slave), format!("{text}\n").as_bytes());+ }+ app.state.assert_invariants_for_test();+ }+}++#[tokio::test]+async fn input_admission_does_not_wait_for_actor_and_raw_input_stays_intact() {+ let (master, mut slave) = pty_pair();+ set_canonical(&slave, true);+ let (entered_tx, entered_rx) = mpsc::channel();+ let (resume_tx, resume_rx) = mpsc::channel();+ let mut barrier = Some((entered_tx, resume_rx));+ let handle = PtyIoActor::spawn(PtyIoActorConfig {+ pane_id: 1,+ master_fd: master,+ initially_quiesced: false,+ on_read: Box::new(move |_| {+ if let Some((entered, resume)) = barrier.take() {+ let _ = entered.send(());+ let _ = resume.recv();+ }+ PtyReadResult::empty()+ }),+ on_reader_exit: None,+ })+ .unwrap();+ let (mut app, pane_id, _) = app_with_actor(handle);+ slave.write_all(b"barrier").unwrap();+ entered_rx.recv_timeout(Duration::from_secs(2)).unwrap();+ let text = "x".repeat(3017);+ let response: serde_json::Value =+ serde_json::from_str(&app.handle_api_request(pane_request(&pane_id, &text))).unwrap();+ assert_eq!(response["error"]["code"], "pane_send_failed");+ set_canonical(&slave, false);+ let response: serde_json::Value =+ serde_json::from_str(&app.handle_api_request(pane_request(&pane_id, &text))).unwrap();+ assert!(response.get("error").is_none(), "{response}");+ // Both rejection and successful admission return while the actor is held.+ resume_tx.send(()).unwrap();+ let mut received = vec![0; text.len() + 1];+ slave.read_exact(&mut received).unwrap();+ assert_eq!(received, format!("{text}\n").as_bytes());+}++#[test]+fn input_guard_does_not_keep_the_master_open() {+ let (master, slave) = pty_pair();+ set_canonical(&slave, true);+ let owner = std::sync::Arc::new(std::fs::File::from(master));+ let guard = super::PtyInputGuard::new(&owner);+ assert_eq!(std::sync::Arc::strong_count(&owner), 1);+ guard.validate(b"valid\n").unwrap();+ drop(owner);+ assert_eq!(+ guard.validate(b"valid\n").unwrap_err().kind(),+ std::io::ErrorKind::BrokenPipe+ );+ assert_eq!(+ guard.clone().validate(b"valid\n").unwrap_err().kind(),+ std::io::ErrorKind::BrokenPipe+ );+}++#[test]+fn canonical_multiline_submission_preserves_each_line() {+ for delimiter in [b'\n', b'\r', b'|', 4] {+ let (master, mut slave) = pty_pair();+ set_canonical(&slave, true);+ let mut settings = std::mem::MaybeUninit::<libc::termios>::uninit();+ assert_eq!(+ unsafe { libc::tcgetattr(slave.as_raw_fd(), settings.as_mut_ptr()) },+ 0+ );+ let mut settings = unsafe { settings.assume_init() };+ settings.c_cc[libc::VEOL] = b'|';+ settings.c_cc[libc::VEOF] = 4;+ settings.c_iflag |= libc::ICRNL;+ settings.c_iflag &= !(libc::IGNCR | libc::INLCR);+ assert_eq!(+ unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &settings) },+ 0+ );+ let handle = PtyIoActor::spawn(PtyIoActorConfig {+ pane_id: 1,+ master_fd: master,+ initially_quiesced: false,+ on_read: Box::new(|_| PtyReadResult::empty()),+ on_reader_exit: None,+ })+ .unwrap();+ let line = [vec![b'x'; 600], vec![delimiter]].concat();+ let bytes = line.repeat(2);+ let expected = bytes+ .iter()+ .copied()+ .filter(|byte| *byte != 4)+ .map(|byte| if byte == b'\r' { b'\n' } else { byte })+ .collect::<Vec<_>>();+ let reader = std::thread::spawn(move || {+ let mut received = Vec::new();+ while received.len() < expected.len() {+ received.extend(read_line(&mut slave));+ }+ assert_eq!(received, expected);+ });+ handle.validate_input_submission(&bytes).unwrap();+ handle.try_write_user_input(Bytes::from(bytes)).unwrap();+ reader.join().unwrap();+ handle.shutdown();+ }+}++#[test]+fn canonical_preflight_respects_quoted_and_translated_delimiters() {+ let (master, slave) = pty_pair();+ set_canonical(&slave, true);+ let mut settings = std::mem::MaybeUninit::<libc::termios>::uninit();+ assert_eq!(+ unsafe { libc::tcgetattr(slave.as_raw_fd(), settings.as_mut_ptr()) },+ 0+ );+ let original = unsafe { settings.assume_init() };+ let prefix = vec![b'x'; 600];+ let suffix = vec![b'y'; 600];+ for (middle, setting) in [+ (vec![b'\n'], 0),+ (vec![b'\r'], 1),+ (vec![22, b'\n'], 2),+ (vec![b'\n'], 3),+ (vec![b'\n'], 4),+ (vec![150, b'\n'], 5),+ (vec![b'|'], 6),+ ] {+ let mut settings = original;+ settings.c_lflag |= libc::IEXTEN | libc::ISIG;+ settings.c_cc[libc::VLNEXT] = 22;+ match setting {+ 0 => settings.c_iflag |= libc::INLCR,+ 1 => settings.c_iflag |= libc::IGNCR,+ 2 => {}+ 3 => settings.c_cc[libc::VINTR] = b'\n',+ 4 => settings.c_cc[libc::VERASE] = b'\n',+ 5 => settings.c_iflag |= libc::ISTRIP,+ 6 => {+ settings.c_cc[libc::VEOL] = libc::_POSIX_VDISABLE;+ settings.c_cc[libc::VEOL2] = b'|';+ settings.c_lflag &= !libc::IEXTEN;+ }+ _ => unreachable!(),+ }+ assert_eq!(+ unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &settings) },+ 0+ );+ let input = [prefix.clone(), middle, suffix.clone()].concat();+ let result = super::input::validate_pty_submission(master.as_raw_fd(), &input, b"\n");+ assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidInput);+ }++ // A quoted newline in the Enter part must not reset a line begun in text.+ let mut settings = original;+ settings.c_lflag |= libc::IEXTEN;+ settings.c_cc[libc::VLNEXT] = 22;+ assert_eq!(+ unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &settings) },+ 0+ );+ let text = [prefix.clone(), vec![22]].concat();+ let enter = [vec![b'\n'], suffix.clone(), vec![b'\n']].concat();+ assert!(super::input::validate_pty_submission(master.as_raw_fd(), &text, &enter).is_err());+ // EXTPROC bypasses quoting and translations, but still recognizes line breaks.+ let external_processing: libc::c_int = 1;+ assert_eq!(+ unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCEXT, &external_processing) },+ 0+ );+ settings.c_iflag |= libc::INLCR;+ assert_eq!(+ unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &settings) },+ 0+ );+ assert!(super::input::validate_pty_submission(master.as_raw_fd(), &text, &enter).is_ok());+ let external_processing: libc::c_int = 0;+ assert_eq!(+ unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCEXT, &external_processing) },+ 0+ );++ let mut settings = original;+ settings.c_iflag |= libc::PARMRK;+ settings.c_iflag &= !(libc::ISTRIP | libc::IGNPAR);+ assert_eq!(+ unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &settings) },+ 0+ );+ assert!(super::input::validate_pty_submission(master.as_raw_fd(), &[0xff; 511], b"\n").is_ok());+ assert!(+ super::input::validate_pty_submission(master.as_raw_fd(), &[0xff; 512], b"\n").is_err()+ );+}diff --git a/src/platform/mod.rs b/src/platform/mod.rsindex 275a99d5e..0349d7c6f 100644--- a/src/platform/mod.rs+++ b/src/platform/mod.rs@@ -424,6 +424,22 @@ mod remote_bridge;mod remote_bridge_tests;#[cfg(unix)]mod unix_common;+/// Other Unix platforms keep their existing input admission policy.+/// Their _PC_MAX_CANON values need not describe the actual queue capacity.+#[cfg(all(unix, not(target_os = "macos")))]+#[derive(Clone, Default)]+pub(crate) struct PtyInputGuard;++#[cfg(all(unix, not(target_os = "macos")))]+impl PtyInputGuard {+ pub(crate) fn new(_master: &std::sync::Arc<std::fs::File>) -> Self {+ Self+ }++ pub(crate) fn validate(&self, _bytes: &[u8]) -> std::io::Result<()> {+ Ok(())+ }+}#[cfg(unix)]pub(crate) mod unix_image_files;#[cfg(unix)]diff --git a/src/pty/actor/unix.rs b/src/pty/actor/unix.rsindex 4d57dd161..47f3c672e 100644--- a/src/pty/actor/unix.rs+++ b/src/pty/actor/unix.rs@@ -98,6 +98,7 @@ pub(crate) struct PtyIoActorHandle {user_writes: Arc<Mutex<UserWriteGate>>,controls: Arc<Mutex<SharedPtyControls>>,response_order: Arc<Mutex<()>>,+ input_guard: crate::platform::PtyInputGuard,}#[derive(Debug)]@@ -106,6 +107,10 @@ struct UserWriteGate {}impl PtyIoActorHandle {+ pub(crate) fn validate_input_submission(&self, bytes: &[u8]) -> std::io::Result<()> {+ self.input_guard.validate(bytes)+ }+pub(crate) fn try_write_user_input(&self,bytes: Bytes,@@ -393,6 +398,7 @@ impl PtyIoActor {}));let controls = Arc::new(Mutex::new(SharedPtyControls::default()));let response_order = Arc::new(Mutex::new(()));+ let file = Arc::new(std::fs::File::from(config.master_fd));let handle = PtyIoActorHandle {data_tx,control_tx,@@ -400,11 +406,12 @@ impl PtyIoActor {user_writes,controls: Arc::clone(&controls),response_order: Arc::clone(&response_order),+ input_guard: crate::platform::PtyInputGuard::new(&file),};let mut runner = PtyIoActorRunner {pane_id: config.pane_id,- file: std::fs::File::from(config.master_fd),+ file,data_rx,control_rx,state: if config.initially_quiesced {@@ -442,7 +449,7 @@ impl PtyIoActor {struct PtyIoActorRunner {pane_id: u32,- file: std::fs::File,+ file: Arc<std::fs::File>,data_rx: mpsc::Receiver<PtyIoDataCommand>,control_rx: std_mpsc::Receiver<PtyIoControlCommand>,state: ActorState,@@ -815,7 +822,7 @@ impl PtyIoActorRunner {fn read_once(&mut self) -> bool {let mut buf = [0u8; 8192];- match self.file.read(&mut buf) {+ match self.file.as_ref().read(&mut buf) {Ok(0) => false,Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => true,Err(err) if err.kind() == std::io::ErrorKind::Interrupted => true,@@ -931,7 +938,7 @@ impl PtyIoActorRunner {fn flush_pending_writes_once(&mut self) -> std::io::Result<Option<SubmissionBoundary>> {while let Some(write) = self.pending_writes.front() {let chunk = &write.bytes[self.current_write_offset..];- match self.file.write(chunk) {+ match self.file.as_ref().write(chunk) {Ok(0) => {return Err(std::io::Error::new(std::io::ErrorKind::WriteZero,@@ -944,7 +951,7 @@ impl PtyIoActorRunner {let completed = self.pending_writes.pop_front().unwrap();self.current_write_offset = 0;if let Some(boundary) = completed.boundary {- self.file.flush()?;+ self.file.as_ref().flush()?;return Ok(Some(boundary));}}@@ -959,7 +966,7 @@ impl PtyIoActorRunner {}}}- self.file.flush()?;+ self.file.as_ref().flush()?;Ok(None)}@@ -1098,7 +1105,7 @@ mod tests {let wake_pipe = fd::create_wake_pipe().expect("wake pipe");let runner = PtyIoActorRunner {pane_id: 1,- file: std::fs::File::from(owned),+ file: Arc::new(std::fs::File::from(owned)),data_rx,control_rx,state: ActorState::Running,@@ -1600,6 +1607,30 @@ mod tests {handle.shutdown();}+ #[tokio::test]+ async fn input_preflight_preserves_handoff_and_shutdown_write_gates() {+ let (handle, mut peer, _read_rx) = actor_with_socket_pair(false);+ let runtime = crate::terminal::TerminalRuntime::test_with_actor(handle.clone());+ handle.begin_handoff(Duration::from_secs(1)).unwrap();+ // A successful preflight is not permission to bypass the existing gate.+ runtime.validate_input_submission(b"blocked").unwrap();+ assert!(runtime+ .try_send_bytes(Bytes::from_static(b"blocked"))+ .is_err());+ handle.rollback_handoff().unwrap();+ runtime.validate_input_submission(b"after").unwrap();+ runtime+ .try_send_bytes(Bytes::from_static(b"after"))+ .unwrap();+ let mut bytes = [0; 5];+ peer.read_exact(&mut bytes).unwrap();+ assert_eq!(&bytes, b"after");+ handle.shutdown();+ assert!(runtime+ .try_send_bytes(Bytes::from_static(b"closed"))+ .is_err());+ }+#[test]fn resize_and_nudge_keep_latest_request_when_command_queue_is_full() {let (data_tx, _data_rx) = mpsc::channel(1);@@ -1618,6 +1649,7 @@ mod tests {user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),controls: Arc::clone(&controls),response_order: Arc::new(Mutex::new(())),+ input_guard: Default::default(),};handle.resize(20, 80, 8, 16, vec![Bytes::from_static(b"old")]);@@ -1669,7 +1701,7 @@ mod tests {let query_light = Arc::clone(&light);let runner = PtyIoActorRunner {pane_id: 1,- file: std::fs::File::from(owned),+ file: Arc::new(std::fs::File::from(owned)),data_rx,control_rx,state: ActorState::Running,@@ -1697,6 +1729,7 @@ mod tests {user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),controls,response_order,+ input_guard: crate::platform::PtyInputGuard::new(&runner.file),};let (changed_tx, changed_rx) = std_mpsc::channel();let (continue_tx, continue_rx) = std_mpsc::channel();@@ -1766,6 +1799,7 @@ mod tests {user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),controls: Arc::new(Mutex::new(SharedPtyControls::default())),response_order: Arc::new(Mutex::new(())),+ input_guard: Default::default(),};let handoff = std::thread::spawn(move || handle.begin_handoff(Duration::from_secs(1)));@@ -1802,7 +1836,9 @@ mod tests {.expect("queued write");let mut runner = PtyIoActorRunner {pane_id: 1,- file: std::fs::File::from(unsafe { OwnedFd::from_raw_fd(actor_socket.into_raw_fd()) }),+ file: Arc::new(std::fs::File::from(unsafe {+ OwnedFd::from_raw_fd(actor_socket.into_raw_fd())+ })),data_rx,control_rx,state: ActorState::Running,diff --git a/src/terminal/runtime.rs b/src/terminal/runtime.rsindex 682aaae2d..23b61da26 100644--- a/src/terminal/runtime.rs+++ b/src/terminal/runtime.rs@@ -478,6 +478,10 @@ impl TerminalRuntime {self.0.try_send_bytes(bytes)}+ pub(crate) fn validate_input_submission(&self, bytes: &[u8]) -> std::io::Result<()> {+ self.0.validate_input_submission(bytes)+ }+pub fn queue_user_input_submission(&self,text: Bytes,@@ -632,6 +636,11 @@ impl TerminalRuntime {(Self(runtime), rx)}+ #[cfg(unix)]+ pub(crate) fn test_with_actor(actor: crate::pty::actor::PtyIoActorHandle) -> Self {+ Self(crate::pane::PaneRuntime::test_with_actor(actor))+ }+pub(crate) fn test_with_channel_capacity(cols: u16,rows: u16,