use std::io::IsTerminal;
use std::os::unix::process::CommandExt;
use anyhow::{Context, Result};
use nix::sys::termios::{cfmakeraw, tcgetattr, tcsetattr, SetArg, Termios};
use std::collections::VecDeque;
use std::path::Path;
use tam_proto::{
AgentInfo, ChatInfo, MemberInfo, MemberOutcome, MemberState, NewMember, Request, Response,
RunInfo, ScreenInfo, ServerMessage, SessionChoice, SessionInfo, ShellInfo, ShellPlace,
TaskInfo, WorktreeReport,
};
use tokio::io::unix::AsyncFd;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, Interest};
use tokio::net::UnixStream;
use tokio::signal::unix::{signal, SignalKind};
use tokio::time::{sleep_until, Duration, Instant};
use crate::script::{self, ErrorKind};
const DETACH_KEY: u8 = 0x1d;
const RESIZE_THROTTLE: Duration = Duration::from_millis(40);
const RESIZE_TIMEOUT: Duration = Duration::from_millis(500);
pub enum DropOutcome {
Dropped { warnings: Vec<String> },
Refused { worktrees: Vec<WorktreeReport> },
}
pub struct Client {
reader: BufReader<tokio::net::unix::OwnedReadHalf>,
writer: tokio::net::unix::OwnedWriteHalf,
pending_events: VecDeque<tam_proto::Event>,
line: Vec<u8>,
}
impl Client {
pub async fn try_connect() -> Result<Option<Self>> {
Self::try_connect_at(&tam_proto::default_socket_path()).await
}
pub async fn try_connect_at(socket_path: &Path) -> Result<Option<Self>> {
match UnixStream::connect(socket_path).await {
Ok(stream) => {
let (reader, writer) = stream.into_split();
let mut client = Self {
reader: BufReader::new(reader),
writer,
pending_events: VecDeque::new(),
line: Vec::new(),
};
client.handshake().await?;
Ok(Some(client))
}
Err(_) => Ok(None),
}
}
pub async fn connect() -> Result<Self> {
let socket_path = tam_proto::default_socket_path();
let stream = match UnixStream::connect(&socket_path).await {
Ok(s) => s,
Err(_) => {
Self::start_daemon().map_err(daemon_error)?;
let mut attempts = 0;
loop {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
match UnixStream::connect(&socket_path).await {
Ok(s) => break s,
Err(_) if attempts < 40 => {
attempts += 1;
continue;
}
Err(e) => {
return Err(daemon_error(
anyhow::Error::new(e)
.context("failed to connect to daemon after starting it"),
));
}
}
}
}
};
let (reader, writer) = stream.into_split();
let mut client = Self {
reader: BufReader::new(reader),
writer,
pending_events: VecDeque::new(),
line: Vec::new(),
};
client.handshake().await?;
Ok(client)
}
async fn handshake(&mut self) -> Result<()> {
let resp = self
.send(Request::Hello {
protocol_version: tam_proto::PROTOCOL_VERSION,
})
.await?;
match resp {
Response::Hello { .. } => Ok(()),
Response::Error { message } if message.contains("protocol version mismatch") => {
Err(script::error(ErrorKind::Daemon, message))
}
Response::Error { .. } => {
Err(script::error(
ErrorKind::Daemon,
"daemon is running an older version. Run 'tam shutdown' then retry.",
))
}
_ => Ok(()),
}
}
fn start_daemon() -> Result<()> {
use std::process::{Command, Stdio};
let exe = std::env::current_exe().context("failed to determine current executable")?;
eprintln!("Starting daemon...");
unsafe {
Command::new(&exe)
.arg("daemon")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.pre_exec(|| {
nix::unistd::setsid()
.map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;
Ok(())
})
.spawn()
.with_context(|| format!("failed to start daemon via {:?}", exe))?;
}
Ok(())
}
pub async fn send(&mut self, request: Request) -> Result<Response> {
let mut json = serde_json::to_string(&request)?;
json.push('\n');
self.writer.write_all(json.as_bytes()).await.map_err(|e| {
daemon_error(anyhow::Error::new(e).context("lost connection to daemon"))
})?;
loop {
match self.next_message().await? {
ServerMessage::Response(resp) => return Ok(resp),
ServerMessage::Event(event) => self.pending_events.push_back(event),
}
}
}
pub async fn read_message(&mut self) -> Result<ServerMessage> {
if let Some(event) = self.pending_events.pop_front() {
return Ok(ServerMessage::Event(event));
}
self.next_message().await
}
async fn next_message(&mut self) -> Result<ServerMessage> {
let n = self
.reader
.read_until(b'\n', &mut self.line)
.await
.context("lost connection to daemon")
.map_err(daemon_error)?;
if n == 0 {
return Err(script::error(
ErrorKind::Daemon,
"lost connection to daemon",
));
}
let line = std::mem::take(&mut self.line);
serde_json::from_slice(line.trim_ascii())
.context("failed to parse daemon message")
.map_err(daemon_error)
}
pub async fn subscribe(&mut self) -> Result<()> {
match self.send(Request::Subscribe).await? {
Response::Ok => Ok(()),
other => Err(unexpected("Subscribe", other)),
}
}
pub async fn list_agents(&mut self) -> Result<Vec<AgentInfo>> {
match self.send(Request::List).await? {
Response::Agents { agents } => Ok(agents),
other => Err(unexpected("List", other)),
}
}
pub async fn list_tasks(&mut self) -> Result<Vec<TaskInfo>> {
match self.send(Request::ListTasks).await? {
Response::Tasks { tasks } => Ok(tasks),
other => Err(unexpected("ListTasks", other)),
}
}
pub async fn get_task(&mut self, name: &str) -> Result<(TaskInfo, Vec<RunInfo>)> {
match self.send(Request::GetTask { name: name.into() }).await? {
Response::Task { task, runs } => Ok((task, runs)),
Response::Error { message } => Err(script::error(ErrorKind::NotFound, message)),
other => Err(unexpected("GetTask", other)),
}
}
pub async fn resolve_member(
&mut self,
target: Option<&str>,
dir: Option<&Path>,
) -> Result<(TaskInfo, MemberInfo, Vec<RunInfo>)> {
let request = Request::ResolveMember {
target: target.map(str::to_string),
dir: dir.map(Path::to_path_buf),
from: std::env::var("TAM_AGENT_ID")
.ok()
.filter(|id| !id.is_empty()),
};
match self.send(request).await? {
Response::Member { task, member, runs } => Ok((task, *member, runs)),
Response::Error { message } => Err(script::error(ErrorKind::NotFound, message)),
other => Err(unexpected("ResolveMember", other)),
}
}
pub async fn run_agent(
&mut self,
member: &str,
session: SessionChoice,
prompt: Option<String>,
args: Vec<String>,
) -> Result<(String, Option<String>)> {
let request = Request::RunAgent {
member: member.into(),
provider: None,
session,
args,
prompt,
env: crate::repos::agent_env(),
wrapper: crate::config::load_config()
.context("cannot read tam's config")?
.wrapper,
};
match self.send(request).await? {
Response::Running { id, resumed } => Ok((id, resumed)),
Response::Error { message } => anyhow::bail!("{message}"),
other => Err(unexpected("RunAgent", other)),
}
}
pub async fn drop_task(
&mut self,
name: &str,
force: bool,
delete_branch: bool,
) -> Result<DropOutcome> {
let request = Request::DropTask {
name: name.into(),
force,
delete_branch,
};
match self.send(request).await? {
Response::Dropped { warnings } => Ok(DropOutcome::Dropped { warnings }),
Response::DropRefused { worktrees } => Ok(DropOutcome::Refused { worktrees }),
other => Err(unexpected("DropTask", other)),
}
}
pub async fn reconcile(&mut self) -> Result<Vec<TaskInfo>> {
match self.send(Request::Reconcile).await? {
Response::Tasks { tasks } => Ok(tasks),
other => Err(unexpected("Reconcile", other)),
}
}
pub async fn repair_member(&mut self, member: &str) -> Result<(TaskInfo, MemberInfo)> {
let request = Request::RepairMember {
member: member.into(),
env: crate::repos::git_env(),
};
match self.send(request).await? {
Response::Member { task, member, .. } => Ok((task, *member)),
other => Err(unexpected("RepairMember", other)),
}
}
pub async fn adopt(
&mut self,
dir: &Path,
name: Option<&str>,
join: Option<&str>,
) -> Result<TaskInfo> {
let request = Request::AdoptWorktree {
dir: dir.to_path_buf(),
name: name.map(str::to_string),
join: join.map(str::to_string),
};
match self.send(request).await? {
Response::Task { task, .. } => Ok(task),
other => Err(unexpected("AdoptWorktree", other)),
}
}
pub async fn create_members(
&mut self,
task: &str,
members: Vec<NewMember>,
source: Option<&str>,
join: bool,
) -> Result<TaskInfo> {
let request = Request::CreateMembers {
task: task.into(),
members,
source: source.map(str::to_string),
join,
env: crate::repos::git_env(),
};
match self.send(request).await? {
Response::Task { task, .. } => Ok(task),
other => Err(unexpected("CreateMembers", other)),
}
}
pub async fn screen(&mut self, id: &str, from: Option<u64>) -> Result<ScreenInfo> {
let request = Request::Screen {
id: id.into(),
from,
};
match self.send(request).await? {
Response::Screen { screen } => Ok(screen),
other => Err(unexpected("Screen", other)),
}
}
pub async fn watch_screen(&mut self, id: Option<&str>, viewing: bool) -> Result<()> {
let request = Request::WatchScreen {
id: id.map(str::to_string),
viewing,
};
match self.send(request).await? {
Response::Ok => Ok(()),
other => Err(unexpected("WatchScreen", other)),
}
}
pub async fn attach(self, id: &str, label: &str) -> Result<()> {
anyhow::ensure!(
std::io::stdin().is_terminal(),
"cannot attach: stdin is not a terminal"
);
let original = enter_raw_mode()?;
let (cols, rows) = terminal_size();
let result = self.attach_relay(id, cols, rows, terminal_size).await;
restore_terminal(&original);
reset_terminal_state();
eprintln!("[detached from {}]", label);
result
}
pub async fn attach_relay(
mut self,
id: &str,
cols: u16,
rows: u16,
on_resize: impl FnMut() -> (u16, u16),
) -> Result<()> {
let tty = open_tty_nonblocking()?;
let winch =
signal(SignalKind::window_change()).context("failed to listen for terminal resize")?;
let resp = self
.send(Request::Attach {
id: id.into(),
cols,
rows,
})
.await?;
match resp {
Response::Attached => {}
Response::Error { message } => {
anyhow::bail!("{}", message);
}
other => {
anyhow::bail!("unexpected response: {:?}", other);
}
}
self.raw_relay(id, &tty, winch, on_resize).await
}
async fn raw_relay(
&mut self,
id: &str,
tty: &AsyncFd<std::fs::File>,
mut winch: tokio::signal::unix::Signal,
mut on_resize: impl FnMut() -> (u16, u16),
) -> Result<()> {
let mut stdout = tokio::io::stdout();
let mut socket_buf = [0u8; 4096];
let mut filter = KbdProtoFilter::new();
let mut filtered = Vec::with_capacity(4096);
let mut tty_buf = [0u8; 4096];
let mut resize_at: Option<Instant> = None;
loop {
tokio::select! {
biased;
_ = winch.recv() => {
resize_at.get_or_insert_with(|| Instant::now() + RESIZE_THROTTLE);
}
_ = sleep_until(resize_at.unwrap_or_else(Instant::now)), if resize_at.is_some() => {
resize_at = None;
let (cols, rows) = on_resize();
send_resize(id, cols, rows).await;
}
result = read_tty(tty, &mut tty_buf) => {
let data = match result.context("failed to read from terminal")? {
0 => break,
n => &tty_buf[..n],
};
if let Some(pos) = data.iter().position(|&b| b == DETACH_KEY) {
if pos > 0 {
self.writer.write_all(&data[..pos]).await?;
}
break;
}
self.writer.write_all(data).await?;
}
result = self.reader.read(&mut socket_buf) => {
match result {
Ok(0) => break,
Ok(n) => {
filtered.clear();
filter.filter(&socket_buf[..n], &mut filtered);
stdout.write_all(&filtered).await?;
stdout.flush().await?;
}
Err(_) => break,
}
}
}
}
Ok(())
}
pub async fn outcomes(&mut self, members: Vec<String>) -> Result<Vec<MemberOutcome>> {
match self.send(Request::GetOutcomes { members }).await? {
Response::Outcomes { members, .. } => Ok(members),
other => Err(unexpected("GetOutcomes", other)),
}
}
pub async fn wait_agents(
&mut self,
members: Vec<String>,
until: Vec<MemberState>,
timeout_secs: Option<u64>,
) -> Result<(Vec<MemberOutcome>, bool)> {
let request = Request::WaitAgents {
members,
until,
timeout_secs,
};
match self.send(request).await? {
Response::Outcomes { members, timed_out } => Ok((members, timed_out)),
other => Err(unexpected("WaitAgents", other)),
}
}
}
pub struct Moved {
pub tasks: Vec<TaskInfo>,
pub moved: Vec<String>,
pub previous: std::collections::BTreeMap<String, String>,
pub notified: Vec<String>,
}
impl Client {
pub async fn merge_tasks(&mut self, into: &str, from: &[String]) -> Result<Moved> {
let request = Request::MergeTasks {
into: into.into(),
from: from.to_vec(),
};
moved("MergeTasks", self.send(request).await?)
}
pub async fn split_member(&mut self, member: &str, name: Option<&str>) -> Result<Moved> {
let request = Request::SplitMember {
member: member.into(),
name: name.map(str::to_string),
};
moved("SplitMember", self.send(request).await?)
}
}
fn moved(request: &str, response: Response) -> Result<Moved> {
match response {
Response::Moved {
tasks,
moved,
previous,
notified,
} => Ok(Moved {
tasks,
moved,
previous,
notified,
}),
other => Err(unexpected(request, other)),
}
}
pub enum Target {
Member(TaskInfo, MemberInfo),
Chat(ChatInfo, Vec<RunInfo>),
Shell(ShellInfo),
}
impl Client {
pub async fn resolve_target(&mut self, target: &str) -> Result<Target> {
let request = Request::ResolveTarget {
target: target.into(),
from: std::env::var("TAM_AGENT_ID")
.ok()
.filter(|id| !id.is_empty()),
};
match self.send(request).await? {
Response::Member { task, member, .. } => Ok(Target::Member(task, *member)),
Response::Chat { chat, runs } => Ok(Target::Chat(*chat, runs)),
Response::Shell { shell } => Ok(Target::Shell(*shell)),
Response::Error { message }
if tam_daemon::shell::is_shell_id(target) && !is_unknown_request(&message) =>
{
Err(script::error(
ErrorKind::NotFound,
format!(
"no open shell '{target}': it exited or was closed (tam ps lists the \
open shells)"
),
))
}
other => Err(not_found("ResolveTarget", other)),
}
}
pub async fn list_chats(&mut self) -> Result<Vec<ChatInfo>> {
match self.send(Request::ListChats).await? {
Response::Chats { chats } => Ok(chats),
other => Err(unexpected("ListChats", other)),
}
}
pub async fn get_chat(&mut self, chat: &str) -> Result<(ChatInfo, Vec<RunInfo>)> {
let request = Request::GetChat { chat: chat.into() };
chat_reply("GetChat", self.send(request).await?).map_err(|e| match e {
ChatError::Refused(message) => script::error(ErrorKind::NotFound, message),
ChatError::Other(e) => e,
})
}
pub async fn create_chat(
&mut self,
dir: &Path,
name: Option<&str>,
session: Option<&str>,
) -> Result<ChatInfo> {
let request = Request::CreateChat {
dir: dir.to_path_buf(),
name: name.map(str::to_string),
session: session.map(str::to_string),
};
Ok(chat_reply("CreateChat", self.send(request).await?)?.0)
}
pub async fn rename_chat(&mut self, chat: &str, name: Option<&str>) -> Result<ChatInfo> {
let request = Request::RenameChat {
chat: chat.into(),
name: name.map(str::to_string),
};
Ok(chat_reply("RenameChat", self.send(request).await?)?.0)
}
pub async fn keep_chat(&mut self, chat: &str, keep: bool) -> Result<ChatInfo> {
let request = Request::KeepChat {
chat: chat.into(),
keep,
};
Ok(chat_reply("KeepChat", self.send(request).await?)?.0)
}
pub async fn chat_history(&mut self, dir: &Path) -> Result<Vec<SessionInfo>> {
let request = Request::ChatHistory {
dir: dir.to_path_buf(),
};
match self.send(request).await? {
Response::Sessions { sessions } => Ok(sessions),
Response::Error { message } => anyhow::bail!("{message}"),
other => Err(unexpected("ChatHistory", other)),
}
}
pub async fn close_chat(&mut self, chat: &str) -> Result<(ChatInfo, Vec<RunInfo>)> {
let request = Request::CloseChat { chat: chat.into() };
Ok(chat_reply("CloseChat", self.send(request).await?)?)
}
}
impl Client {
pub async fn open_shell(&mut self, on: ShellPlace) -> Result<ShellInfo> {
let request = Request::OpenShell {
on,
env: crate::repos::agent_env(),
wrapper: crate::config::load_config()
.context("cannot read tam's config")?
.wrapper,
};
match self.send(request).await? {
Response::Shell { shell } => Ok(*shell),
other => Err(unexpected("OpenShell", other)),
}
}
pub async fn list_shells(&mut self) -> Result<Vec<ShellInfo>> {
match self.send(Request::ListShells).await? {
Response::Shells { shells } => Ok(shells),
other => Err(unexpected("ListShells", other)),
}
}
pub async fn close_shell(&mut self, id: &str) -> Result<ShellInfo> {
let request = Request::CloseShell { id: id.into() };
match self.send(request).await? {
Response::Shell { shell } => Ok(*shell),
other => Err(unexpected("CloseShell", other)),
}
}
}
enum ChatError {
Refused(String),
Other(anyhow::Error),
}
impl From<ChatError> for anyhow::Error {
fn from(e: ChatError) -> Self {
match e {
ChatError::Refused(message) => anyhow::anyhow!("{message}"),
ChatError::Other(e) => e,
}
}
}
fn chat_reply(request: &str, response: Response) -> Result<(ChatInfo, Vec<RunInfo>), ChatError> {
match response {
Response::Chat { chat, runs } => Ok((*chat, runs)),
Response::Error { message } if !is_unknown_request(&message) => {
Err(ChatError::Refused(message))
}
other => Err(ChatError::Other(unexpected(request, other))),
}
}
fn not_found(request: &str, response: Response) -> anyhow::Error {
match response {
Response::Error { message } if !is_unknown_request(&message) => {
script::error(ErrorKind::NotFound, message)
}
other => unexpected(request, other),
}
}
fn is_unknown_request(message: &str) -> bool {
message.starts_with("invalid request: unknown variant")
}
fn unexpected(request: &str, response: Response) -> anyhow::Error {
match response {
Response::Error { message } if is_unknown_request(&message) => {
anyhow::anyhow!(
"{message}\nThe running tam daemon is older than this tam: restart it \
(tam shutdown, which stops its agents)"
)
}
Response::Error { message } => anyhow::anyhow!("{message}"),
other => script::error(
ErrorKind::Daemon,
format!("unexpected response to {request}: {other:?}"),
),
}
}
fn daemon_error(err: anyhow::Error) -> anyhow::Error {
script::error(ErrorKind::Daemon, format!("{err:#}"))
}
async fn send_resize(id: &str, cols: u16, rows: u16) {
let request = async {
if let Ok(Some(mut control)) = Client::try_connect().await {
let _ = control
.send(Request::Resize {
id: id.to_string(),
cols,
rows,
})
.await;
}
};
let _ = tokio::time::timeout(RESIZE_TIMEOUT, request).await;
}
struct KbdProtoFilter {
pending: Vec<u8>,
state: FilterState,
}
#[derive(Clone, Copy)]
enum FilterState {
Normal,
Esc,
Csi,
KbdProto { marker: u8 },
}
impl KbdProtoFilter {
fn new() -> Self {
Self {
pending: Vec::new(),
state: FilterState::Normal,
}
}
fn filter(&mut self, input: &[u8], out: &mut Vec<u8>) {
for &b in input {
match self.state {
FilterState::Normal => {
if b == 0x1b {
self.state = FilterState::Esc;
self.pending.push(b);
} else {
out.push(b);
}
}
FilterState::Esc => {
if b == b'[' {
self.pending.push(b);
self.state = FilterState::Csi;
} else {
self.emit_pending_and_reprocess(b, out);
}
}
FilterState::Csi => {
if b == b'>' || b == b'<' || b == b'=' {
self.pending.push(b);
self.state = FilterState::KbdProto { marker: b };
} else {
self.emit_pending_and_reprocess(b, out);
}
}
FilterState::KbdProto { marker } => {
if self.is_kbd_final_byte(b, marker) {
self.pending.clear();
self.state = FilterState::Normal;
} else if b.is_ascii_digit() || b == b';' {
self.pending.push(b);
} else {
self.emit_pending_and_reprocess(b, out);
}
}
}
}
}
fn is_kbd_final_byte(&self, b: u8, marker: u8) -> bool {
match b {
b'u' => true,
b'm' if marker == b'>' => true,
_ => false,
}
}
fn emit_pending_and_reprocess(&mut self, b: u8, out: &mut Vec<u8>) {
out.extend_from_slice(&self.pending);
self.pending.clear();
if b == 0x1b {
self.pending.push(b);
self.state = FilterState::Esc;
} else {
out.push(b);
self.state = FilterState::Normal;
}
}
}
fn open_tty_nonblocking() -> Result<AsyncFd<std::fs::File>> {
use std::os::unix::fs::OpenOptionsExt;
let open = |path: &std::path::Path| {
std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY)
.open(path)
};
let file = nix::unistd::ttyname(std::io::stdin())
.map_err(std::io::Error::from)
.and_then(|path| open(&path))
.or_else(|_| open(std::path::Path::new("/dev/tty")))
.context("failed to open the terminal")?;
AsyncFd::new(file).context("failed to register the terminal with the reactor")
}
async fn read_tty(tty: &AsyncFd<std::fs::File>, buf: &mut [u8]) -> std::io::Result<usize> {
use std::io::Read;
tty.async_io(Interest::READABLE, |mut file| file.read(buf))
.await
}
pub(crate) fn terminal_size() -> (u16, u16) {
let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
let ret = unsafe {
libc::ioctl(
libc::STDOUT_FILENO,
libc::TIOCGWINSZ as libc::c_ulong,
&mut ws,
)
};
if ret == 0 && ws.ws_col > 0 && ws.ws_row > 0 {
(ws.ws_col, ws.ws_row)
} else {
(80, 24)
}
}
fn enter_raw_mode() -> Result<Termios> {
let stdin_fd = std::io::stdin();
let original = tcgetattr(&stdin_fd).context("failed to get terminal attributes")?;
let mut raw = original.clone();
cfmakeraw(&mut raw);
tcsetattr(&stdin_fd, SetArg::TCSAFLUSH, &raw).context("failed to set raw mode")?;
Ok(original)
}
fn restore_terminal(original: &Termios) {
let stdin_fd = std::io::stdin();
let _ = tcsetattr(&stdin_fd, SetArg::TCSAFLUSH, original);
}
pub(crate) fn reset_terminal_state() {
use std::io::Write;
let mut out = std::io::stdout();
let _ = out.write_all(
concat!(
"\x1b[<u",
"\x1b[>4m",
"\x1b[?1049l",
"\x1b[?1000l",
"\x1b[?1002l",
"\x1b[?1003l",
"\x1b[?1006l",
"\x1b[?2004l",
"\x1b[?1l",
"\x1b[?7h",
"\x1b[r",
"\x1b[m",
"\x1b[?25h",
"\x1b[H",
"\x1b[2J",
)
.as_bytes(),
);
let _ = out.flush();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_request_the_daemon_does_not_know_says_to_restart_it() {
let old = Response::Error {
message: "invalid request: unknown variant `create_members`, expected one of `spawn`"
.into(),
};
let err = unexpected("CreateMembers", old).to_string();
assert!(err.contains("older than this tam"), "{err}");
let other = Response::Error {
message: "task 'x' not found".into(),
};
assert_eq!(
unexpected("GetTask", other).to_string(),
"task 'x' not found"
);
}
fn filtered(input: &[u8]) -> Vec<u8> {
let mut f = KbdProtoFilter::new();
let mut out = Vec::new();
f.filter(input, &mut out);
out
}
#[test]
fn filter_passes_plain_text() {
assert_eq!(filtered(b"hello world"), b"hello world");
}
#[test]
fn filter_passes_normal_csi() {
assert_eq!(filtered(b"\x1b[1;1H"), b"\x1b[1;1H");
assert_eq!(filtered(b"\x1b[31m"), b"\x1b[31m");
}
#[test]
fn filter_strips_kbd_push() {
assert_eq!(filtered(b"\x1b[>1u"), b"");
assert_eq!(filtered(b"\x1b[>1;1u"), b"");
}
#[test]
fn filter_strips_kbd_pop() {
assert_eq!(filtered(b"\x1b[<u"), b"");
}
#[test]
fn filter_strips_modify_other_keys() {
assert_eq!(filtered(b"\x1b[>4;2m"), b"");
assert_eq!(filtered(b"\x1b[>4m"), b"");
}
#[test]
fn filter_preserves_surrounding_data() {
assert_eq!(filtered(b"before\x1b[>1uafter"), b"beforeafter");
}
#[test]
fn filter_handles_split_across_calls() {
let mut f = KbdProtoFilter::new();
let mut out = Vec::new();
f.filter(b"\x1b[>", &mut out);
f.filter(b"1u", &mut out);
assert_eq!(out, b"");
}
#[test]
fn filter_emits_incomplete_on_non_match() {
assert_eq!(filtered(b"\x1b[>1c"), b"\x1b[>1c");
}
}