From 7b842ac508f2787a082857719fd9a60b9e021809 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn Date: Thu, 26 Nov 2026 10:08:58 +0900 Subject: [PATCH 1/8] WIP: interactive input for services: run -i, send, attach, signal (#68) FIFO-based stdin for services started with --interactive/-i (Unix): the service reads the FIFO read-only and inherits an extra write end, so it never sees EOF and no taba process stays behind. taba send, taba attach and taba signal follow the stop ownership rules (owner, exclusive borrow, or --force --reason). ps --json reports "input". taba ui: i attaches. Design under review on #68 (PTY + holder); not ready to merge. Co-Authored-By: Claude Opus 5.5 --- src/borrows.rs | 2 +- src/claims.rs | 3 + src/error.rs | 2 +- src/gc.rs | 1 + src/input.rs | 609 +++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 173 +++++++++++++- src/state.rs | 25 ++ src/ui/app.rs | 57 +++++ src/ui/mod.rs | 28 ++- src/ui/view.rs | 5 +- tests/input.rs | 271 ++++++++++++++++++++++ 11 files changed, 1167 insertions(+), 9 deletions(-) create mode 100644 src/input.rs create mode 100644 tests/input.rs diff --git a/src/borrows.rs b/src/borrows.rs index c15342b..0dad14a 100644 --- a/src/borrows.rs +++ b/src/borrows.rs @@ -145,7 +145,7 @@ pub fn borrowed(svc: &Service, bs: &[Borrow]) -> TabaError { format!("taba move {} --to {}", svc.id(), scopes[0]), )) } -fn locked(svc: &Service, b: &Borrow) -> TabaError { +pub(crate) fn locked(svc: &Service, b: &Borrow) -> TabaError { TabaError::new("E_LOCKED",format!("{} is locked by {}",svc.id(),b.scope)).details(json!({"service":svc.id(),"scope":b.scope,"holder":b.holder.agent,"expires_at":b.expires_at})).next(Next::just("retry later or use --wait-lock SECS")) } pub fn authorise( diff --git a/src/claims.rs b/src/claims.rs index 5f867dc..e953499 100644 --- a/src/claims.rs +++ b/src/claims.rs @@ -171,6 +171,9 @@ pub fn transfer(store: &Store, svc: &Service, target: &str, how: &str) -> Result let mut moved = svc.clone(); moved.scope = target.into(); moved.log_path = store.log_path(target, &svc.name); + if moved.input.is_some() { + moved.input = Some(store.input_path(target, &svc.name)); + } let event = json!({"at":rfc3339(now_secs()), "event":"service_moved", "how":how, "from":svc.id(), "to":moved.id(), "instance":svc.instance()}); moved.moves.push(event.clone()); store.move_service(&svc.scope, &moved)?; diff --git a/src/error.rs b/src/error.rs index 5ca562a..d69c22d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -161,7 +161,7 @@ pub fn exit_code(code: &str) -> u8 { match code { "E_USAGE" | "E_NO_SCOPE" | "E_INVALID_IDENT" | "E_FORCE_NEEDS_REASON" => 2, "E_NOT_OWNER" | "E_SCOPE_HELD" | "E_LEASE_LIVE" | "E_LOCKED" | "E_BUSY" | "E_BORROWED" - | "E_NO_CLAIMANT" | "E_CONFLICT" | "E_STILL_RUNNING" => 3, + | "E_NO_CLAIMANT" | "E_CONFLICT" | "E_STILL_RUNNING" | "E_NO_INPUT" | "E_NOT_RUNNING" => 3, "E_PORT_IN_USE" | "E_PORT_CLAIMED" | "E_NO_FREE_PORT" | "E_START_FAILED" | "E_NOT_READY" => 4, "E_NOT_FOUND" | "E_DANGLING" => 5, diff --git a/src/gc.rs b/src/gc.rs index ba47d6f..d71a557 100644 --- a/src/gc.rs +++ b/src/gc.rs @@ -339,6 +339,7 @@ mod tests { service_expires_at: None, moves: Vec::new(), stop_requested_at: None, + input: None, }; store.put(&svc).unwrap(); svc diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 0000000..1ed858b --- /dev/null +++ b/src/input.rs @@ -0,0 +1,609 @@ +//! Interactive input for services (#68): `run --interactive`, `send`, `attach` +//! and `signal`. +//! +//! A service started with `run --interactive` gets a FIFO in +//! `$TABA_HOME/inputs//.fifo` as its stdin, opened read-only. +//! The service also inherits a write end of the same FIFO as an extra file +//! descriptor, so it never reads EOF while nobody is sending, and no taba +//! process stays behind. (Stdin itself is not opened read-write: the Dart VM, +//! and so `flutter run`, receives nothing from a read-write FIFO on macOS.) +//! `send` and `attach` open the FIFO for writing, write and close it. +//! +//! Writing to a service's stdin, or signalling it, mutates someone else's +//! process, so the same rules as `stop` apply: the owning scope (under its +//! lease) or the holder of an exclusive borrow; anyone else needs +//! `--force --reason`, which is recorded in events.jsonl. While another scope +//! holds an exclusive borrow, the owner is refused with `E_LOCKED`. +//! +//! Windows (named pipes) is not supported yet: these commands fail there +//! with `E_UNSUPPORTED`. + +use crate::error::{Next, Output, Result, TabaError}; +use crate::scope::{self, Caller}; +use crate::state::{Service, Store}; +use crate::{borrows, config, lease}; +use serde_json::json; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +/// How long a write waits for a service that does not read its stdin. +const WRITE_TIMEOUT: Duration = Duration::from_secs(5); +/// The byte that ends `attach` (Ctrl+]). +const DETACH: u8 = 0x1d; + +pub fn unsupported(what: &str) -> TabaError { + TabaError::new( + "E_UNSUPPORTED", + format!("{what} is not supported on this platform yet (Unix only)"), + ) + .details(json!({ "feature": what, "platform": std::env::consts::OS })) +} + +/// The input FIFO of a service being started: `stdin` for the child, and +/// `keep`, a write end without close-on-exec that the child inherits so its +/// stdin never reaches EOF. taba drops both after the spawn. +pub struct Fifo { + pub path: PathBuf, + pub stdin: std::fs::File, + #[cfg(unix)] + pub _keep: std::os::fd::OwnedFd, +} + +/// Creates the input FIFO of `scope/name` (replacing a stale one) and opens +/// both ends for the child. +#[cfg(unix)] +pub fn create(store: &Store, scope: &str, name: &str) -> Result { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::OpenOptionsExt; + let path = store.input_path(scope, name); + let fail = |what: &str, e: std::io::Error| { + TabaError::state(format!("cannot {what} input FIFO {}: {e}", path.display())) + }; + crate::state::create_private_dir_all(path.parent().expect("input has parent"))?; + match std::fs::remove_file(&path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()), + _ => {} + } + let c = std::ffi::CString::new(path.as_os_str().as_bytes()) + .map_err(|_| TabaError::state("input path contains a NUL byte"))?; + if unsafe { libc::mkfifo(c.as_ptr(), 0o600) } != 0 { + return Err(fail("create", std::io::Error::last_os_error())); + } + // Non-blocking, as no writer exists yet; cleared below. + let stdin = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(&path) + .map_err(|e| fail("open", e))?; + // Without O_CLOEXEC, so the child inherits it. taba is single-threaded + // here and spawns nothing else before dropping it. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_WRONLY) }; + if fd < 0 { + return Err(fail("open", std::io::Error::last_os_error())); + } + let keep = unsafe { OwnedFd::from_raw_fd(fd) }; + let raw = stdin.as_raw_fd(); + let flags = unsafe { libc::fcntl(raw, libc::F_GETFL) }; + if flags < 0 || unsafe { libc::fcntl(raw, libc::F_SETFL, flags & !libc::O_NONBLOCK) } < 0 { + return Err(fail("set up", std::io::Error::last_os_error())); + } + Ok(Fifo { + path, + stdin, + _keep: keep, + }) +} + +#[cfg(windows)] +pub fn create(_store: &Store, _scope: &str, _name: &str) -> Result { + Err(unsupported("run --interactive").next(Next::just( + "start it without --interactive; see https://github.com/Buchi-dev-dzn/taba/issues/68", + ))) +} + +/// Writes `bytes` to the service's input FIFO without blocking forever on a +/// service that does not read. +#[cfg(unix)] +pub fn write(svc: &Service, path: &Path, bytes: &[u8]) -> Result<()> { + use std::io::{ErrorKind, Write}; + use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; + let is_fifo = path + .symlink_metadata() + .is_ok_and(|m| m.file_type().is_fifo()); + if !is_fifo { + return Err(no_input(svc).details(json!({ "service": svc.id(), "path": path }))); + } + let mut f = std::fs::OpenOptions::new() + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(path) + .map_err(|e| match e.raw_os_error() { + // No reader: the service (and every process holding its stdin) is gone. + Some(libc::ENXIO) => not_running(svc), + _ => TabaError::state(format!("cannot open {}: {e}", path.display())), + })?; + let deadline = std::time::Instant::now() + WRITE_TIMEOUT; + let mut rest = bytes; + while !rest.is_empty() { + match f.write(rest) { + Ok(n) => rest = &rest[n..], + Err(e) if e.kind() == ErrorKind::WouldBlock => { + if std::time::Instant::now() >= deadline { + return Err(TabaError::new( + "E_INPUT_BLOCKED", + format!( + "{} is not reading its input; {} of {} bytes were not written", + svc.id(), + rest.len(), + bytes.len() + ), + ) + .details(json!({ "service": svc.id(), "unwritten": rest.len() })) + .next(Next::run( + "check the service", + format!("taba logs {}", svc.id()), + ))); + } + std::thread::sleep(Duration::from_millis(20)); + } + Err(e) if e.kind() == ErrorKind::Interrupted => {} + Err(e) if e.raw_os_error() == Some(libc::EPIPE) => return Err(not_running(svc)), + Err(e) => return Err(TabaError::state(format!("cannot write input: {e}"))), + } + } + Ok(()) +} + +#[cfg(windows)] +pub fn write(_svc: &Service, _path: &Path, _bytes: &[u8]) -> Result<()> { + Err(unsupported("service input")) +} + +fn no_input(svc: &Service) -> TabaError { + TabaError::new( + "E_NO_INPUT", + format!( + "{} was not started with --interactive, so it has no stdin to write to", + svc.id() + ), + ) + .details(json!({ "service": svc.id() })) + .next(Next::run( + "restart it with --interactive (stop it first)", + format!("taba stop {}", svc.id()), + )) +} + +fn not_running(svc: &Service) -> TabaError { + TabaError::new("E_NOT_RUNNING", format!("{} is not running", svc.id())) + .details(json!({ "service": svc.id(), "instance": svc.instance() })) + .next(Next::run("read its log", format!("taba logs {}", svc.id()))) +} + +/// The service `target` names, if `caller` may write to or signal it (the +/// `stop` rules, see the module docs). Records a `--force` override. +pub(crate) fn authorise( + store: &Store, + caller: &Caller, + target: &str, + verb: &str, + force_reason: Option<&str>, + needs_input: bool, +) -> Result { + let (scope, name) = crate::resolve_target(target, caller)?; + let _lock = store.lock()?; + let svc = store + .get(&scope, &name)? + .ok_or_else(|| crate::not_found(&scope, &name))?; + let owner = caller.scope.as_deref() == Some(svc.scope.as_str()); + if owner && force_reason.is_none() { + let cfg = config::Config::load(store.root())?; + lease::touch(store, &cfg, caller, &scope, lease::Access::Mutate, None)?; + } + let live = borrows::live(store, &svc)?; + let exclusive = live.iter().find(|b| b.exclusive); + let holds_exclusive = exclusive.is_some_and(|b| b.owned(caller)); + if force_reason.is_none() { + if !owner && !holds_exclusive { + return Err(crate::not_owner(caller, &svc, verb)); + } + if let Some(b) = exclusive.filter(|_| !holds_exclusive) { + return Err(borrows::locked(&svc, b)); + } + } + if let Some(op) = store.live_op(&scope, &name)? { + return Err(crate::busy(&svc.id(), &op)); + } + if !svc.is_running() { + return Err(not_running(&svc)); + } + if needs_input && svc.input.is_none() { + return Err(no_input(&svc)); + } + if let Some(reason) = force_reason { + let overrode: &[&str] = if owner || holds_exclusive { + &[] + } else { + &["E_NOT_OWNER"] + }; + crate::record_force( + store, + &format!("force_{verb}"), + caller, + &svc, + reason, + overrode, + )?; + } + Ok(svc) +} + +/// The bytes of one `--key`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Key(pub Vec); + +/// The bytes `--key` names: one character, or `enter`, `esc`, `tab`, +/// `space`, `backspace` or `ctrl-X`. +pub fn parse_key(s: &str) -> std::result::Result { + key_bytes(s).map(Key) +} + +fn key_bytes(s: &str) -> std::result::Result, String> { + let named = match s.to_ascii_lowercase().as_str() { + "enter" | "return" => Some(b"\n".to_vec()), + "esc" | "escape" => Some(vec![0x1b]), + "tab" => Some(b"\t".to_vec()), + "space" => Some(b" ".to_vec()), + "backspace" => Some(vec![0x7f]), + _ => None, + }; + if let Some(b) = named { + return Ok(b); + } + let lower = s.to_ascii_lowercase(); + if let Some(c) = lower.strip_prefix("ctrl-").or(lower.strip_prefix("ctrl+")) + && let [c @ b'a'..=b'z'] = c.as_bytes() + { + return Ok(vec![c - b'a' + 1]); + } + let mut chars = s.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => Ok(c.to_string().into_bytes()), + _ => Err(format!( + "`{s}` is not a key: use one character (r, R, q, ...), enter, esc, tab, space, \ + backspace or ctrl-X" + )), + } +} + +pub struct SendArgs { + pub target: String, + pub text: Option, + pub key: Option, + pub no_newline: bool, + pub scope: Option, + pub agent: Option, + pub force: bool, + pub reason: Option, +} + +pub fn cmd_send(a: SendArgs) -> Result { + let reason = crate::check_force(a.force, a.reason)?; + let bytes = match (a.text, a.key) { + (Some(t), None) if a.no_newline => t.into_bytes(), + (Some(t), None) => format!("{t}\n").into_bytes(), + (None, Some(Key(k))) => k, + _ => return Err(TabaError::usage("give TEXT or --key KEY")), + }; + let caller = scope::resolve(a.scope, a.agent)?; + let store = Store::open()?; + let svc = authorise(&store, &caller, &a.target, "send", reason.as_deref(), true)?; + let path = svc.input.clone().expect("checked"); + write(&svc, &path, &bytes)?; + let mut body = json!({ + "service": svc.id(), + "bytes": bytes.len(), + "instance": svc.instance(), + }); + if reason.is_some() { + body["forced"] = json!(true); + } + Ok(Output::new( + body, + format!("{}: sent {} byte(s)", svc.id(), bytes.len()), + )) +} + +/// `taba signal`: the signals `signal` accepts. +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] +pub enum Signal { + #[value(name = "USR1", alias = "usr1", alias = "SIGUSR1")] + Usr1, + #[value(name = "USR2", alias = "usr2", alias = "SIGUSR2")] + Usr2, + #[value(name = "HUP", alias = "hup", alias = "SIGHUP")] + Hup, +} + +impl Signal { + fn name(self) -> &'static str { + match self { + Signal::Usr1 => "USR1", + Signal::Usr2 => "USR2", + Signal::Hup => "HUP", + } + } +} + +pub struct SignalArgs { + pub target: String, + pub signal: Signal, + pub scope: Option, + pub agent: Option, + pub force: bool, + pub reason: Option, +} + +pub fn cmd_signal(a: SignalArgs) -> Result { + let reason = crate::check_force(a.force, a.reason)?; + if cfg!(windows) { + return Err(unsupported("taba signal")); + } + let caller = scope::resolve(a.scope, a.agent)?; + let store = Store::open()?; + let svc = authorise( + &store, + &caller, + &a.target, + "signal", + reason.as_deref(), + false, + )?; + send_signal(&svc, a.signal)?; + let mut body = json!({ + "service": svc.id(), + "signal": a.signal.name(), + "pid": svc.pid, + "instance": svc.instance(), + }); + if reason.is_some() { + body["forced"] = json!(true); + } + Ok(Output::new( + body, + format!( + "{}: sent SIG{} to pid {}", + svc.id(), + a.signal.name(), + svc.pid + ), + )) +} + +/// Signals the service's main process only: the default action of SIGUSR1 +/// and SIGUSR2 is to terminate, so the rest of the group is left alone. +#[cfg(unix)] +fn send_signal(svc: &Service, sig: Signal) -> Result<()> { + let n = match sig { + Signal::Usr1 => libc::SIGUSR1, + Signal::Usr2 => libc::SIGUSR2, + Signal::Hup => libc::SIGHUP, + }; + // Re-verify the identity right before signalling, as `stop` does. + if !crate::proc::is_alive(svc.pid, svc.start_time) { + return Err(not_running(svc)); + } + if unsafe { libc::kill(svc.pid, n) } != 0 { + let e = std::io::Error::last_os_error(); + return Err(TabaError::new( + "E_SIGNAL_FAILED", + format!("{}: cannot signal pid {}: {e}", svc.id(), svc.pid), + ) + .details(json!({ "service": svc.id(), "pid": svc.pid }))); + } + Ok(()) +} + +#[cfg(windows)] +fn send_signal(_svc: &Service, _sig: Signal) -> Result<()> { + Err(unsupported("taba signal")) +} + +pub struct AttachArgs { + pub target: String, + pub scope: Option, + pub agent: Option, + pub force: bool, + pub reason: Option, +} + +pub fn cmd_attach(a: AttachArgs) -> Result> { + let reason = crate::check_force(a.force, a.reason)?; + let caller = scope::resolve(a.scope, a.agent)?; + let store = Store::open()?; + attach(&store, &caller, &a.target, reason.as_deref())?; + Ok(None) +} + +/// Restores the terminal mode when `attach` ends, also on an error. +struct RawMode(bool); +impl Drop for RawMode { + fn drop(&mut self) { + if self.0 { + let _ = ratatui::crossterm::terminal::disable_raw_mode(); + } + } +} + +/// Shows the service's log and forwards the caller's input to its stdin +/// until Ctrl+] (on a terminal) or EOF (on a pipe), or until the service +/// exits. The service keeps running after a detach. Also used by `taba ui`. +pub(crate) fn attach( + store: &Store, + caller: &Caller, + target: &str, + force_reason: Option<&str>, +) -> Result<()> { + use std::io::{IsTerminal, Read, Seek, SeekFrom, Write}; + + let svc = authorise(store, caller, target, "attach", force_reason, true)?; + let path = svc.input.clone().expect("checked"); + let tty = std::io::stdin().is_terminal(); + let mut log = std::fs::File::open(&svc.log_path) + .map_err(|e| TabaError::state(format!("cannot open {}: {e}", svc.log_path.display())))?; + let end = log.metadata()?.len(); + let mut pos = crate::log_tail_start(&mut log, 0, end, 20)?; + + let how = if tty { + "Ctrl+] detaches" + } else { + "EOF detaches" + }; + eprintln!( + "taba: attached to {} ({how}; the service keeps running)", + svc.id() + ); + let raw = RawMode( + tty && ratatui::crossterm::terminal::enable_raw_mode() + .map_err(|e| TabaError::state(format!("cannot set up the terminal: {e}"))) + .is_ok(), + ); + + let mut stdout = std::io::stdout().lock(); + let mut chunk = Vec::new(); + // After stdin ends (a pipe), the log is shown a little longer so the + // service's answer to the last input is not cut off. + let mut linger: Option = None; + let outcome = loop { + let running = svc.is_running(); + log.seek(SeekFrom::Start(pos))?; + chunk.clear(); + log.read_to_end(&mut chunk)?; + if !chunk.is_empty() { + pos += chunk.len() as u64; + let out = if raw.0 { crlf(&chunk) } else { chunk.clone() }; + if stdout.write_all(&out).and_then(|_| stdout.flush()).is_err() { + break "closed"; + } + } else if !running { + break "exited"; + } + if linger.is_some_and(|t| t.elapsed() >= Duration::from_millis(500)) { + break "detached"; + } + if linger.is_some() { + std::thread::sleep(Duration::from_millis(50)); + continue; + } + // Waiting for input also paces the loop. No reader thread is left + // behind, so `taba ui` gets every key back after a detach. + match read_stdin(Duration::from_millis(50))? { + None => {} + Some(bytes) if bytes.is_empty() => { + linger = Some(std::time::Instant::now()); + } + Some(bytes) if raw.0 => { + let (send, stop) = match bytes.iter().position(|&b| b == DETACH) { + Some(i) => (&bytes[..i], true), + None => (&bytes[..], false), + }; + if !send.is_empty() { + write(&svc, &path, send)?; + } + if stop { + break "detached"; + } + } + Some(bytes) => write(&svc, &path, &bytes)?, + } + }; + drop(raw); + match outcome { + "exited" => eprintln!("\ntaba: {} exited", svc.id()), + "detached" => eprintln!("\ntaba: detached from {}; it keeps running", svc.id()), + _ => {} + } + Ok(()) +} + +/// Waits up to `timeout` for stdin: `None` when nothing arrived, an empty +/// buffer at EOF, else the bytes read. +#[cfg(unix)] +fn read_stdin(timeout: Duration) -> Result>> { + let mut fds = libc::pollfd { + fd: libc::STDIN_FILENO, + events: libc::POLLIN, + revents: 0, + }; + let ms = timeout.as_millis().min(i32::MAX as u128) as libc::c_int; + let n = unsafe { libc::poll(&mut fds, 1, ms) }; + if n < 0 { + let e = std::io::Error::last_os_error(); + if e.kind() == std::io::ErrorKind::Interrupted { + return Ok(None); + } + return Err(TabaError::state(format!("cannot read stdin: {e}"))); + } + if n == 0 { + return Ok(None); + } + if fds.revents & libc::POLLNVAL != 0 { + return Ok(Some(Vec::new())); + } + let mut buf = vec![0u8; 4096]; + let got = unsafe { libc::read(libc::STDIN_FILENO, buf.as_mut_ptr().cast(), buf.len()) }; + if got < 0 { + let e = std::io::Error::last_os_error(); + if matches!( + e.kind(), + std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock + ) { + return Ok(None); + } + return Err(TabaError::state(format!("cannot read stdin: {e}"))); + } + buf.truncate(got as usize); + Ok(Some(buf)) +} + +#[cfg(windows)] +fn read_stdin(_timeout: Duration) -> Result>> { + Err(unsupported("taba attach")) +} + +/// `\n` → `\r\n` for a terminal in raw mode. +fn crlf(bytes: &[u8]) -> Vec { + let mut out = Vec::with_capacity(bytes.len() + bytes.len() / 16); + let mut prev = 0u8; + for &b in bytes { + if b == b'\n' && prev != b'\r' { + out.push(b'\r'); + } + out.push(b); + prev = b; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys() { + assert_eq!(key_bytes("r").unwrap(), b"r"); + assert_eq!(key_bytes("R").unwrap(), b"R"); + assert_eq!(key_bytes("enter").unwrap(), b"\n"); + assert_eq!(key_bytes("ctrl-c").unwrap(), vec![3]); + assert_eq!(key_bytes("Ctrl+D").unwrap(), vec![4]); + assert_eq!(key_bytes("esc").unwrap(), vec![0x1b]); + assert!(key_bytes("rr").is_err()); + assert!(key_bytes("").is_err()); + } + + #[test] + fn crlf_adds_carriage_returns_once() { + assert_eq!(crlf(b"a\nb\r\nc"), b"a\r\nb\r\nc"); + } +} diff --git a/src/main.rs b/src/main.rs index cd9b17e..a927622 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod error; mod gc; mod handoff; mod hooks; +mod input; mod lease; mod listing; mod ports; @@ -77,6 +78,11 @@ enum Cmd { /// already_running re-run), independent of the lease #[arg(long, value_parser = config::parse_service_ttl_flag)] service_ttl: Option, + /// Interactive: give the service a stdin that stays open, for + /// `taba send` and `taba attach` (e.g. `r` for a Flutter hot reload; + /// Unix only) + #[arg(short = 'i', long = "interactive")] + input: bool, /// Print one JSON document (also: TABA_OUTPUT=json) #[arg(long)] json: bool, @@ -84,6 +90,78 @@ enum Cmd { #[arg(last = true, required = true, value_name = "CMD")] command: Vec, }, + /// Write a line (or one key) to the stdin of a service started with --interactive + Send { + /// SCOPE/NAME, or NAME in the caller's scope + target: String, + /// Text to write; a newline is added unless --no-newline + #[arg(required_unless_present = "key", conflicts_with = "key")] + text: Option, + /// Write one key without a newline: a character such as r, or enter, + /// esc, tab, space, backspace, ctrl-X + #[arg(long, value_parser = input::parse_key, value_name = "KEY")] + key: Option, + /// Do not add a newline after TEXT + #[arg(long, conflicts_with = "key")] + no_newline: bool, + /// The caller's scope (default: $TABA_SCOPE, else the git worktree) + #[arg(long)] + scope: Option, + /// Agent acting (default: $TABA_AGENT, else "human") + #[arg(long)] + agent: Option, + /// Write to a service of another scope (needs --reason; recorded) + #[arg(long)] + force: bool, + /// Why --force is needed (recorded in events.jsonl) + #[arg(long, requires = "force")] + reason: Option, + /// Print one JSON document (also: TABA_OUTPUT=json) + #[arg(long)] + json: bool, + }, + /// Follow a service's log and type into its stdin (--interactive services); + /// Ctrl+] detaches and the service keeps running + Attach { + /// SCOPE/NAME, or NAME in the caller's scope + target: String, + /// The caller's scope (default: $TABA_SCOPE, else the git worktree) + #[arg(long)] + scope: Option, + /// Agent acting (default: $TABA_AGENT, else "human") + #[arg(long)] + agent: Option, + /// Attach to a service of another scope (needs --reason; recorded) + #[arg(long)] + force: bool, + /// Why --force is needed (recorded in events.jsonl) + #[arg(long, requires = "force")] + reason: Option, + }, + /// Send SIGUSR1, SIGUSR2 or SIGHUP to a service's main process (Unix; + /// `flutter run` hot-reloads on USR1 and hot-restarts on USR2) + Signal { + /// SCOPE/NAME, or NAME in the caller's scope + target: String, + /// USR1, USR2 or HUP + #[arg(value_enum, ignore_case = true)] + signal: input::Signal, + /// The caller's scope (default: $TABA_SCOPE, else the git worktree) + #[arg(long)] + scope: Option, + /// Agent acting (default: $TABA_AGENT, else "human") + #[arg(long)] + agent: Option, + /// Signal a service of another scope (needs --reason; recorded) + #[arg(long)] + force: bool, + /// Why --force is needed (recorded in events.jsonl) + #[arg(long, requires = "force")] + reason: Option, + /// Print one JSON document (also: TABA_OUTPUT=json) + #[arg(long)] + json: bool, + }, /// Show the caller's scope, where it came from, and its services Whoami { /// Scope to report (default: $TABA_SCOPE, else the git worktree) @@ -505,6 +583,7 @@ fn main() -> ExitCode { ready, ttl, service_ttl, + input, json, command, } => ( @@ -518,10 +597,71 @@ fn main() -> ExitCode { ready, ttl, service_ttl, + input, command, }) .map(Some), ), + Cmd::Send { + target, + text, + key, + no_newline, + scope, + agent, + force, + reason, + json, + } => ( + json || env_json(), + input::cmd_send(input::SendArgs { + target, + text, + key, + no_newline, + scope, + agent, + force, + reason, + }) + .map(Some), + ), + Cmd::Attach { + target, + scope, + agent, + force, + reason, + } => ( + env_json(), + input::cmd_attach(input::AttachArgs { + target, + scope, + agent, + force, + reason, + }), + ), + Cmd::Signal { + target, + signal, + scope, + agent, + force, + reason, + json, + } => ( + json || env_json(), + input::cmd_signal(input::SignalArgs { + target, + signal, + scope, + agent, + force, + reason, + }) + .map(Some), + ), Cmd::Renew { scope, agent, @@ -879,6 +1019,7 @@ struct RunArgs { ready: Option, ttl: Option, service_ttl: Option, + input: bool, command: Vec, } @@ -896,6 +1037,11 @@ fn cmd_run(a: RunArgs) -> Result { )); } }; + if a.input && cfg!(windows) { + return Err(input::unsupported("run --interactive").next(Next::just( + "start it without --interactive; Windows support is tracked in the taba issues", + ))); + } if let Some(r) = &a.ready && r.needs_port() && a.port.is_none() @@ -964,6 +1110,7 @@ fn cmd_run(a: RunArgs) -> Result { if ex.template() == template.as_slice() && ex.cwd == caller.cwd && ex.port_request() == port_request + && ex.input.is_some() == a.input { let mut ex = ex.clone(); if let Some(ttl) = a.service_ttl.or(ex.service_ttl_secs) { @@ -979,17 +1126,19 @@ fn cmd_run(a: RunArgs) -> Result { return Err(TabaError::new( "E_CONFLICT", format!( - "{} is already running with a different command, directory or port \ - (command {:?}, dir {}, port {}); stop it first", + "{} is already running with a different command, directory, port or \ + --interactive (command {:?}, dir {}, port {}, input {}); stop it first", ex.id(), ex.template(), tilde(&ex.cwd), ex.port_request().unwrap_or_else(|| "-".into()), + ex.input.is_some(), ), ) .details(json!({ "service": ex.id(), "command": ex.template(), "directory": ex.cwd, "port": ex.port, "port_request": ex.port_request(), "instance": ex.instance(), + "input": ex.input.is_some(), })) .next(Next::run( "stop it, then run again", @@ -1046,12 +1195,22 @@ fn cmd_run(a: RunArgs) -> Result { let log_offset = log.metadata()?.len(); let log_err = log.try_clone()?; + let fifo = if a.input { + Some(input::create(&store, &scope, &name)?) + } else { + None + }; + let input_path = fifo.as_ref().map(|f| f.path.clone()); + let stdin = match &fifo { + Some(f) => Stdio::from(f.stdin.try_clone()?), + None => Stdio::null(), + }; let mut cmd = Command::new(proc::resolve_program(&command[0])); cmd.args(&command[1..]) .current_dir(&caller.cwd) .env("TABA_SCOPE", &scope) .env("TABA_SERVICE", &name) - .stdin(Stdio::null()) + .stdin(stdin) .stdout(Stdio::from(log)) .stderr(Stdio::from(log_err)); if let Some(p) = port { @@ -1066,7 +1225,10 @@ fn cmd_run(a: RunArgs) -> Result { }; // Detached: its own session / process group (Unix) or console and job // (Windows), so closing the launching terminal does not stop it. - let spawned = proc::spawn_detached(cmd).map_err(|e| match e { + let spawned = proc::spawn_detached(cmd); + // The child holds its own copies of the FIFO now. + drop(fifo); + let spawned = spawned.map_err(|e| match e { proc::SpawnError::Start(e) => start_failed(format!("cannot start {:?}: {e}", command[0])), proc::SpawnError::Vanished => { start_failed(format!("{id} exited immediately; see taba logs {id}")) @@ -1094,6 +1256,7 @@ fn cmd_run(a: RunArgs) -> Result { .map(|t| util::rfc3339(util::now_secs().saturating_add(t))), moves: Vec::new(), stop_requested_at: None, + input: input_path, }; store.put(&svc)?; if let Some(borrow) = &delegation { @@ -1379,6 +1542,7 @@ pub(crate) fn ps_snapshot( "claims": claims::rows(store, &queue)?, "borrows": { "shared": borrows.iter().filter(|b| !b.exclusive).count(), "exclusive": usize::from(exclusive.is_some()) }, "locked_by": exclusive.map(|b| &b.scope), + "input": s.input.is_some(), })); borrowers.push(borrows.iter().map(|b| b.scope.clone()).collect()); } @@ -2102,6 +2266,7 @@ mod stop_tests { service_expires_at: None, moves: Vec::new(), stop_requested_at: None, + input: None, }) .unwrap(); } diff --git a/src/state.rs b/src/state.rs index 5088a69..4054ddc 100644 --- a/src/state.rs +++ b/src/state.rs @@ -6,6 +6,7 @@ //! services//.json service records (v0.1 fields + optional v0.2 fields) //! logs//.log service output //! ops//.json in-flight mutation of one service (operation lock) +//! inputs//.fifo stdin of a service started with `run --interactive` (Unix) //! events.jsonl append-only audit log //! version state schema version //! lock global lock (flock / LockFileEx) @@ -140,6 +141,10 @@ pub struct Service { /// seconds); a later cleanup forces it once `stop_timeout` has passed. #[serde(default, skip_serializing_if = "Option::is_none")] pub stop_requested_at: Option, + /// `run --interactive`: the FIFO that is this instance's stdin (Unix). The + /// service holds it open for reading and writing, so it never sees EOF. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -448,6 +453,14 @@ impl Store { .join(format!("{name}.log")) } + /// The FIFO used as stdin by a service started with `run --interactive`. + pub fn input_path(&self, scope: &str, name: &str) -> PathBuf { + self.root + .join("inputs") + .join(scope) + .join(format!("{name}.fifo")) + } + fn op_path(&self, scope: &str, name: &str) -> PathBuf { self.root .join("ops") @@ -624,6 +637,16 @@ impl Store { if let Some(dir) = old_log.parent() { let _ = fs::remove_dir(dir); } + // The service keeps its open FIFO; only the name writers use moves. + let old_input = self.input_path(from_scope, &svc.name); + if old_input.symlink_metadata().is_ok() { + let new_input = self.input_path(&svc.scope, &svc.name); + create_private_dir_all(new_input.parent().expect("input has parent"))?; + fs::rename(&old_input, &new_input)?; + if let Some(dir) = old_input.parent() { + let _ = fs::remove_dir(dir); + } + } let old_claims = self.claims_path(from_scope, &svc.name); if old_claims.exists() { let new_claims = self.claims_path(&svc.scope, &svc.name); @@ -683,6 +706,7 @@ impl Store { self.record_path(scope, name), self.op_path(scope, name), self.claims_path(scope, name), + self.input_path(scope, name), ] { remove_file_and_empty_parent(&path)?; } @@ -701,6 +725,7 @@ impl Store { self.log_path(scope, name), self.op_path(scope, name), self.claims_path(scope, name), + self.input_path(scope, name), ] { remove_file_and_empty_parent(&path)?; } diff --git a/src/ui/app.rs b/src/ui/app.rs index e0b54ec..263311a 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -29,6 +29,8 @@ pub struct Row { pub pending_gc: Option, /// Whether the owning scope's lease is expired. pub lease_expired: bool, + /// Started with `run --interactive`: `i` attaches to it. + pub input: bool, } impl Row { @@ -57,6 +59,7 @@ impl Row { locked_by: json["locked_by"].as_str().map(str::to_string), pending_gc: json["pending_gc"].as_str().map(str::to_string), lease_expired: json["lease"]["state"].as_str() == Some("expired"), + input: svc.input.is_some(), scope: svc.scope, name: svc.name, }) @@ -138,6 +141,8 @@ pub enum Effect { Quit, Run(Action), OpenLog(PathBuf), + /// `taba attach SCOPE/NAME`, with the TUI suspended. + Attach(String, String), } #[derive(Debug, Clone, PartialEq, Eq)] @@ -369,6 +374,12 @@ impl App { .find(|r| r.scope == scope && r.name == name) } + /// Whether `i` (attach) applies to the selected line. + pub fn can_attach(&self) -> bool { + self.selected_row() + .is_some_and(|r| r.input && !r.is_exited()) + } + fn selected_row(&self) -> Option<&Row> { match &self.cursor { Some(Item::Service(s, n)) => self.row(s, n), @@ -609,6 +620,29 @@ impl App { } } } + KeyCode::Char('i') => { + let (text, effect) = match self.selected_row() { + Some(r) if r.input && !r.is_exited() => { + (None, Effect::Attach(r.scope.clone(), r.name.clone())) + } + Some(r) if r.input => { + (Some(format!("{} is not running", r.id())), Effect::None) + } + Some(r) => ( + Some(format!( + "{} was not started with --interactive; it takes no input", + r.id() + )), + Effect::None, + ), + None => ( + Some("select a service started with --interactive".to_string()), + Effect::None, + ), + }; + self.notice = text.map(|text| Notice { text, error: false }); + return effect; + } KeyCode::Char('l') => match self.selected_row() { Some(r) => { let path = r.log_path.clone(); @@ -697,6 +731,7 @@ pub(crate) mod tests { locked_by: None, pending_gc: None, lease_expired: false, + input: false, } } @@ -732,6 +767,28 @@ pub(crate) mod tests { Item::Scope(s.into()) } + #[test] + fn i_attaches_only_to_a_running_input_service() { + let mut app = App::new(Some("login-fix".into())); + let with_input = Row { + input: true, + ..row("login-fix", "app", "running") + }; + app.set_rows(vec![with_input, row("login-fix", "web", "running")], 0); + // On the scope line: nothing to attach to. + assert_eq!(app.handle_key(key(KeyCode::Char('i'))), Effect::None); + app.handle_key(key(KeyCode::Down)); + assert!(app.can_attach()); + assert_eq!( + app.handle_key(key(KeyCode::Char('i'))), + Effect::Attach("login-fix".into(), "app".into()) + ); + app.handle_key(key(KeyCode::Down)); + assert!(!app.can_attach()); + assert_eq!(app.handle_key(key(KeyCode::Char('i'))), Effect::None); + assert!(app.notice.as_ref().unwrap().text.contains("--interactive")); + } + #[test] fn current_scope_first_and_expanded_others_folded() { let app = sample(); diff --git a/src/ui/mod.rs b/src/ui/mod.rs index c6a68f7..52f91c4 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -5,7 +5,9 @@ //! `ps`'s lease peek, so watching changes nothing). `x` stops or removes //! through the same functions as `taba stop` / `taba rm`, as the caller //! resolved like any CLI call (`$TABA_SCOPE`, `$TABA_AGENT`, git worktree), -//! and never with `--force`. Quitting never stops anything. +//! and never with `--force`. `i` on a service started with `--interactive` +//! suspends the TUI and runs `taba attach` until Ctrl+] detaches. Quitting +//! never stops anything. //! //! Built on ratatui with the crossterm backend (macOS, Linux and Windows //! terminals). The state and key handling live in `app.rs` and drawing in @@ -135,6 +137,29 @@ fn event_loop( running = Some((handle, rx, action)); } Effect::OpenLog(path) => tail = Some(LogTail::new(path)), + Effect::Attach(scope, name) => { + // The same as `taba attach SCOPE/NAME` (never forced), + // with the TUI suspended until Ctrl+] detaches. + ratatui::restore(); + let res = crate::input::attach(store, caller, &format!("{scope}/{name}"), None); + *terminal = ratatui::try_init().map_err(io_err)?; + terminal.clear().map_err(io_err)?; + match res { + Ok(()) => { + app.notice = Some(app::Notice { + text: format!("detached from {scope}/{name}"), + error: false, + }) + } + Err(e) => { + app.notice = Some(app::Notice { + text: e.message, + error: true, + }) + } + } + next_refresh = Instant::now(); + } Effect::None => {} } } @@ -301,6 +326,7 @@ mod tests { service_expires_at: None, moves: Vec::new(), stop_requested_at: None, + input: None, }) .unwrap(); } diff --git a/src/ui/view.rs b/src/ui/view.rs index 1ec78f4..1daee09 100644 --- a/src/ui/view.rs +++ b/src/ui/view.rs @@ -492,8 +492,9 @@ fn footer(app: &App) -> Line<'static> { ]), Mode::Logs => Line::raw(" ↑↓ PgUp PgDn scroll End follow Esc back q quit"), Mode::Normal => Line::raw(format!( - " ↑↓ move ←→ / space collapse·expand x {} l logs / filter q quit", - app.x_label() + " ↑↓ move ←→ / space collapse·expand x {} l logs{} / filter q quit", + app.x_label(), + if app.can_attach() { " i input" } else { "" } )), } } diff --git a/tests/input.rs b/tests/input.rs new file mode 100644 index 0000000..e4545ee --- /dev/null +++ b/tests/input.rs @@ -0,0 +1,271 @@ +//! Interactive input (#68): `run --interactive`, `send`, `attach`, `signal`. +mod common; +use common::*; + +/// Echoes each stdin line as `got:LINE`, reports SIGUSR1 and EOF. +#[cfg(unix)] +const ECHO: &str = r#" +import signal, sys +signal.signal(signal.SIGUSR1, lambda *a: print("usr1", flush=True)) +print("ready", flush=True) +for line in sys.stdin: + print("got:" + line.rstrip("\n"), flush=True) +print("EOF", flush=True) +"#; + +/// Never reads stdin (which is /dev/null without `--interactive`); reports SIGUSR1. +#[cfg(unix)] +const SLEEPER: &str = r#" +import signal, time +signal.signal(signal.SIGUSR1, lambda *a: print("usr1", flush=True)) +print("ready", flush=True) +time.sleep(60) +"#; + +#[cfg(unix)] +mod unix { + use super::*; + use serde_json::Value; + use std::io::Write; + use std::path::Path; + use std::process::Stdio; + use std::time::Duration; + + fn start(f: &Fixture, cwd: &Path, name: &str, input: bool) -> Value { + // Without --interactive stdin is /dev/null, so that service must not read it. + let script = f.root.join(if input { "echo.py" } else { "sleeper.py" }); + std::fs::write(&script, if input { ECHO } else { SLEEPER }).unwrap(); + let script = script.to_str().unwrap().to_string(); + let mut args = vec!["run", "--name", name, "--json"]; + if input { + args.push("--interactive"); + } + args.extend(["--wait", "--ready", "log:ready", "--", PY, "-u", &script]); + let out = f.taba(cwd, &args); + assert_eq!(exit(&out), 0, "{}", text(&out)); + json(&out) + } + + fn log(f: &Fixture, cwd: &Path, id: &str) -> String { + let out = f.taba(cwd, &["logs", id]); + String::from_utf8_lossy(&out.stdout).into_owned() + } + + fn wait_log(f: &Fixture, cwd: &Path, id: &str, needle: &str) { + wait_until(&format!("{needle:?} in the log of {id}"), || { + log(f, cwd, id).contains(needle) + }); + } + + fn code(out: &std::process::Output) -> String { + json(out)["error"]["code"] + .as_str() + .unwrap_or("") + .to_string() + } + + #[test] + fn send_reaches_stdin_and_stdin_stays_open_without_a_writer() { + let f = Fixture::new("input-send"); + let svc = start(&f, &f.wt_a, "echo", true); + let id = svc["service"].as_str().unwrap().to_string(); + + // Nobody writes: the service must not read EOF. + std::thread::sleep(Duration::from_millis(1500)); + assert!(!log(&f, &f.wt_a, &id).contains("EOF")); + let row = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); + assert_eq!(row["status"], "running"); + assert_eq!(row["input"], true); + + let out = f.taba(&f.wt_a, &["send", &id, "hello", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["bytes"], 6); + wait_log(&f, &f.wt_a, &id, "got:hello"); + + // A key and text without newline join the next line. + assert_eq!(exit(&f.taba(&f.wt_a, &["send", &id, "--key", "r"])), 0); + let out = f.taba(&f.wt_a, &["send", &id, "x", "--no-newline"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(exit(&f.taba(&f.wt_a, &["send", &id, "--key", "enter"])), 0); + wait_log(&f, &f.wt_a, &id, "got:rx"); + + // Between sends no writer is connected; still no EOF. + std::thread::sleep(Duration::from_millis(500)); + assert!(!log(&f, &f.wt_a, &id).contains("EOF")); + + // attach from a pipe: forwards stdin, shows the log, detaches at EOF. + let mut child = f + .cmd(&f.wt_a, &["attach", &id]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(b"via attach\n") + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert!(String::from_utf8_lossy(&out.stderr).contains("keeps running")); + wait_log(&f, &f.wt_a, &id, "got:via attach"); + assert_eq!( + f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap()["status"], + "running" + ); + + // signal goes to the main process. + let out = f.taba(&f.wt_a, &["signal", &id, "USR1", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["signal"], "USR1"); + wait_log(&f, &f.wt_a, &id, "usr1"); + + // Same flags again: already running; different --interactive: conflict. + let again = start(&f, &f.wt_a, "echo", true); + assert_eq!(again["status"], "already_running"); + let script = f.root.join("echo.py"); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "echo", + "--json", + "--", + PY, + "-u", + script.to_str().unwrap(), + ], + ); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_CONFLICT"); + + // After stop: E_NOT_RUNNING; rm removes the FIFO. + assert_eq!(exit(&f.taba(&f.wt_a, &["stop", &id])), 0); + let out = f.taba(&f.wt_a, &["send", &id, "late", "--json"]); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NOT_RUNNING"); + let fifo = f + .home() + .join("inputs") + .join(svc["scope"].as_str().unwrap()) + .join("echo.fifo"); + assert!(fifo.exists()); + assert_eq!(exit(&f.taba(&f.wt_a, &["rm", &id])), 0); + assert!(!fifo.exists()); + } + + #[test] + fn a_service_without_input_is_refused() { + let f = Fixture::new("input-none"); + let svc = start(&f, &f.wt_a, "plain", false); + let id = svc["service"].as_str().unwrap(); + let out = f.taba(&f.wt_a, &["send", id, "hello", "--json"]); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NO_INPUT"); + let out = f + .cmd(&f.wt_a, &["attach", id]) + .env("TABA_OUTPUT", "json") + .stdin(Stdio::null()) + .output() + .unwrap(); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NO_INPUT"); + let row = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); + assert_eq!(row["input"], false); + // signal does not need --interactive. + let out = f.taba(&f.wt_a, &["signal", id, "usr1"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + wait_log(&f, &f.wt_a, id, "usr1"); + } + + #[test] + fn input_follows_the_ownership_rules() { + let f = Fixture::new("input-owner"); + let svc = start(&f, &f.wt_a, "echo", true); + let id = svc["service"].as_str().unwrap(); + + // Another scope is refused, for send, attach and signal alike. + let out = f.taba(&f.wt_b, &["send", id, "intruder", "--json"]); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NOT_OWNER"); + let out = f + .cmd(&f.wt_b, &["attach", id]) + .env("TABA_OUTPUT", "json") + .stdin(Stdio::null()) + .output() + .unwrap(); + assert_eq!(code(&out), "E_NOT_OWNER"); + let out = f.taba(&f.wt_b, &["signal", id, "USR1", "--json"]); + assert_eq!(code(&out), "E_NOT_OWNER"); + let out = f.taba(&f.wt_b, &["send", id, "x", "--force", "--json"]); + assert_eq!(code(&out), "E_FORCE_NEEDS_REASON"); + std::thread::sleep(Duration::from_millis(300)); + assert!(!log(&f, &f.wt_a, id).contains("intruder")); + + // --force --reason is allowed and recorded. + let out = f.taba( + &f.wt_b, + &[ + "send", id, "forced", "--force", "--reason", "test", "--json", + ], + ); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["forced"], true); + wait_log(&f, &f.wt_a, id, "got:forced"); + let ev = f + .events() + .into_iter() + .find(|e| e["event"] == "force_send") + .expect("force_send recorded"); + assert_eq!(ev["reason"], "test"); + assert_eq!(ev["overrode"], serde_json::json!(["E_NOT_OWNER"])); + + // An exclusive borrow lets the borrower send and locks out the owner. + let out = f.taba(&f.wt_b, &["borrow", id, "--mut", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let out = f.taba(&f.wt_b, &["send", id, "borrower", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + wait_log(&f, &f.wt_a, id, "got:borrower"); + let out = f.taba(&f.wt_a, &["send", id, "owner", "--json"]); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_LOCKED"); + assert_eq!(exit(&f.taba(&f.wt_b, &["release", id])), 0); + let out = f.taba(&f.wt_a, &["send", id, "owner", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + wait_log(&f, &f.wt_a, id, "got:owner"); + } + + #[test] + fn a_bad_key_is_a_usage_error() { + let f = Fixture::new("input-key"); + let out = f.taba(&f.wt_a, &["send", "x", "--key", "rr", "--json"]); + assert_eq!(exit(&out), 2, "{}", text(&out)); + assert_eq!(code(&out), "E_USAGE"); + } +} + +#[cfg(windows)] +#[test] +fn run_input_is_unsupported_on_windows() { + let f = Fixture::new("input-windows"); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--interactive", + "--name", + "x", + "--json", + "--", + PY, + "-c", + SLEEP_30, + ], + ); + assert_eq!(exit(&out), 1, "{}", text(&out)); + assert_eq!(json(&out)["error"]["code"], "E_UNSUPPORTED"); + assert!(f.ps(&[]).is_empty()); +} From fbccdf0f234904bbef290eeb4ca85f4a43366f43 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn Date: Thu, 26 Nov 2026 13:17:44 +0900 Subject: [PATCH 2/8] Interactive services: PTY stdin + holder, log-view input mode, reload (#68) - Interactive services get a pseudo-terminal as stdin (stdout/stderr still go to the log). A per-service holder (`taba __hold`) keeps the PTY master open, forwards the input FIFO into it, drains it and exits with the service. Echo is off; the PTY is not the controlling terminal. - `run -i/--interactive`, `--no-interactive`; `flutter run` and `vite` (also via npm/pnpm/yarn/bun scripts) are interactive by default and the reply says `interactive: yes`. - `taba logs -f` on a terminal is read-only until `i`; Ctrl+] stops typing, q quits. `taba attach` opens it in input mode; `i` in `taba ui` too. - `taba reload [--restart]`: Flutter SIGUSR1/SIGUSR2, Vite `r` + Enter; E_NO_RELOAD otherwise. - `ps --json` field is `interactive`. Windows: E_UNSUPPORTED (#79); fixes the unused-constant build error on windows-latest. - Tests, README section, SKILL.md hot-reload section. Co-Authored-By: Claude Opus 5.5 --- README.md | 86 ++++- skills/taba/SKILL.md | 44 ++- src/claims.rs | 4 +- src/error.rs | 3 +- src/input.rs | 862 ++++++++++++++++++++++++++++++++++++------- src/main.rs | 162 ++++++-- src/state.rs | 19 +- src/ui/app.rs | 50 +-- src/ui/mod.rs | 11 +- src/ui/view.rs | 5 +- tests/input.rs | 262 ++++++++++++- 11 files changed, 1293 insertions(+), 215 deletions(-) diff --git a/README.md b/README.md index b5971d5..4d5c395 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,7 @@ Windows Terminal and PowerShell, and Linux terminals. | `←` `→`, `Space` | Fold or unfold a scope. Folding only changes the view; nothing is stopped. | | `x` | On a running service: stop it. On a scope line: stop every service of that scope. On an exited service: remove it, like `taba rm`. It asks first: `y` confirms, any other key cancels. | | `l` | Follow the selected service's log, like `taba logs -f`. `↑` `↓` `PgUp` `PgDn` scroll, `End` follows again, `Esc` goes back. | +| `i` | On an [interactive](#interactive-dev-servers-flutter-vite) service, in the list or its log: type into it. The UI steps aside for the log view in input mode; `Ctrl+]` comes back. | | `/` | Filter by scope or service name. `Enter` keeps the filter, `Esc` clears it. | | `Esc` | Clear the filter and any messages. | | `q`, `Ctrl+C` | Quit. Services keep running. | @@ -310,6 +311,64 @@ Windows Terminal and PowerShell, and Linux terminals. - **It needs an interactive terminal.** Programs should read `taba ps --watch --json` instead. +## Interactive dev servers (Flutter, Vite) + +Some dev servers take keys while they run: `flutter run` (`r` hot reload, +`R` hot restart), Vite (`r` + Enter restarts the server, `h` + Enter shows +help). They only read those keys when stdin is a terminal, so taba can start +a service **interactive**: its stdin is a pseudo-terminal, and its output +still goes to the log as for any other service. + +```sh +# flutter run and vite are interactive automatically: +taba run --name app --wait=300 --ready "log:Flutter run key commands" -- flutter run -d chrome +# started login-fix-3f9a/app +# ... +# interactive: yes (type: taba attach login-fix-3f9a/app; i in taba logs -f) + +taba run --name web --port auto --wait -- npm run dev -- --port '{port}' --strictPort + +# Anything else: -i / --interactive. --no-interactive turns it off. +taba run -i --name repl -- python3 -i +``` + +**Typing.** `taba logs -f S/N` on a terminal shows the log read-only. Press +`i` to type into the service (a bar says *INPUT MODE*): every key goes to +it, as if you ran it in that terminal. `Ctrl+]` stops typing, and `q` (or +`Ctrl+C`) leaves the log; the service keeps running either way. +`taba attach S/N` opens the same view already in input mode. In `taba ui`, +`i` does the same. Watching is free; typing follows the [ownership +rules](#ownership-model), as `stop` does. + +**From scripts and agents.** + +| Command | What it does | +| --- | --- | +| `taba reload S/N` | Reload the dev server the best way taba knows. `flutter run`: SIGUSR1 (hot reload; `--restart`: SIGUSR2, hot restart), which needs no stdin. Vite: `r` + Enter (restarts the server; open pages reload). Anything else: `E_NO_RELOAD`. | +| `taba send S/N TEXT` | Write `TEXT` and a newline to its stdin (`--no-newline` for none). | +| `taba send S/N --key K` | Write one key: a character such as `r`, or `enter`, `esc`, `tab`, `space`, `backspace`, `ctrl-X`. | +| `taba signal S/N USR1\|USR2\|HUP` | Signal the service's main process (works without `--interactive`). | + +`taba ps --json` shows `"interactive": true` for such services. + +Notes: + +- **Flutter web: wait for the browser.** `flutter run -d chrome` prints + `Flutter run key commands` before the browser has connected; a reload in + that gap only recompiles (`No client connected`). If a script reloads + right after start, wait for + `--ready "log:Dart VM Service on Chrome is available"` instead. +- **How it works.** One small holder process per interactive service + (`taba __hold`, exits with the service) keeps the terminal open and + forwards what `send` and `attach` write to + `$TABA_HOME/inputs//.fifo`. Echo is off, so typed keys do not + show up in the log. The terminal is not the service's controlling + terminal: `Ctrl+C` typed into it is not turned into SIGINT; use + `taba stop`. +- **Windows** is not supported yet ([#79](https://github.com/Buchi-dev-dzn/taba/issues/79)): + `-i` fails with `E_UNSUPPORTED`, and `flutter run` / `vite` start as + before, without input. + ## Use with AI agents taba is meant for AI coding agents as much as for people: @@ -456,6 +515,8 @@ If your agent doesn't load skills, paste this into `AGENTS.md` or `CLAUDE.md`: - On an error, read `error.code` and do the first item of `error.next`. Never answer `E_PORT_IN_USE` or `E_NOT_OWNER` with `kill`, `pkill` or `--force`. - Read recent output with `taba logs --tail 100 --json`. +- After editing a Flutter or Vite app, run `taba reload ` (Flutter hot + restart: `--restart`), not a restart of the service. - Stop only your own scope: `taba stop --scope `, then clean up with `taba rm --scope `. Never touch other scopes or processes taba didn't start. @@ -521,13 +582,17 @@ that. Measurements against Docker are in [docs/benchmarks.md](docs/benchmarks.md | Command | What it does | | --- | --- | -| `taba run [--scope S] --name N [--port P \| auto \| auto:START] [--wait[=SECS]] [--ready CHECK] [--json] -- CMD...` | Start `CMD` detached as service `S/N`, in its own process group, with output appended to its log. `{port}` in `CMD` is replaced by the port, and `PORT` is set. | +| `taba run [--scope S] --name N [--port P \| auto \| auto:START] [--wait[=SECS]] [--ready CHECK] [-i \| --no-interactive] [--json] -- CMD...` | Start `CMD` detached as service `S/N`, in its own process group, with output appended to its log. `{port}` in `CMD` is replaced by the port, and `PORT` is set. `-i` makes it [interactive](#interactive-dev-servers-flutter-vite) (default for `flutter run` and `vite`). | | `taba whoami [--scope S] [--json]` | Show the scope taba uses here, its source (`flag`, `env`, `git`), worktree, branch, agent and services. | | `taba ps [--scope S] [--running] [--json]` | List services with status `running`, `starting`, `stopping` or `exited`, plus URL and directory (`~` for your home; absolute in `--json`). `--running` hides exited ones. | | `taba ps --watch --json [--scope S] [--running] [--interval DURATION]` | Keep running and print the `ps --json` document as one line (NDJSON) at once and again whenever it changes, until interrupted. Read-only. See [Watching for changes](#watching-for-changes). | | `taba ps --all [--json]` | List every listening TCP port of your user, managed by taba or not: address, pid, command, directory, git worktree and branch, and the taba service if there is one. Read-only. | | `taba ui` | Browse every scope's services in a terminal UI; stop, remove, filter and follow logs with the keyboard. See [Terminal UI](#terminal-ui). | -| `taba logs S/N [--tail N] [-f] [--json]` (or a bare name in your scope) | Print the log, or its last `N` lines. Add `-f` to follow it until the service exits. `--json` returns up to 16 KiB of log data in `log` and is incompatible with `-f`. | +| `taba logs S/N [--tail N] [-f] [--json]` (or a bare name in your scope) | Print the log, or its last `N` lines. Add `-f` to follow it until the service exits; for an interactive service on a terminal, `i` types into it. `--json` returns up to 16 KiB of log data in `log` and is incompatible with `-f`. | +| `taba attach S/N` | Follow an interactive service's log in input mode; `Ctrl+]` stops typing, `q` quits. From a pipe: forward stdin until EOF. | +| `taba send S/N TEXT \| --key K [--no-newline]` | Write to an interactive service's stdin. | +| `taba reload S/N [--restart]` | Hot reload `flutter run` (SIGUSR1; `--restart`: SIGUSR2), restart Vite (`r`). | +| `taba signal S/N USR1\|USR2\|HUP` | Signal a service's main process (macOS, Linux). | | `taba stop S/N` (or `N` in your scope) | Stop one service of your own scope. | | `taba stop --scope S` | Stop every service in scope `S`. | | `taba stop ... --timeout SECS` | Seconds to wait between SIGTERM and SIGKILL (Windows: Ctrl+Break and job termination; default 5). | @@ -551,8 +616,9 @@ that. Measurements against Docker are in [docs/benchmarks.md](docs/benchmarks.md | `taba update [--json]` | Check, then replace an eligible official standalone Linux or macOS install. Otherwise, report the manual upgrade path. See [Updating](#updating). | `--ready` is `tcp` (default when there is a port), `http:PATH` or -`log:REGEX`, and needs `--wait`. `--agent NAME` on `run`, `stop`, `rm` and -`whoami` overrides `$TABA_AGENT`. Run `taba --help` to see all +`log:REGEX`, and needs `--wait`. `--agent NAME` on `run`, `stop`, `rm`, +`whoami`, `send`, `attach`, `reload` and `signal` overrides `$TABA_AGENT`; +`send`, `attach`, `reload` and `signal` take `--force --reason` like `stop`. Run `taba --help` to see all flags. ### Errors @@ -582,7 +648,10 @@ single quotes). The exit status follows the code: | `E_LOCKED` | 3 | Another scope has an exclusive maintenance borrow. Retry later or use `--wait-lock` for a legitimate maintenance operation. | | `E_NO_CLAIMANT` | 3 | `disown` found no eligible claimant. Arrange a claim before disowning. | | `E_BUSY` | 3 | Another `stop` or starting `run` of that service is in progress, or another taba process held the state lock for the whole lock timeout (`details.holder_pid` when recorded). | -| `E_CONFLICT` | 3 | Same name already running with a different command, directory or port. | +| `E_CONFLICT` | 3 | Same name already running with a different command, directory, port or interactive mode. | +| `E_NO_INPUT` | 3 | `send` or `attach` to a service that is not interactive (or whose input holder is gone). Restart it with `--interactive`. | +| `E_NO_RELOAD` | 3 | `reload` of something that is not `flutter run` or Vite. Use `taba send S/N --key ...` with its own key. | +| `E_NOT_RUNNING` | 3 | `send`, `attach`, `reload` or `signal` of a service that has exited. | | `E_STILL_RUNNING` | 3 | `rm` of a running service. | | `E_PORT_IN_USE`, `E_PORT_CLAIMED` | 4 | The port is held by a process, or reserved by another taba service. | | `E_NO_FREE_PORT` | 4 | `--port auto` found no free port in its range. | @@ -593,6 +662,8 @@ single quotes). The exit status follows the code: | `E_BORROW_COMMAND` | 1 | The command run under `borrow --mut` exited unsuccessfully; inspect `exit_code` and its output. | | `E_CONFIG` | 1 | A `config.toml` field, `TABA_TTL`, or `TABA_LOCK_TIMEOUT` is invalid or unreadable; `details` identifies the source. | | `E_STATE` | 1 | State is unreadable, unavailable, damaged, or out of space. Read `details.path` and `next`; listings may instead emit `W_STATE_SKIPPED`. | +| `E_INPUT_BLOCKED` | 1 | The service did not read its input for 5 s; some bytes were not written. | +| `E_UNSUPPORTED` | 1 | Not available on this platform yet: interactive services and `signal` on Windows ([#79](https://github.com/Buchi-dev-dzn/taba/issues/79)). | | `E_SIGNAL_FAILED` | 1 | taba could not signal a verified service; inspect the result and ask the human rather than using raw process controls. | | `E_UPDATE_FAILED` | 1 | `taba update` could not reach, read or verify the release. The installed binary is unchanged. | @@ -748,6 +819,7 @@ $TABA_HOME (default ~/.taba) ├── borrows/.json # shared and exclusive borrow records ├── logs//.log # stdout + stderr, appended across runs ├── ops//.json # in-flight stop or start of that service (operation lock) +├── inputs//.fifo # input of an interactive service, read by its holder (macOS, Linux) ├── events.jsonl # append-only created, moved, cleanup, hook and audited override events ├── version # state schema version (2) ├── btime/ # Linux boot-time cache and recovery copies @@ -840,6 +912,10 @@ taba is an early prototype: - **Some children are not tracked.** Children that move into a different process group or session (Windows: break away from the job) are not tracked, and `stop` won't reach them. +- **Interactive services: macOS and Linux only.** No ConPTY on Windows yet + ([#79](https://github.com/Buchi-dev-dzn/taba/issues/79)). Logs keep the + service's output as written; taba does not strip colors or `\r` progress + lines. - **No log rotation.** Logs grow across runs until you `taba rm` the service. - **Ownership is a convention, not security.** `--scope`, `$TABA_SCOPE` and `$TABA_AGENT` are claims, not credentials. Leases prevent accidental diff --git a/skills/taba/SKILL.md b/skills/taba/SKILL.md index 59d396f..d0b5614 100644 --- a/skills/taba/SKILL.md +++ b/skills/taba/SKILL.md @@ -14,7 +14,10 @@ in. Everything below uses only these commands: taba whoami [--scope S] [--agent A] [--json] taba run [--scope S] --name N [--port P | --port auto | --port auto:START] [--wait[=SECS]] [--ready tcp|http:PATH|log:REGEX] [--ttl DURATION] - [--service-ttl DURATION] [--json] -- CMD... + [--service-ttl DURATION] [-i | --no-interactive] [--json] -- CMD... +taba reload S/N | N [--restart] [--json] +taba send S/N | N TEXT [--no-newline] | --key KEY [--json] +taba signal S/N | N USR1|USR2|HUP [--json] taba ps [--scope S] [--running] [--json] taba ps --all [--json] taba ps --watch --json [--scope S] [--running] [--interval DURATION] @@ -45,6 +48,8 @@ Ctrl+C or when its stdout is closed), never in a one-shot tool call; there, use `taba ps --json`. `taba ui` is an interactive terminal UI for humans; agents should not run it (it needs a terminal and waits for keys). Point the human to it instead. +The same goes for `taba attach` (it waits for keys): use `taba send` and +`taba reload`. ## Identity, scope and leases @@ -131,6 +136,8 @@ expiry when the human needs them. | `E_CONFIG` | `$TABA_HOME/config.toml`, `TABA_TTL`, or `TABA_LOCK_TIMEOUT` is invalid or unreadable. | Use `error.details` to correct the named key or environment value; do not discard state. | | `E_STATE` | State is unreadable, damaged, unavailable, or lacks space. | Read `error.details.path` and `error.next`; ask the human before any repair that removes records. | | `E_BUSY` | Another change is in progress, or the global state lock timed out. | Wait, inspect with `taba ps --json`, then retry. | +| `E_NO_INPUT`, `E_NO_RELOAD`, `E_NOT_RUNNING`, `E_INPUT_BLOCKED` | `send` / `reload` could not reach the service. | See "Hot reload (Flutter, Vite)". | +| `E_UNSUPPORTED` | Not available on this platform (interactive services on Windows). | Run it without `-i`; restart the service instead of reloading. | | `E_SIGNAL_FAILED` | taba could not signal a verified service. | Inspect the result and ask the human; do not use raw kill commands. | | `E_FORCE_NEEDS_REASON` | A protected action needs an audited reason. | Do not bypass the guard; ask the human or coordinator for direction. | | `E_UPDATE_FAILED` | An update check or verification failed. | Keep using the current binary and ask the human if an update is required. | @@ -160,6 +167,41 @@ data was omitted, and `bytes_total` is the original log size in bytes. The file is available at `log_path`, also listed by `taba ps --json`. Logs of any scope are readable. +## Hot reload (Flutter, Vite) + +`flutter run` and `vite` (also behind `npm run dev`, `pnpm dev`, ...) start +**interactive**: their stdin is a terminal taba can type into, and the +`run` reply has `"interactive": true`. After you edit the app: + +```sh +taba reload app --json # flutter run: hot reload (SIGUSR1) +taba reload app --restart --json # flutter run: hot restart (SIGUSR2) +taba reload web --json # vite: sends r + Enter, restarts the dev server +taba send app --key R --json # any key the tool documents (no Enter) +taba send repl 'print(1)' --json # a line (with Enter) to a service started with -i +``` + +Then read the result in the log (`taba logs app --tail 20 --json`): Flutter +prints `Reloaded application in ...` or `Restarted application in ...`, and +compile errors there too. Do not restart the service to pick up a change +that a reload can apply. + +- Start Flutter web with + `taba run --name app --wait=300 --ready "log:Flutter run key commands" --json -- flutter run -d chrome`. + That line appears before the browser has connected; if a reload right + after start reports `No client connected`, wait for + `log:Dart VM Service on Chrome is available` instead. +- Any other program that reads keys: start it with `-i`. `--no-interactive` + turns the default off. +- `send`, `reload` and `signal` follow the same ownership rules as `stop`: + your scope or an exclusive borrow. Errors: `E_NO_INPUT` (not interactive: + restart it with `-i`), `E_NO_RELOAD` (taba knows no reload for it; use + `taba send --key`), `E_NOT_RUNNING`, `E_INPUT_BLOCKED` (it does not read + its input). On Windows these return `E_UNSUPPORTED`; restart the service + to pick up changes there. +- Humans type into it with `taba attach S/N`, or `i` in `taba logs -f` and + `taba ui`; point them there. + ## Borrowing another scope's service Use `taba borrow S/N --json` for the URL and borrow ID. Check that ID with diff --git a/src/claims.rs b/src/claims.rs index e953499..a6f1bf1 100644 --- a/src/claims.rs +++ b/src/claims.rs @@ -171,8 +171,8 @@ pub fn transfer(store: &Store, svc: &Service, target: &str, how: &str) -> Result let mut moved = svc.clone(); moved.scope = target.into(); moved.log_path = store.log_path(target, &svc.name); - if moved.input.is_some() { - moved.input = Some(store.input_path(target, &svc.name)); + if let Some(input) = &mut moved.input { + input.fifo = store.input_path(target, &svc.name); } let event = json!({"at":rfc3339(now_secs()), "event":"service_moved", "how":how, "from":svc.id(), "to":moved.id(), "instance":svc.instance()}); moved.moves.push(event.clone()); diff --git a/src/error.rs b/src/error.rs index d69c22d..b6f318a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -161,7 +161,8 @@ pub fn exit_code(code: &str) -> u8 { match code { "E_USAGE" | "E_NO_SCOPE" | "E_INVALID_IDENT" | "E_FORCE_NEEDS_REASON" => 2, "E_NOT_OWNER" | "E_SCOPE_HELD" | "E_LEASE_LIVE" | "E_LOCKED" | "E_BUSY" | "E_BORROWED" - | "E_NO_CLAIMANT" | "E_CONFLICT" | "E_STILL_RUNNING" | "E_NO_INPUT" | "E_NOT_RUNNING" => 3, + | "E_NO_CLAIMANT" | "E_CONFLICT" | "E_STILL_RUNNING" | "E_NO_INPUT" | "E_NOT_RUNNING" + | "E_NO_RELOAD" => 3, "E_PORT_IN_USE" | "E_PORT_CLAIMED" | "E_NO_FREE_PORT" | "E_START_FAILED" | "E_NOT_READY" => 4, "E_NOT_FOUND" | "E_DANGLING" => 5, diff --git a/src/input.rs b/src/input.rs index 1ed858b..d5ac5f6 100644 --- a/src/input.rs +++ b/src/input.rs @@ -1,64 +1,204 @@ -//! Interactive input for services (#68): `run --interactive`, `send`, `attach` -//! and `signal`. +//! Interactive services (#68): `run --interactive`, `send`, `attach`, +//! `reload`, `signal`, and typing into a service from its log view. //! -//! A service started with `run --interactive` gets a FIFO in -//! `$TABA_HOME/inputs//.fifo` as its stdin, opened read-only. -//! The service also inherits a write end of the same FIFO as an extra file -//! descriptor, so it never reads EOF while nobody is sending, and no taba -//! process stays behind. (Stdin itself is not opened read-write: the Dart VM, -//! and so `flutter run`, receives nothing from a read-write FIFO on macOS.) -//! `send` and `attach` open the FIFO for writing, write and close it. +//! # How input reaches the service (Unix) //! -//! Writing to a service's stdin, or signalling it, mutates someone else's -//! process, so the same rules as `stop` apply: the owning scope (under its -//! lease) or the holder of an exclusive borrow; anyone else needs -//! `--force --reason`, which is recorded in events.jsonl. While another scope -//! holds an exclusive borrow, the owner is refused with `E_LOCKED`. +//! Dev servers such as `flutter run` and `vite` only read their keys when +//! stdin is a terminal, so an interactive service gets a pseudo-terminal +//! (PTY) as its stdin. Only stdin: stdout and stderr still go to the log +//! file, so the log stays the same as for any other service. //! -//! Windows (named pipes) is not supported yet: these commands fail there -//! with `E_UNSUPPORTED`. +//! ```text +//! taba send / attach ──write──▶ inputs//.fifo +//! │ (read by) +//! holder: `taba __hold` +//! │ write +//! PTY master ══▶ PTY slave = service stdin +//! ``` +//! +//! `run` creates the FIFO and the PTY (echo off, so typed keys do not show +//! up anywhere), starts the service with the PTY slave as stdin, then +//! starts a small holder process (`taba __hold`, one per interactive +//! service, in its own session). The holder keeps the PTY master open (a +//! closed master would end the service's stdin), copies the FIFO into it, +//! drains whatever the terminal side outputs, and exits once the service's +//! process group is gone. The holder also keeps the FIFO open for reading, +//! so writers never block on a missing reader and the service never sees +//! EOF between two `send`s. +//! +//! The PTY is not the service's controlling terminal: the service stays in +//! its own session as before, so a crashing holder does not SIGHUP it, and +//! Ctrl+C typed into it is not turned into SIGINT (use `taba stop`). +//! +//! # Who may type +//! +//! Viewing a log is free. Writing to a service's stdin, or signalling it, +//! mutates someone else's process, so the same rules as `stop` apply: the +//! owning scope (under its lease) or the holder of an exclusive borrow; +//! anyone else needs `--force --reason`, which is recorded in events.jsonl. +//! While another scope holds an exclusive borrow, the owner is refused with +//! `E_LOCKED`. +//! +//! Windows (ConPTY) is not supported yet (#79): `run --interactive` and +//! these commands fail there with `E_UNSUPPORTED`. + +#![cfg_attr(windows, allow(dead_code, unused_imports, unused_variables))] use crate::error::{Next, Output, Result, TabaError}; use crate::scope::{self, Caller}; -use crate::state::{Service, Store}; +use crate::state::{Input, Service, Store}; use crate::{borrows, config, lease}; use serde_json::json; +use std::fs::File; use std::path::{Path, PathBuf}; use std::time::Duration; /// How long a write waits for a service that does not read its stdin. const WRITE_TIMEOUT: Duration = Duration::from_secs(5); -/// The byte that ends `attach` (Ctrl+]). +/// The byte that leaves input mode (Ctrl+]). const DETACH: u8 = 0x1d; +/// Terminal size the service sees (its output is a file, not this size). +const COLS: u16 = 120; +const ROWS: u16 = 40; pub fn unsupported(what: &str) -> TabaError { TabaError::new( "E_UNSUPPORTED", - format!("{what} is not supported on this platform yet (Unix only)"), + format!("{what} is not supported on this platform yet (macOS and Linux only)"), ) .details(json!({ "feature": what, "platform": std::env::consts::OS })) + .next(Next::just( + "start it without --interactive; Windows (ConPTY) support is tracked in \ + https://github.com/Buchi-dev-dzn/taba/issues/79", + )) +} + +// ------------------------------------------------------------ detection + +/// Dev servers taba knows how to drive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// `flutter run`: `r` hot reload, `R` hot restart; also SIGUSR1/SIGUSR2. + Flutter, + /// `vite` (dev or preview): `r` + Enter restarts the server. + Vite, + Other, +} + +impl Kind { + pub fn name(self) -> &'static str { + match self { + Kind::Flutter => "flutter", + Kind::Vite => "vite", + Kind::Other => "other", + } + } +} + +/// What `command` (run in `cwd`) is: `flutter run`, `vite`, or something +/// else. Looks through wrappers (`fvm flutter run`, `npx vite`, +/// `sh -c '...'`) and one level of package.json scripts (`npm run dev`, +/// `pnpm dev`, `yarn dev`, `bun run dev`). +pub fn detect(command: &[String], cwd: &Path) -> Kind { + detect_words(&split(command), Some(cwd)) +} + +fn split(command: &[String]) -> Vec { + command + .iter() + .flat_map(|w| w.split_whitespace()) + .map(|w| w.trim_matches(|c| c == '"' || c == '\'').to_string()) + .collect() +} + +/// The program name of `word`: lower case, without directory and without +/// `.exe`/`.bat`/`.cmd`/`.js`/`.mjs`. +fn base(word: &str) -> String { + let file = word.rsplit(['/', '\\']).next().unwrap_or(word); + let file = file.to_ascii_lowercase(); + for ext in [".exe", ".bat", ".cmd", ".js", ".mjs"] { + if let Some(stem) = file.strip_suffix(ext) { + return stem.to_string(); + } + } + file +} + +fn first_arg(words: &[String]) -> Option<&str> { + words + .iter() + .map(String::as_str) + .find(|w| !w.starts_with('-')) +} + +fn detect_words(words: &[String], cwd: Option<&Path>) -> Kind { + for (i, w) in words.iter().enumerate() { + let rest = &words[i + 1..]; + match base(w).as_str() { + "flutter" if first_arg(rest) == Some("run") => return Kind::Flutter, + "vite" if !matches!(first_arg(rest), Some("build" | "optimize")) => { + return Kind::Vite; + } + pm @ ("npm" | "pnpm" | "yarn" | "bun") => { + if let Some(cwd) = cwd + && let Some(script) = script_name(pm, rest) + && let Some(body) = package_script(cwd, script) + { + let kind = detect_words(&split(&[body]), None); + if kind != Kind::Other { + return kind; + } + } + } + _ => {} + } + } + Kind::Other +} + +/// The package.json script a package-manager call runs, if any. +fn script_name<'a>(pm: &str, rest: &'a [String]) -> Option<&'a str> { + let mut args = rest + .iter() + .map(String::as_str) + .filter(|w| !w.starts_with('-')); + match (pm, args.next()?) { + (_, "run" | "run-script") => args.next(), + ("npm", "start") => Some("start"), + ("npm", _) => None, + (_, script) => Some(script), + } +} + +fn package_script(cwd: &Path, script: &str) -> Option { + let text = std::fs::read_to_string(cwd.join("package.json")).ok()?; + let pkg: serde_json::Value = serde_json::from_str(&text).ok()?; + pkg["scripts"][script].as_str().map(str::to_string) } -/// The input FIFO of a service being started: `stdin` for the child, and -/// `keep`, a write end without close-on-exec that the child inherits so its -/// stdin never reaches EOF. taba drops both after the spawn. -pub struct Fifo { - pub path: PathBuf, - pub stdin: std::fs::File, - #[cfg(unix)] - pub _keep: std::os::fd::OwnedFd, +// ------------------------------------------------------------ setup (run) + +/// The terminal of an interactive service being started. +pub struct Terminal { + pub fifo: PathBuf, + /// The PTY slave: the child's stdin. + pub stdin: File, + master: File, + /// The FIFO, opened for reading (and writing, so it never reaches EOF). + reader: File, } -/// Creates the input FIFO of `scope/name` (replacing a stale one) and opens -/// both ends for the child. +/// Creates the input FIFO of `scope/name` (replacing a stale one) and a PTY +/// with echo off. #[cfg(unix)] -pub fn create(store: &Store, scope: &str, name: &str) -> Result { - use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +pub fn create(store: &Store, scope: &str, name: &str) -> Result { + use std::os::fd::{AsRawFd, FromRawFd}; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::OpenOptionsExt; let path = store.input_path(scope, name); - let fail = |what: &str, e: std::io::Error| { - TabaError::state(format!("cannot {what} input FIFO {}: {e}", path.display())) + let os = |what: &str| { + let e = std::io::Error::last_os_error(); + TabaError::state(format!("cannot {what} for {scope}/{name}: {e}")) }; crate::state::create_private_dir_all(path.parent().expect("input has parent"))?; match std::fs::remove_file(&path) { @@ -68,46 +208,186 @@ pub fn create(store: &Store, scope: &str, name: &str) -> Result { let c = std::ffi::CString::new(path.as_os_str().as_bytes()) .map_err(|_| TabaError::state("input path contains a NUL byte"))?; if unsafe { libc::mkfifo(c.as_ptr(), 0o600) } != 0 { - return Err(fail("create", std::io::Error::last_os_error())); + return Err(os("create the input FIFO")); } - // Non-blocking, as no writer exists yet; cleared below. - let stdin = std::fs::OpenOptions::new() + // Read-write: opening does not wait for a writer, and the holder never + // reads EOF while nobody is sending. + let reader = std::fs::OpenOptions::new() .read(true) - .custom_flags(libc::O_NONBLOCK) + .write(true) .open(&path) - .map_err(|e| fail("open", e))?; - // Without O_CLOEXEC, so the child inherits it. taba is single-threaded - // here and spawns nothing else before dropping it. - let fd = unsafe { libc::open(c.as_ptr(), libc::O_WRONLY) }; + .map_err(|e| TabaError::state(format!("cannot open {}: {e}", path.display())))?; + + let fd = unsafe { libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY) }; if fd < 0 { - return Err(fail("open", std::io::Error::last_os_error())); + return Err(os("open a pseudo-terminal")); + } + let master = unsafe { File::from_raw_fd(fd) }; + let m = master.as_raw_fd(); + unsafe { + libc::fcntl(m, libc::F_SETFD, libc::FD_CLOEXEC); + } + if unsafe { libc::grantpt(m) } != 0 || unsafe { libc::unlockpt(m) } != 0 { + return Err(os("set up the pseudo-terminal")); } - let keep = unsafe { OwnedFd::from_raw_fd(fd) }; - let raw = stdin.as_raw_fd(); - let flags = unsafe { libc::fcntl(raw, libc::F_GETFL) }; - if flags < 0 || unsafe { libc::fcntl(raw, libc::F_SETFL, flags & !libc::O_NONBLOCK) } < 0 { - return Err(fail("set up", std::io::Error::last_os_error())); + // ptsname is not thread-safe; `run` has no other threads here. + let name_ptr = unsafe { libc::ptsname(m) }; + if name_ptr.is_null() { + return Err(os("name the pseudo-terminal")); } - Ok(Fifo { - path, + let slave_path = unsafe { std::ffi::CStr::from_ptr(name_ptr) } + .to_string_lossy() + .into_owned(); + let stdin = std::fs::OpenOptions::new() + .read(true) + .write(true) + .custom_flags(libc::O_NOCTTY) + .open(&slave_path) + .map_err(|e| TabaError::state(format!("cannot open {slave_path}: {e}")))?; + let s = stdin.as_raw_fd(); + unsafe { + let mut t: libc::termios = std::mem::zeroed(); + if libc::tcgetattr(s, &mut t) == 0 { + t.c_lflag &= !(libc::ECHO | libc::ECHOE | libc::ECHOK | libc::ECHONL); + libc::tcsetattr(s, libc::TCSANOW, &t); + } + let ws = libc::winsize { + ws_row: ROWS, + ws_col: COLS, + ws_xpixel: 0, + ws_ypixel: 0, + }; + libc::ioctl(m, libc::TIOCSWINSZ, &ws); + } + Ok(Terminal { + fifo: path, stdin, - _keep: keep, + master, + reader, + }) +} + +#[cfg(windows)] +pub fn create(_store: &Store, _scope: &str, _name: &str) -> Result { + Err(unsupported("run --interactive")) +} + +/// Starts the holder of the service `spawned` (see the module docs); +/// `stderr` is the service's log. +#[cfg(unix)] +pub fn spawn_holder(t: Terminal, spawned: &crate::proc::Spawned, stderr: File) -> Result { + use std::os::fd::AsRawFd; + use std::os::unix::process::CommandExt; + use std::process::{Command, Stdio}; + let exe = std::env::current_exe() + .map_err(|e| TabaError::state(format!("cannot find the taba executable: {e}")))?; + let (m, r) = (t.master.as_raw_fd(), t.reader.as_raw_fd()); + let mut cmd = Command::new(exe); + cmd.arg("__hold") + .args([ + m.to_string(), + r.to_string(), + spawned.pid.to_string(), + spawned.pgid.to_string(), + spawned.start_time.to_string(), + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::from(stderr)); + unsafe { + // Only the holder inherits the two descriptors. + cmd.pre_exec(move || { + for fd in [m, r] { + if libc::fcntl(fd, libc::F_SETFD, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + } + Ok(()) + }); + } + let holder = crate::proc::spawn_detached(cmd).map_err(|e| { + TabaError::new( + "E_START_FAILED", + format!("cannot start the input holder: {e:?}"), + ) + })?; + Ok(Input { + fifo: t.fifo, + holder_pid: holder.pid, + holder_start_time: holder.start_time, }) } #[cfg(windows)] -pub fn create(_store: &Store, _scope: &str, _name: &str) -> Result { - Err(unsupported("run --interactive").next(Next::just( - "start it without --interactive; see https://github.com/Buchi-dev-dzn/taba/issues/68", - ))) +pub fn spawn_holder(_t: Terminal, _spawned: &crate::proc::Spawned, _stderr: File) -> Result { + Err(unsupported("run --interactive")) } -/// Writes `bytes` to the service's input FIFO without blocking forever on a +/// `taba __hold MASTER FIFO PID PGID START_TIME`: the holder process. Copies +/// the FIFO into the PTY master and drains the master until the service's +/// process group is gone. +#[cfg(unix)] +pub fn hold(master: i32, fifo: i32, pid: i32, pgid: i32, start_time: u64) -> u8 { + use std::io::{ErrorKind, Read, Write}; + use std::os::fd::FromRawFd; + for fd in [master, fifo] { + if unsafe { libc::fcntl(fd, libc::F_GETFD) } < 0 { + eprintln!("taba __hold: descriptor {fd} is not open"); + return 1; + } + unsafe { + libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC); + } + } + let mut drain = unsafe { File::from_raw_fd(master) }; + let mut fifo = unsafe { File::from_raw_fd(fifo) }; + let Ok(mut to_master) = drain.try_clone() else { + eprintln!("taba __hold: cannot duplicate the terminal"); + return 1; + }; + std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + loop { + match fifo.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + if to_master.write_all(&buf[..n]).is_err() { + break; + } + } + Err(e) if e.kind() == ErrorKind::Interrupted => {} + Err(_) => break, + } + } + }); + // With echo off this is usually silent; draining keeps a program that + // writes to its terminal from blocking. + std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + loop { + match drain.read(&mut buf) { + Ok(0) => break, + Ok(_) => {} + Err(e) if e.kind() == ErrorKind::Interrupted => {} + Err(_) => break, + } + } + }); + while crate::proc::group_is_ours(pid, pgid, start_time) { + std::thread::sleep(Duration::from_millis(200)); + } + 0 +} + +// ------------------------------------------------------------ writing + +/// Writes `bytes` to the service's input without blocking forever on a /// service that does not read. #[cfg(unix)] -pub fn write(svc: &Service, path: &Path, bytes: &[u8]) -> Result<()> { +pub fn write(svc: &Service, input: &Input, bytes: &[u8]) -> Result<()> { use std::io::{ErrorKind, Write}; use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; + let path = &input.fifo; let is_fifo = path .symlink_metadata() .is_ok_and(|m| m.file_type().is_fifo()); @@ -119,7 +399,8 @@ pub fn write(svc: &Service, path: &Path, bytes: &[u8]) -> Result<()> { .custom_flags(libc::O_NONBLOCK) .open(path) .map_err(|e| match e.raw_os_error() { - // No reader: the service (and every process holding its stdin) is gone. + // No reader: the holder is gone. + Some(libc::ENXIO) if svc.is_running() => holder_gone(svc, input), Some(libc::ENXIO) => not_running(svc), _ => TabaError::state(format!("cannot open {}: {e}", path.display())), })?; @@ -148,7 +429,9 @@ pub fn write(svc: &Service, path: &Path, bytes: &[u8]) -> Result<()> { std::thread::sleep(Duration::from_millis(20)); } Err(e) if e.kind() == ErrorKind::Interrupted => {} - Err(e) if e.raw_os_error() == Some(libc::EPIPE) => return Err(not_running(svc)), + Err(e) if e.raw_os_error() == Some(libc::EPIPE) => { + return Err(holder_gone(svc, input)); + } Err(e) => return Err(TabaError::state(format!("cannot write input: {e}"))), } } @@ -156,7 +439,7 @@ pub fn write(svc: &Service, path: &Path, bytes: &[u8]) -> Result<()> { } #[cfg(windows)] -pub fn write(_svc: &Service, _path: &Path, _bytes: &[u8]) -> Result<()> { +pub fn write(_svc: &Service, _input: &Input, _bytes: &[u8]) -> Result<()> { Err(unsupported("service input")) } @@ -164,7 +447,7 @@ fn no_input(svc: &Service) -> TabaError { TabaError::new( "E_NO_INPUT", format!( - "{} was not started with --interactive, so it has no stdin to write to", + "{} was not started with --interactive, so it takes no input", svc.id() ), ) @@ -175,6 +458,22 @@ fn no_input(svc: &Service) -> TabaError { )) } +fn holder_gone(svc: &Service, input: &Input) -> TabaError { + TabaError::new( + "E_NO_INPUT", + format!( + "{}: its input holder (pid {}) is gone, so it takes no more input", + svc.id(), + input.holder_pid + ), + ) + .details(json!({ "service": svc.id(), "holder_pid": input.holder_pid })) + .next(Next::run( + "restart it (stop it first)", + format!("taba stop {}", svc.id()), + )) +} + fn not_running(svc: &Service) -> TabaError { TabaError::new("E_NOT_RUNNING", format!("{} is not running", svc.id())) .details(json!({ "service": svc.id(), "instance": svc.instance() })) @@ -239,6 +538,8 @@ pub(crate) fn authorise( Ok(svc) } +// ------------------------------------------------------------ send + /// The bytes of one `--key`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Key(pub Vec); @@ -251,7 +552,9 @@ pub fn parse_key(s: &str) -> std::result::Result { fn key_bytes(s: &str) -> std::result::Result, String> { let named = match s.to_ascii_lowercase().as_str() { - "enter" | "return" => Some(b"\n".to_vec()), + // A terminal's Enter key sends CR; the PTY turns it into "\n" for + // line-based readers (ICRNL) and raw-mode programs expect it. + "enter" | "return" => Some(b"\r".to_vec()), "esc" | "escape" => Some(vec![0x1b]), "tab" => Some(b"\t".to_vec()), "space" => Some(b" ".to_vec()), @@ -296,11 +599,14 @@ pub fn cmd_send(a: SendArgs) -> Result { (None, Some(Key(k))) => k, _ => return Err(TabaError::usage("give TEXT or --key KEY")), }; + if cfg!(windows) { + return Err(unsupported("taba send")); + } let caller = scope::resolve(a.scope, a.agent)?; let store = Store::open()?; let svc = authorise(&store, &caller, &a.target, "send", reason.as_deref(), true)?; - let path = svc.input.clone().expect("checked"); - write(&svc, &path, &bytes)?; + let input = svc.input.clone().expect("checked"); + write(&svc, &input, &bytes)?; let mut body = json!({ "service": svc.id(), "bytes": bytes.len(), @@ -315,6 +621,8 @@ pub fn cmd_send(a: SendArgs) -> Result { )) } +// ------------------------------------------------------------ signal, reload + /// `taba signal`: the signals `signal` accepts. #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] pub enum Signal { @@ -410,6 +718,100 @@ fn send_signal(_svc: &Service, _sig: Signal) -> Result<()> { Err(unsupported("taba signal")) } +pub struct ReloadArgs { + pub target: String, + pub restart: bool, + pub scope: Option, + pub agent: Option, + pub force: bool, + pub reason: Option, +} + +/// `taba reload`: the most reliable reload for the kind of dev server. +/// `flutter run`: SIGUSR1 (hot reload) or SIGUSR2 (`--restart`, hot +/// restart), which needs no stdin. Vite: `r` + Enter on stdin (restarts the +/// dev server; open pages reload), so it needs `--interactive`. +pub fn cmd_reload(a: ReloadArgs) -> Result { + let reason = crate::check_force(a.force, a.reason)?; + let caller = scope::resolve(a.scope, a.agent)?; + let store = Store::open()?; + let (scope, name) = crate::resolve_target(&a.target, &caller)?; + let peek = store + .get(&scope, &name)? + .ok_or_else(|| crate::not_found(&scope, &name))?; + let kind = detect(peek.template(), &peek.cwd); + if kind == Kind::Other { + return Err(TabaError::new( + "E_NO_RELOAD", + format!( + "{} is not a dev server taba knows how to reload (flutter run, vite)", + peek.id() + ), + ) + .details(json!({ "service": peek.id(), "command": peek.template() })) + .next(Next::run( + "send its reload key yourself", + format!("taba send {} --key r", peek.id()), + ))); + } + if cfg!(windows) { + return Err(unsupported("taba reload")); + } + let id = peek.id(); + let svc = authorise( + &store, + &caller, + &id, + "reload", + reason.as_deref(), + kind == Kind::Vite, + )?; + let (method, text) = match kind { + Kind::Flutter => { + let sig = if a.restart { + Signal::Usr2 + } else { + Signal::Usr1 + }; + send_signal(&svc, sig)?; + let what = if a.restart { + "hot restart" + } else { + "hot reload" + }; + ( + format!("SIG{}", sig.name()), + format!( + "{id}: {what} requested (SIG{} to pid {})", + sig.name(), + svc.pid + ), + ) + } + _ => { + let input = svc.input.clone().expect("checked"); + write(&svc, &input, b"r\n")?; + ( + "stdin".to_string(), + format!("{id}: sent r (Vite restarts the dev server; open pages reload)"), + ) + } + }; + let mut body = json!({ + "service": id, + "kind": kind.name(), + "method": method, + "restart": a.restart, + "instance": svc.instance(), + }); + if reason.is_some() { + body["forced"] = json!(true); + } + Ok(Output::new(body, text)) +} + +// ------------------------------------------------------------ log view + pub struct AttachArgs { pub target: String, pub scope: Option, @@ -418,62 +820,202 @@ pub struct AttachArgs { pub reason: Option, } +/// `taba attach`: the log view in input mode (on a terminal), or forward +/// stdin until EOF (from a pipe). pub fn cmd_attach(a: AttachArgs) -> Result> { + use std::io::IsTerminal; let reason = crate::check_force(a.force, a.reason)?; + if cfg!(windows) { + return Err(unsupported("taba attach")); + } let caller = scope::resolve(a.scope, a.agent)?; let store = Store::open()?; - attach(&store, &caller, &a.target, reason.as_deref())?; + let svc = authorise( + &store, + &caller, + &a.target, + "attach", + reason.as_deref(), + true, + )?; + let (log, pos) = open_tail(&svc)?; + if std::io::stdin().is_terminal() { + view( + &store, + &caller, + &svc, + log, + pos, + true, + false, + reason.as_deref(), + ) + } else { + forward_pipe(&svc, log, pos) + }?; Ok(None) } -/// Restores the terminal mode when `attach` ends, also on an error. -struct RawMode(bool); +/// `taba ui`: `i` on an interactive service. Input mode right away; Ctrl+] +/// returns to the TUI. +pub(crate) fn attach_from_ui(store: &Store, caller: &Caller, target: &str) -> Result<()> { + let svc = authorise(store, caller, target, "attach", None, true)?; + let (log, pos) = open_tail(&svc)?; + view(store, caller, &svc, log, pos, true, true, None) +} + +/// `taba logs -f` on a terminal, for an interactive service: read-only +/// until `i`. `log` is positioned after what was already printed. +pub(crate) fn follow(store: &Store, caller: &Caller, svc: &Service, log: File) -> Result<()> { + use std::io::Seek; + let mut log = log; + let pos = log.stream_position()?; + view(store, caller, svc, log, pos, false, false, None) +} + +fn open_tail(svc: &Service) -> Result<(File, u64)> { + let mut log = File::open(&svc.log_path) + .map_err(|e| TabaError::state(format!("cannot open {}: {e}", svc.log_path.display())))?; + let end = log.metadata()?.len(); + let pos = crate::log_tail_start(&mut log, 0, end, 20)?; + Ok((log, pos)) +} + +/// Restores the terminal mode when the view ends, also on an error. +struct RawMode; +impl RawMode { + fn enable() -> Result { + ratatui::crossterm::terminal::enable_raw_mode() + .map_err(|e| TabaError::state(format!("cannot set up the terminal: {e}")))?; + Ok(RawMode) + } +} impl Drop for RawMode { fn drop(&mut self) { - if self.0 { - let _ = ratatui::crossterm::terminal::disable_raw_mode(); - } + let _ = ratatui::crossterm::terminal::disable_raw_mode(); } } -/// Shows the service's log and forwards the caller's input to its stdin -/// until Ctrl+] (on a terminal) or EOF (on a pipe), or until the service -/// exits. The service keeps running after a detach. Also used by `taba ui`. -pub(crate) fn attach( +/// One status line between log lines (raw mode: explicit `\r\n`). +fn status(text: &str) { + eprint!("\r\n\x1b[7m taba \x1b[0m {text}\r\n"); +} + +fn banner(id: &str, typing: bool, leave_to_ui: bool) { + if typing { + let back = if leave_to_ui { + "Ctrl+] returns to taba ui" + } else { + "Ctrl+] stops typing" + }; + status(&format!("INPUT MODE: keys go to {id} · {back}")); + } else { + status(&format!( + "read-only log of {id} · i types into it · q quits (the service keeps running)" + )); + } +} + +/// The log view on a terminal: follows the log and, in input mode, sends +/// each key to the service. `i` enters input mode (if the caller may type), +/// Ctrl+] leaves it (or the view, with `leave_on_detach`), `q` / Ctrl+C +/// quits. The service keeps running. +#[allow(clippy::too_many_arguments)] +fn view( store: &Store, caller: &Caller, - target: &str, + svc: &Service, + mut log: File, + mut pos: u64, + mut typing: bool, + leave_on_detach: bool, force_reason: Option<&str>, ) -> Result<()> { - use std::io::{IsTerminal, Read, Seek, SeekFrom, Write}; - - let svc = authorise(store, caller, target, "attach", force_reason, true)?; - let path = svc.input.clone().expect("checked"); - let tty = std::io::stdin().is_terminal(); - let mut log = std::fs::File::open(&svc.log_path) - .map_err(|e| TabaError::state(format!("cannot open {}: {e}", svc.log_path.display())))?; - let end = log.metadata()?.len(); - let mut pos = crate::log_tail_start(&mut log, 0, end, 20)?; + use std::io::{Read, Seek, SeekFrom, Write}; + let id = svc.id(); + let raw = RawMode::enable()?; + banner(&id, typing, leave_on_detach); + let mut stdout = std::io::stdout().lock(); + let mut chunk = Vec::new(); + loop { + let running = svc.is_running(); + log.seek(SeekFrom::Start(pos))?; + chunk.clear(); + log.read_to_end(&mut chunk)?; + if !chunk.is_empty() { + pos += chunk.len() as u64; + if stdout + .write_all(&crlf(&chunk)) + .and_then(|_| stdout.flush()) + .is_err() + { + break; + } + } else if !running { + status(&format!("{id} exited")); + break; + } + let Some(bytes) = read_stdin(Duration::from_millis(50))? else { + continue; + }; + if bytes.is_empty() { + break; // the terminal went away + } + if typing { + let (send, detach) = match bytes.iter().position(|&b| b == DETACH) { + Some(i) => (&bytes[..i], true), + None => (&bytes[..], false), + }; + if !send.is_empty() { + let input = svc.input.as_ref().expect("interactive"); + if let Err(e) = write(svc, input, send) { + status(&e.message); + } + } + if detach { + if leave_on_detach { + break; + } + typing = false; + banner(&id, typing, leave_on_detach); + } + continue; + } + for &b in &bytes { + match b { + b'i' => { + match authorise(store, caller, &id, "attach", force_reason, true) { + Ok(_) => { + typing = true; + banner(&id, typing, leave_on_detach); + } + Err(e) => status(&format!("cannot type into {id}: {}", e.message)), + } + break; + } + b'q' | 0x03 | 0x04 => { + drop(raw); + return Ok(()); + } + _ => {} + } + } + } + drop(raw); + Ok(()) +} - let how = if tty { - "Ctrl+] detaches" - } else { - "EOF detaches" - }; +/// `taba attach` from a pipe: forwards stdin until EOF, then shows the log +/// a little longer so the answer to the last input is not cut off. +fn forward_pipe(svc: &Service, mut log: File, mut pos: u64) -> Result<()> { + use std::io::{Read, Seek, SeekFrom, Write}; + let input = svc.input.clone().expect("interactive"); eprintln!( - "taba: attached to {} ({how}; the service keeps running)", + "taba: attached to {} (EOF detaches; the service keeps running)", svc.id() ); - let raw = RawMode( - tty && ratatui::crossterm::terminal::enable_raw_mode() - .map_err(|e| TabaError::state(format!("cannot set up the terminal: {e}"))) - .is_ok(), - ); - let mut stdout = std::io::stdout().lock(); let mut chunk = Vec::new(); - // After stdin ends (a pipe), the log is shown a little longer so the - // service's answer to the last input is not cut off. let mut linger: Option = None; let outcome = loop { let running = svc.is_running(); @@ -482,77 +1024,72 @@ pub(crate) fn attach( log.read_to_end(&mut chunk)?; if !chunk.is_empty() { pos += chunk.len() as u64; - let out = if raw.0 { crlf(&chunk) } else { chunk.clone() }; - if stdout.write_all(&out).and_then(|_| stdout.flush()).is_err() { + if stdout + .write_all(&chunk) + .and_then(|_| stdout.flush()) + .is_err() + { break "closed"; } } else if !running { break "exited"; } - if linger.is_some_and(|t| t.elapsed() >= Duration::from_millis(500)) { - break "detached"; - } - if linger.is_some() { + if let Some(t) = linger { + if t.elapsed() >= Duration::from_millis(500) { + break "detached"; + } std::thread::sleep(Duration::from_millis(50)); continue; } - // Waiting for input also paces the loop. No reader thread is left - // behind, so `taba ui` gets every key back after a detach. match read_stdin(Duration::from_millis(50))? { None => {} - Some(bytes) if bytes.is_empty() => { - linger = Some(std::time::Instant::now()); - } - Some(bytes) if raw.0 => { - let (send, stop) = match bytes.iter().position(|&b| b == DETACH) { - Some(i) => (&bytes[..i], true), - None => (&bytes[..], false), - }; - if !send.is_empty() { - write(&svc, &path, send)?; - } - if stop { - break "detached"; - } - } - Some(bytes) => write(&svc, &path, &bytes)?, + Some(bytes) if bytes.is_empty() => linger = Some(std::time::Instant::now()), + Some(bytes) => write(svc, &input, &bytes)?, } }; - drop(raw); match outcome { - "exited" => eprintln!("\ntaba: {} exited", svc.id()), - "detached" => eprintln!("\ntaba: detached from {}; it keeps running", svc.id()), + "exited" => eprintln!("taba: {} exited", svc.id()), + "detached" => eprintln!("taba: detached from {}; it keeps running", svc.id()), _ => {} } Ok(()) } /// Waits up to `timeout` for stdin: `None` when nothing arrived, an empty -/// buffer at EOF, else the bytes read. +/// buffer at EOF, else the bytes read. Uses select(2), which (unlike poll) +/// works on terminals on macOS. #[cfg(unix)] fn read_stdin(timeout: Duration) -> Result>> { - let mut fds = libc::pollfd { - fd: libc::STDIN_FILENO, - events: libc::POLLIN, - revents: 0, + let fd = libc::STDIN_FILENO; + let mut tv = libc::timeval { + tv_sec: timeout.as_secs() as libc::time_t, + tv_usec: timeout.subsec_micros() as libc::suseconds_t, + }; + let n = unsafe { + let mut set: libc::fd_set = std::mem::zeroed(); + libc::FD_ZERO(&mut set); + libc::FD_SET(fd, &mut set); + libc::select( + fd + 1, + &mut set, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut tv, + ) }; - let ms = timeout.as_millis().min(i32::MAX as u128) as libc::c_int; - let n = unsafe { libc::poll(&mut fds, 1, ms) }; if n < 0 { let e = std::io::Error::last_os_error(); if e.kind() == std::io::ErrorKind::Interrupted { return Ok(None); } - return Err(TabaError::state(format!("cannot read stdin: {e}"))); + // EBADF: stdin is closed. + return Ok(Some(Vec::new())); } if n == 0 { return Ok(None); } - if fds.revents & libc::POLLNVAL != 0 { - return Ok(Some(Vec::new())); - } let mut buf = vec![0u8; 4096]; - let got = unsafe { libc::read(libc::STDIN_FILENO, buf.as_mut_ptr().cast(), buf.len()) }; + let got = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; if got < 0 { let e = std::io::Error::last_os_error(); if matches!( @@ -590,11 +1127,15 @@ fn crlf(bytes: &[u8]) -> Vec { mod tests { use super::*; + fn words(s: &str) -> Vec { + s.split(' ').map(str::to_string).collect() + } + #[test] fn keys() { assert_eq!(key_bytes("r").unwrap(), b"r"); assert_eq!(key_bytes("R").unwrap(), b"R"); - assert_eq!(key_bytes("enter").unwrap(), b"\n"); + assert_eq!(key_bytes("enter").unwrap(), b"\r"); assert_eq!(key_bytes("ctrl-c").unwrap(), vec![3]); assert_eq!(key_bytes("Ctrl+D").unwrap(), vec![4]); assert_eq!(key_bytes("esc").unwrap(), vec![0x1b]); @@ -606,4 +1147,51 @@ mod tests { fn crlf_adds_carriage_returns_once() { assert_eq!(crlf(b"a\nb\r\nc"), b"a\r\nb\r\nc"); } + + #[test] + fn detects_flutter_run_and_vite() { + let none = Path::new("/nonexistent"); + let d = |s: &str| detect(&words(s), none); + assert_eq!(d("flutter run -d chrome"), Kind::Flutter); + assert_eq!(d("fvm flutter run"), Kind::Flutter); + assert_eq!(d("/opt/flutter/bin/flutter --verbose run"), Kind::Flutter); + assert_eq!(d("flutter.bat run"), Kind::Flutter); + assert_eq!(d("flutter build web"), Kind::Other); + assert_eq!(d("flutter test"), Kind::Other); + assert_eq!(d("vite"), Kind::Vite); + assert_eq!(d("npx vite --port 5173"), Kind::Vite); + assert_eq!(d("node node_modules/vite/bin/vite.js"), Kind::Vite); + assert_eq!(d("vite preview"), Kind::Vite); + assert_eq!(d("vite build"), Kind::Other); + assert_eq!(d("python3 -m http.server"), Kind::Other); + assert_eq!(d("node vite.config.ts"), Kind::Other); + // A shell command line is split into words. + assert_eq!( + detect( + &["sh".into(), "-c".into(), "cd app && flutter run".into()], + none + ), + Kind::Flutter + ); + } + + #[test] + fn detects_vite_behind_package_scripts() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("package.json"), + r#"{"scripts":{"dev":"vite --host","build":"vite build","start":"vite","serve":"node server.js"}}"#, + ) + .unwrap(); + let d = |s: &str| detect(&words(s), dir.path()); + assert_eq!(d("npm run dev"), Kind::Vite); + assert_eq!(d("npm start"), Kind::Vite); + assert_eq!(d("pnpm dev"), Kind::Vite); + assert_eq!(d("yarn run dev"), Kind::Vite); + assert_eq!(d("bun run dev"), Kind::Vite); + assert_eq!(d("npm run build"), Kind::Other); + assert_eq!(d("npm run serve"), Kind::Other); + assert_eq!(d("npm install"), Kind::Other); + assert_eq!(d("npm run missing"), Kind::Other); + } } diff --git a/src/main.rs b/src/main.rs index a927622..c614e9f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,7 +28,7 @@ use scope::{Caller, ScopeSource, check_ident}; use serde_json::{Value, json}; use state::{OpLock, Service, Store}; use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::io::{self, IsTerminal, Read, Seek, SeekFrom, Write}; use std::process::{Command, ExitCode, Stdio}; use std::thread; use std::time::Duration; @@ -78,11 +78,14 @@ enum Cmd { /// already_running re-run), independent of the lease #[arg(long, value_parser = config::parse_service_ttl_flag)] service_ttl: Option, - /// Interactive: give the service a stdin that stays open, for - /// `taba send` and `taba attach` (e.g. `r` for a Flutter hot reload; - /// Unix only) - #[arg(short = 'i', long = "interactive")] - input: bool, + /// Interactive: the service's stdin is a terminal that `taba attach`, + /// `taba send` and `i` in the log view type into (macOS, Linux). + /// Default for `flutter run` and `vite` + #[arg(short = 'i', long)] + interactive: bool, + /// Not interactive, also for `flutter run` and `vite` + #[arg(long, conflicts_with = "interactive")] + no_interactive: bool, /// Print one JSON document (also: TABA_OUTPUT=json) #[arg(long)] json: bool, @@ -90,7 +93,7 @@ enum Cmd { #[arg(last = true, required = true, value_name = "CMD")] command: Vec, }, - /// Write a line (or one key) to the stdin of a service started with --interactive + /// Write a line (or one key) to the stdin of an interactive service Send { /// SCOPE/NAME, or NAME in the caller's scope target: String, @@ -120,8 +123,8 @@ enum Cmd { #[arg(long)] json: bool, }, - /// Follow a service's log and type into its stdin (--interactive services); - /// Ctrl+] detaches and the service keeps running + /// Follow an interactive service's log and type into it; Ctrl+] stops + /// typing, q quits, and the service keeps running Attach { /// SCOPE/NAME, or NAME in the caller's scope target: String, @@ -138,6 +141,30 @@ enum Cmd { #[arg(long, requires = "force")] reason: Option, }, + /// Reload a dev server: `flutter run` hot reload (SIGUSR1; --restart: + /// hot restart, SIGUSR2), `vite` restart (`r` on its stdin) + Reload { + /// SCOPE/NAME, or NAME in the caller's scope + target: String, + /// Flutter: hot restart instead of hot reload + #[arg(long)] + restart: bool, + /// The caller's scope (default: $TABA_SCOPE, else the git worktree) + #[arg(long)] + scope: Option, + /// Agent acting (default: $TABA_AGENT, else "human") + #[arg(long)] + agent: Option, + /// Reload a service of another scope (needs --reason; recorded) + #[arg(long)] + force: bool, + /// Why --force is needed (recorded in events.jsonl) + #[arg(long, requires = "force")] + reason: Option, + /// Print one JSON document (also: TABA_OUTPUT=json) + #[arg(long)] + json: bool, + }, /// Send SIGUSR1, SIGUSR2 or SIGHUP to a service's main process (Unix; /// `flutter run` hot-reloads on USR1 and hot-restarts on USR2) Signal { @@ -433,6 +460,16 @@ enum Cmd { #[cfg(windows)] #[command(name = "__ctrl-break", hide = true)] CtrlBreak { attach: u32, pgid: u32 }, + /// Internal (Unix): the input holder of an interactive service + #[cfg(unix)] + #[command(name = "__hold", hide = true)] + Hold { + master: i32, + fifo: i32, + pid: i32, + pgid: i32, + start_time: u64, + }, } #[derive(Subcommand)] @@ -574,6 +611,16 @@ fn main() -> ExitCode { Cmd::CtrlBreak { attach, pgid } => { return ExitCode::from(proc::ctrl_break_helper(attach, pgid)); } + #[cfg(unix)] + Cmd::Hold { + master, + fifo, + pid, + pgid, + start_time, + } => { + return ExitCode::from(input::hold(master, fifo, pid, pgid, start_time)); + } Cmd::Run { scope, agent, @@ -583,7 +630,8 @@ fn main() -> ExitCode { ready, ttl, service_ttl, - input, + interactive, + no_interactive, json, command, } => ( @@ -597,7 +645,11 @@ fn main() -> ExitCode { ready, ttl, service_ttl, - input, + interactive: if no_interactive { + Some(false) + } else { + interactive.then_some(true) + }, command, }) .map(Some), @@ -642,6 +694,26 @@ fn main() -> ExitCode { reason, }), ), + Cmd::Reload { + target, + restart, + scope, + agent, + force, + reason, + json, + } => ( + json || env_json(), + input::cmd_reload(input::ReloadArgs { + target, + restart, + scope, + agent, + force, + reason, + }) + .map(Some), + ), Cmd::Signal { target, signal, @@ -1019,7 +1091,8 @@ struct RunArgs { ready: Option, ttl: Option, service_ttl: Option, - input: bool, + /// `-i` (Some(true)), `--no-interactive` (Some(false)), else detected. + interactive: Option, command: Vec, } @@ -1037,11 +1110,13 @@ fn cmd_run(a: RunArgs) -> Result { )); } }; - if a.input && cfg!(windows) { - return Err(input::unsupported("run --interactive").next(Next::just( - "start it without --interactive; Windows support is tracked in the taba issues", - ))); + if a.interactive == Some(true) && cfg!(windows) { + return Err(input::unsupported("run --interactive")); } + // `flutter run` and `vite` are interactive unless --no-interactive. + let interactive = a.interactive.unwrap_or_else(|| { + cfg!(unix) && input::detect(&a.command, &caller.cwd) != input::Kind::Other + }); if let Some(r) = &a.ready && r.needs_port() && a.port.is_none() @@ -1110,7 +1185,7 @@ fn cmd_run(a: RunArgs) -> Result { if ex.template() == template.as_slice() && ex.cwd == caller.cwd && ex.port_request() == port_request - && ex.input.is_some() == a.input + && ex.input.is_some() == interactive { let mut ex = ex.clone(); if let Some(ttl) = a.service_ttl.or(ex.service_ttl_secs) { @@ -1127,7 +1202,7 @@ fn cmd_run(a: RunArgs) -> Result { "E_CONFLICT", format!( "{} is already running with a different command, directory, port or \ - --interactive (command {:?}, dir {}, port {}, input {}); stop it first", + interactive mode (command {:?}, dir {}, port {}, interactive {}); stop it first", ex.id(), ex.template(), tilde(&ex.cwd), @@ -1138,7 +1213,7 @@ fn cmd_run(a: RunArgs) -> Result { .details(json!({ "service": ex.id(), "command": ex.template(), "directory": ex.cwd, "port": ex.port, "port_request": ex.port_request(), "instance": ex.instance(), - "input": ex.input.is_some(), + "interactive": ex.input.is_some(), })) .next(Next::run( "stop it, then run again", @@ -1195,14 +1270,17 @@ fn cmd_run(a: RunArgs) -> Result { let log_offset = log.metadata()?.len(); let log_err = log.try_clone()?; - let fifo = if a.input { + let terminal = if interactive { Some(input::create(&store, &scope, &name)?) } else { None }; - let input_path = fifo.as_ref().map(|f| f.path.clone()); - let stdin = match &fifo { - Some(f) => Stdio::from(f.stdin.try_clone()?), + let holder_err = match &terminal { + Some(_) => Some(log.try_clone()?), + None => None, + }; + let stdin = match &terminal { + Some(t) => Stdio::from(t.stdin.try_clone()?), None => Stdio::null(), }; let mut cmd = Command::new(proc::resolve_program(&command[0])); @@ -1225,15 +1303,28 @@ fn cmd_run(a: RunArgs) -> Result { }; // Detached: its own session / process group (Unix) or console and job // (Windows), so closing the launching terminal does not stop it. - let spawned = proc::spawn_detached(cmd); - // The child holds its own copies of the FIFO now. - drop(fifo); - let spawned = spawned.map_err(|e| match e { + let spawned = proc::spawn_detached(cmd).map_err(|e| match e { proc::SpawnError::Start(e) => start_failed(format!("cannot start {:?}: {e}", command[0])), proc::SpawnError::Vanished => { start_failed(format!("{id} exited immediately; see taba logs {id}")) } })?; + // Interactive: the holder keeps the terminal open and feeds it input. + let input = match (terminal, holder_err) { + (Some(t), Some(err)) => match input::spawn_holder(t, &spawned, err) { + Ok(i) => Some(i), + Err(e) => { + let _ = proc::stop_group( + spawned.pid, + spawned.pgid, + spawned.start_time, + Duration::from_secs(2), + ); + return Err(e); + } + }, + _ => None, + }; let pid = spawned.pid; let mut svc = Service { scope: scope.clone(), @@ -1256,7 +1347,7 @@ fn cmd_run(a: RunArgs) -> Result { .map(|t| util::rfc3339(util::now_secs().saturating_add(t))), moves: Vec::new(), stop_requested_at: None, - input: input_path, + input, }; store.put(&svc)?; if let Some(borrow) = &delegation { @@ -1344,6 +1435,7 @@ fn run_result( "pid": svc.pid, "directory": svc.cwd, "log_path": svc.log_path, + "interactive": svc.input.is_some(), }); let verb = if status == "started" { "started" @@ -1351,6 +1443,11 @@ fn run_result( "already running" }; let mut text = describe(verb, &svc); + if svc.input.is_some() { + text.push_str(&format!( + "\n interactive: yes (type: taba attach {id}; i in taba logs -f)" + )); + } if let Some(c) = check { text.push_str(&format!("\n ready {} check passed in {ms} ms", c.name())); } @@ -1542,7 +1639,7 @@ pub(crate) fn ps_snapshot( "claims": claims::rows(store, &queue)?, "borrows": { "shared": borrows.iter().filter(|b| !b.exclusive).count(), "exclusive": usize::from(exclusive.is_some()) }, "locked_by": exclusive.map(|b| &b.scope), - "input": s.input.is_some(), + "interactive": s.input.is_some(), })); borrowers.push(borrows.iter().map(|b| b.scope.clone()).collect()); } @@ -1706,6 +1803,13 @@ fn cmd_logs(target: &str, follow: bool, tail: Option, json: bool) -> Result if !follow { return Ok(None); } + // An interactive service on a terminal: the log view, read-only until `i`. + if cfg!(unix) && svc.input.is_some() && io::stdin().is_terminal() && io::stdout().is_terminal() + { + drop(stdout); + input::follow(&store, &caller, &svc, file)?; + return Ok(None); + } let mut pos = file.stream_position()?; let mut buf = Vec::new(); loop { diff --git a/src/state.rs b/src/state.rs index 4054ddc..93b9efb 100644 --- a/src/state.rs +++ b/src/state.rs @@ -6,7 +6,7 @@ //! services//.json service records (v0.1 fields + optional v0.2 fields) //! logs//.log service output //! ops//.json in-flight mutation of one service (operation lock) -//! inputs//.fifo stdin of a service started with `run --interactive` (Unix) +//! inputs//.fifo input of a service started with `run --interactive` (Unix) //! events.jsonl append-only audit log //! version state schema version //! lock global lock (flock / LockFileEx) @@ -141,10 +141,21 @@ pub struct Service { /// seconds); a later cleanup forces it once `stop_timeout` has passed. #[serde(default, skip_serializing_if = "Option::is_none")] pub stop_requested_at: Option, - /// `run --interactive`: the FIFO that is this instance's stdin (Unix). The - /// service holds it open for reading and writing, so it never sees EOF. + /// `run --interactive` (Unix): the input FIFO and the holder process that + /// forwards it to the service's terminal (see `input.rs`). #[serde(default, skip_serializing_if = "Option::is_none")] - pub input: Option, + pub input: Option, +} + +/// The input side of an interactive service. Its stdin is a pseudo-terminal; +/// the holder keeps the terminal's master side open and copies what `send` +/// and `attach` write to `fifo` into it. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Input { + pub fifo: PathBuf, + pub holder_pid: i32, + /// Holder start time, in the units of `Service::start_time`. + pub holder_start_time: u64, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] diff --git a/src/ui/app.rs b/src/ui/app.rs index 263311a..4ec7a95 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -29,7 +29,7 @@ pub struct Row { pub pending_gc: Option, /// Whether the owning scope's lease is expired. pub lease_expired: bool, - /// Started with `run --interactive`: `i` attaches to it. + /// Interactive (`run --interactive`): `i` types into it. pub input: bool, } @@ -380,6 +380,29 @@ impl App { .is_some_and(|r| r.input && !r.is_exited()) } + /// `i`: type into the selected service, if it is interactive. + fn attach_key(&mut self) -> Effect { + let (text, effect) = match self.selected_row() { + Some(r) if r.input && !r.is_exited() => { + (None, Effect::Attach(r.scope.clone(), r.name.clone())) + } + Some(r) if r.input => (Some(format!("{} is not running", r.id())), Effect::None), + Some(r) => ( + Some(format!( + "{} is not interactive (start it with --interactive); it takes no input", + r.id() + )), + Effect::None, + ), + None => ( + Some("select an interactive service".to_string()), + Effect::None, + ), + }; + self.notice = text.map(|text| Notice { text, error: false }); + effect + } + fn selected_row(&self) -> Option<&Row> { match &self.cursor { Some(Item::Service(s, n)) => self.row(s, n), @@ -543,6 +566,7 @@ impl App { return Effect::None; } KeyCode::Char('q') => return Effect::Quit, + KeyCode::Char('i') => return self.attach_key(), _ => {} } let log = self.log.get_or_insert_with(LogView::default); @@ -620,29 +644,7 @@ impl App { } } } - KeyCode::Char('i') => { - let (text, effect) = match self.selected_row() { - Some(r) if r.input && !r.is_exited() => { - (None, Effect::Attach(r.scope.clone(), r.name.clone())) - } - Some(r) if r.input => { - (Some(format!("{} is not running", r.id())), Effect::None) - } - Some(r) => ( - Some(format!( - "{} was not started with --interactive; it takes no input", - r.id() - )), - Effect::None, - ), - None => ( - Some("select a service started with --interactive".to_string()), - Effect::None, - ), - }; - self.notice = text.map(|text| Notice { text, error: false }); - return effect; - } + KeyCode::Char('i') => return self.attach_key(), KeyCode::Char('l') => match self.selected_row() { Some(r) => { let path = r.log_path.clone(); diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 52f91c4..81a3cf3 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -5,8 +5,8 @@ //! `ps`'s lease peek, so watching changes nothing). `x` stops or removes //! through the same functions as `taba stop` / `taba rm`, as the caller //! resolved like any CLI call (`$TABA_SCOPE`, `$TABA_AGENT`, git worktree), -//! and never with `--force`. `i` on a service started with `--interactive` -//! suspends the TUI and runs `taba attach` until Ctrl+] detaches. Quitting +//! and never with `--force`. `i` on an interactive service (in the list or its +//! log view) suspends the TUI and types into it until Ctrl+]. Quitting //! never stops anything. //! //! Built on ratatui with the crossterm backend (macOS, Linux and Windows @@ -138,10 +138,11 @@ fn event_loop( } Effect::OpenLog(path) => tail = Some(LogTail::new(path)), Effect::Attach(scope, name) => { - // The same as `taba attach SCOPE/NAME` (never forced), - // with the TUI suspended until Ctrl+] detaches. + // The log view in input mode, as `taba attach SCOPE/NAME` + // (never forced), with the TUI suspended until Ctrl+]. ratatui::restore(); - let res = crate::input::attach(store, caller, &format!("{scope}/{name}"), None); + let res = + crate::input::attach_from_ui(store, caller, &format!("{scope}/{name}")); *terminal = ratatui::try_init().map_err(io_err)?; terminal.clear().map_err(io_err)?; match res { diff --git a/src/ui/view.rs b/src/ui/view.rs index 1daee09..a32f5d1 100644 --- a/src/ui/view.rs +++ b/src/ui/view.rs @@ -490,7 +490,10 @@ fn footer(app: &App) -> Line<'static> { Span::styled(format!(" /{}▏", app.filter), bold), Span::raw(" Enter keep · Esc clear"), ]), - Mode::Logs => Line::raw(" ↑↓ PgUp PgDn scroll End follow Esc back q quit"), + Mode::Logs => Line::raw(format!( + " ↑↓ PgUp PgDn scroll End follow{} Esc back q quit", + if app.can_attach() { " i input" } else { "" } + )), Mode::Normal => Line::raw(format!( " ↑↓ move ←→ / space collapse·expand x {} l logs{} / filter q quit", app.x_label(), diff --git a/tests/input.rs b/tests/input.rs index e4545ee..8e1b7dd 100644 --- a/tests/input.rs +++ b/tests/input.rs @@ -1,12 +1,16 @@ -//! Interactive input (#68): `run --interactive`, `send`, `attach`, `signal`. +//! Interactive services (#68): `run --interactive`, `send`, `attach`, +//! `reload`, `signal`, and input mode in `logs -f`. mod common; use common::*; -/// Echoes each stdin line as `got:LINE`, reports SIGUSR1 and EOF. +/// Reports whether stdin is a terminal with echo, then echoes each stdin +/// line as `got:LINE`; reports SIGUSR1 and EOF. #[cfg(unix)] const ECHO: &str = r#" -import signal, sys +import signal, sys, termios signal.signal(signal.SIGUSR1, lambda *a: print("usr1", flush=True)) +echo = bool(termios.tcgetattr(0)[3] & termios.ECHO) if sys.stdin.isatty() else None +print("tty=%s echo=%s" % (sys.stdin.isatty(), echo), flush=True) print("ready", flush=True) for line in sys.stdin: print("got:" + line.rstrip("\n"), flush=True) @@ -64,6 +68,34 @@ mod unix { .to_string() } + /// The holder pid from the service record. + fn holder_pid(f: &Fixture, svc: &Value) -> i32 { + let rec = f + .home() + .join("services") + .join(svc["scope"].as_str().unwrap()) + .join(format!("{}.json", svc["name"].as_str().unwrap())); + let rec: Value = serde_json::from_slice(&std::fs::read(rec).unwrap()).unwrap(); + rec["input"]["holder_pid"].as_i64().expect("holder_pid") as i32 + } + + fn alive(pid: i32) -> bool { + // kill(pid, 0) succeeds for zombies too; the holder is reparented + // and reaped once it exits. + unsafe { libc::kill(pid, 0) == 0 } + } + + /// An executable `name` in a fresh bin dir, running the Python `body`. + fn fake_tool(f: &Fixture, name: &str, body: &str) -> String { + use std::os::unix::fs::PermissionsExt; + let dir = f.root.join("bin"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, format!("#!/usr/bin/env python3\n{body}")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.to_str().unwrap().to_string() + } + #[test] fn send_reaches_stdin_and_stdin_stays_open_without_a_writer() { let f = Fixture::new("input-send"); @@ -75,7 +107,10 @@ mod unix { assert!(!log(&f, &f.wt_a, &id).contains("EOF")); let row = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); assert_eq!(row["status"], "running"); - assert_eq!(row["input"], true); + assert_eq!(row["interactive"], true); + assert_eq!(svc["interactive"], true); + // stdin is a terminal with echo off; stdout is still the log file. + assert!(log(&f, &f.wt_a, &id).contains("tty=True echo=False")); let out = f.taba(&f.wt_a, &["send", &id, "hello", "--json"]); assert_eq!(exit(&out), 0, "{}", text(&out)); @@ -142,8 +177,12 @@ mod unix { assert_eq!(exit(&out), 3, "{}", text(&out)); assert_eq!(code(&out), "E_CONFLICT"); - // After stop: E_NOT_RUNNING; rm removes the FIFO. + // After stop: the holder exits too, send gives E_NOT_RUNNING, and + // rm removes the FIFO. + let holder = holder_pid(&f, &svc); + assert!(alive(holder), "holder {holder} runs while the service does"); assert_eq!(exit(&f.taba(&f.wt_a, &["stop", &id])), 0); + wait_until("the holder to exit", || !alive(holder)); let out = f.taba(&f.wt_a, &["send", &id, "late", "--json"]); assert_eq!(exit(&out), 3, "{}", text(&out)); assert_eq!(code(&out), "E_NOT_RUNNING"); @@ -174,7 +213,7 @@ mod unix { assert_eq!(exit(&out), 3, "{}", text(&out)); assert_eq!(code(&out), "E_NO_INPUT"); let row = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); - assert_eq!(row["input"], false); + assert_eq!(row["interactive"], false); // signal does not need --interactive. let out = f.taba(&f.wt_a, &["signal", id, "usr1"]); assert_eq!(exit(&out), 0, "{}", text(&out)); @@ -238,6 +277,217 @@ mod unix { wait_log(&f, &f.wt_a, id, "got:owner"); } + /// Like `flutter run`: keys in cbreak mode, hot reload on SIGUSR1 and + /// hot restart on SIGUSR2. + const FAKE_FLUTTER: &str = r#" +import os, signal, sys, tty +signal.signal(signal.SIGUSR1, lambda *a: print("reloaded", flush=True)) +signal.signal(signal.SIGUSR2, lambda *a: print("restarted", flush=True)) +print("args=" + " ".join(sys.argv[1:]), flush=True) +if sys.stdin.isatty(): + tty.setcbreak(0) +print("Flutter run key commands.", flush=True) +while True: + c = os.read(0, 1) + if not c: + print("EOF", flush=True) + signal.pause() + print("key:" + c.decode(), flush=True) +"#; + + /// Like `vite`: line-based shortcuts. + const FAKE_VITE: &str = r#" +import sys +print("tty=%s" % sys.stdin.isatty(), flush=True) +print("VITE ready", flush=True) +for line in sys.stdin: + print("shortcut:" + line.strip(), flush=True) +"#; + + #[test] + fn flutter_run_is_interactive_by_default_and_reloads_by_signal() { + let f = Fixture::new("input-flutter"); + let flutter = fake_tool(&f, "flutter", FAKE_FLUTTER); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "app", + "--wait", + "--ready", + "log:Flutter run key commands", + "--", + &flutter, + "run", + "-d", + "chrome", + ], + ); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(stdout.contains("interactive: yes"), "{stdout}"); + let id = format!("{}/app", f.scope_of(&f.wt_a)); + let row = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); + assert_eq!(row["interactive"], true); + + // A single key arrives without Enter. + assert_eq!(exit(&f.taba(&f.wt_a, &["send", &id, "--key", "r"])), 0); + wait_log(&f, &f.wt_a, &id, "key:r"); + + let out = f.taba(&f.wt_a, &["reload", &id, "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let v = json(&out); + assert_eq!(v["kind"], "flutter"); + assert_eq!(v["method"], "SIGUSR1"); + wait_log(&f, &f.wt_a, &id, "reloaded"); + let out = f.taba(&f.wt_a, &["reload", &id, "--restart", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["method"], "SIGUSR2"); + wait_log(&f, &f.wt_a, &id, "restarted"); + + // Another scope may not reload it. + let out = f.taba(&f.wt_b, &["reload", &id, "--json"]); + assert_eq!(code(&out), "E_NOT_OWNER"); + + // --no-interactive: stdin is /dev/null (EOF), but reload still works. + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "plain", + "--no-interactive", + "--wait", + "--ready", + "log:Flutter run key commands", + "--json", + "--", + &flutter, + "run", + ], + ); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["interactive"], false); + let plain = format!("{}/plain", f.scope_of(&f.wt_a)); + wait_log(&f, &f.wt_a, &plain, "EOF"); + let out = f.taba(&f.wt_a, &["send", &plain, "x", "--json"]); + assert_eq!(code(&out), "E_NO_INPUT"); + } + + #[test] + fn vite_is_interactive_by_default_and_reloads_with_r() { + let f = Fixture::new("input-vite"); + let vite = fake_tool(&f, "vite", FAKE_VITE); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "web", + "--wait", + "--ready", + "log:VITE ready", + "--json", + "--", + &vite, + "--host", + ], + ); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["interactive"], true); + let id = json(&out)["service"].as_str().unwrap().to_string(); + assert!(log(&f, &f.wt_a, &id).contains("tty=True")); + let out = f.taba(&f.wt_a, &["reload", &id, "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["kind"], "vite"); + assert_eq!(json(&out)["method"], "stdin"); + wait_log(&f, &f.wt_a, &id, "shortcut:r"); + + // Something else: no reload method. + let plain = start(&f, &f.wt_a, "plain", false); + let out = f.taba( + &f.wt_a, + &["reload", plain["service"].as_str().unwrap(), "--json"], + ); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NO_RELOAD"); + } + + /// `logs -f` on a terminal: read-only until `i`, Ctrl+] stops typing, + /// q quits; the service keeps running. + #[test] + fn the_log_view_types_only_in_input_mode() { + use std::io::Read; + use std::os::fd::FromRawFd; + let f = Fixture::new("input-view"); + let svc = start(&f, &f.wt_a, "echo", true); + let id = svc["service"].as_str().unwrap().to_string(); + + let (mut master, slave) = unsafe { + let m = libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY); + assert!(m >= 0); + assert_eq!(libc::grantpt(m), 0); + assert_eq!(libc::unlockpt(m), 0); + let name = std::ffi::CStr::from_ptr(libc::ptsname(m)) + .to_string_lossy() + .into_owned(); + let master = std::fs::File::from_raw_fd(m); + let slave = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(name) + .unwrap(); + (master, slave) + }; + let mut child = f + .cmd(&f.wt_a, &["logs", "-f", &id]) + .stdin(slave.try_clone().unwrap()) + .stdout(slave.try_clone().unwrap()) + .stderr(slave.try_clone().unwrap()) + .spawn() + .unwrap(); + drop(slave); + let screen = std::sync::Arc::new(std::sync::Mutex::new(String::new())); + let mut reader = master.try_clone().unwrap(); + let sink = screen.clone(); + std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + while let Ok(n) = reader.read(&mut buf) { + if n == 0 { + break; + } + sink.lock() + .unwrap() + .push_str(&String::from_utf8_lossy(&buf[..n])); + } + }); + let shown = |needle: &str| screen.lock().unwrap().contains(needle); + wait_until("the read-only banner", || shown("read-only log of")); + let mut key = |bytes: &[u8]| { + master.write_all(bytes).unwrap(); + std::thread::sleep(Duration::from_millis(400)); + }; + key(b"nope\r"); // read-only: dropped + key(b"i"); + wait_until("the input banner", || shown("INPUT MODE")); + key(b"typed\r"); + wait_log(&f, &f.wt_a, &id, "got:typed"); + key(&[0x1d]); // Ctrl+]: back to read-only + key(b"late\r"); + key(b"q"); + let status = child.wait().unwrap(); + assert!(status.success()); + let log = log(&f, &f.wt_a, &id); + assert!( + !log.contains("got:nope") && !log.contains("got:late"), + "{log}" + ); + assert!(shown("got:typed"), "the view shows the log"); + let row = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); + assert_eq!(row["status"], "running"); + } + #[test] fn a_bad_key_is_a_usage_error() { let f = Fixture::new("input-key"); From 6aa0b2619c23c0b7fde143ae8c3313fd754ddb4e Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn <208559603+Buchi-dev-dzn@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:54:27 +0900 Subject: [PATCH 3/8] fix: guard Unix-only input timeout on Windows --- src/input.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/input.rs b/src/input.rs index d5ac5f6..ec8ee6b 100644 --- a/src/input.rs +++ b/src/input.rs @@ -54,6 +54,7 @@ use std::path::{Path, PathBuf}; use std::time::Duration; /// How long a write waits for a service that does not read its stdin. +#[cfg(unix)] const WRITE_TIMEOUT: Duration = Duration::from_secs(5); /// The byte that leaves input mode (Ctrl+]). const DETACH: u8 = 0x1d; From a0de0d44defdf8bc339af1cb463ce167fb27a937 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn <208559603+Buchi-dev-dzn@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:56:59 +0900 Subject: [PATCH 4/8] fix: provide Windows CLI parser sufficient stack --- src/main.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main.rs b/src/main.rs index 7303a02..14765f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -628,6 +628,23 @@ fn usage_error(e: &clap::Error, args: &[String]) -> TabaError { } fn main() -> ExitCode { + // Clap's large derived command tree overflows the smaller default Windows + // main-thread stack. Parse and dispatch on a thread with an explicit stack. + #[cfg(windows)] + { + return std::thread::Builder::new() + .name("taba-main".into()) + .stack_size(8 * 1024 * 1024) + .spawn(main_impl) + .expect("start taba main thread") + .join() + .expect("taba main thread"); + } + #[cfg(not(windows))] + main_impl() +} + +fn main_impl() -> ExitCode { let cli = match Cli::try_parse() { Ok(cli) => cli, Err(e) => { From 85fafaa7955b9c56de3f6ae4e7b4dc15a1b05583 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn <208559603+Buchi-dev-dzn@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:00:57 +0900 Subject: [PATCH 5/8] fix: satisfy Windows Clippy on main-thread wrapper --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 14765f4..ee9d7f9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -632,7 +632,7 @@ fn main() -> ExitCode { // main-thread stack. Parse and dispatch on a thread with an explicit stack. #[cfg(windows)] { - return std::thread::Builder::new() + std::thread::Builder::new() .name("taba-main".into()) .stack_size(8 * 1024 * 1024) .spawn(main_impl) From ac8e6d474f4b13343dfa5ba3834adaff8bbf6a36 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn <208559603+Buchi-dev-dzn@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:04:24 +0900 Subject: [PATCH 6/8] fix: return Windows CLI thread exit code --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index ee9d7f9..c7d31d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -638,7 +638,7 @@ fn main() -> ExitCode { .spawn(main_impl) .expect("start taba main thread") .join() - .expect("taba main thread"); + .expect("taba main thread") } #[cfg(not(windows))] main_impl() From 64f64803020e610da6b83158c198ced10eadadf5 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn <208559603+Buchi-dev-dzn@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:54:27 +0900 Subject: [PATCH 7/8] Harden interactive input and Flutter reload handling --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 29 +- src/gc.rs | 1 + src/input.rs | 847 +++++++++++++++++++++++++++++++++-------------- src/main.rs | 85 +++-- src/proc/unix.rs | 11 +- src/state.rs | 28 ++ src/ui/mod.rs | 1 + tests/input.rs | 302 +++++++++++++++-- 10 files changed, 1001 insertions(+), 305 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 79c7dff..40c4106 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1680,6 +1680,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "shlex", "tar", "tempfile", "toml", diff --git a/Cargo.toml b/Cargo.toml index 5a34c52..ecf7b0e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" license = "MIT" [dependencies] +shlex = "2.0.1" clap = { version = "4.6.9", features = ["derive"] } regex = { version = "1.13.2", default-features = false, features = ["std", "unicode-perl"] } serde = { version = "1.0.229", features = ["derive"] } diff --git a/README.md b/README.md index 0461510..61a3ae1 100644 --- a/README.md +++ b/README.md @@ -449,14 +449,14 @@ taba run -i --name repl -- python3 -i it, as if you ran it in that terminal. `Ctrl+]` stops typing, and `q` (or `Ctrl+C`) leaves the log; the service keeps running either way. `taba attach S/N` opens the same view already in input mode. In `taba ui`, -`i` does the same. Watching is free; typing follows the [ownership -rules](#ownership-model), as `stop` does. +`i` does the same. Watching is free; each write checks the [ownership +rules](#ownership-model) again and stays with the instance you attached to. **From scripts and agents.** | Command | What it does | | --- | --- | -| `taba reload S/N` | Reload the dev server the best way taba knows. `flutter run`: SIGUSR1 (hot reload; `--restart`: SIGUSR2, hot restart), which needs no stdin. Vite: `r` + Enter (restarts the server; open pages reload). Anything else: `E_NO_RELOAD`. | +| `taba reload S/N` | Linux only for a verified `flutter run` leader: SIGUSR1 (hot reload; `--restart`: SIGUSR2, hot restart), no stdin needed. On macOS use Flutter's `r` / `R` keys instead. Vite dev: `r` + Enter (restarts the server; open pages reload). Vite preview and unsupported signal targets return `E_NO_RELOAD`. | | `taba send S/N TEXT` | Write `TEXT` and a newline to its stdin (`--no-newline` for none). | | `taba send S/N --key K` | Write one key: a character such as `r`, or `enter`, `esc`, `tab`, `space`, `backspace`, `ctrl-X`. | | `taba signal S/N USR1\|USR2\|HUP` | Signal the service's main process (works without `--interactive`). | @@ -465,6 +465,20 @@ rules](#ownership-model), as `stop` does. Notes: +- **Flutter on macOS.** `reload` and `reload --restart` return + `E_NO_RELOAD` without sending a signal. Use `taba attach S/N` and press + `r` (hot reload) or `R` (hot restart), or run `taba send S/N --key r` + or `taba send S/N --key R`. +- **Unsupported wrappers and older interactive records.** A wrapper that + stays as Flutter's process leader is not a supported signal target. If + the service still accepts input, use Flutter's keys. If the wrapper was + not detected and the service has no input, or an older interactive + record fails FIFO verification, run `taba stop S/N`. Then rerun the + original `taba run --interactive ...` command with its original service + name, options and arguments (add `--interactive` before the service + command, replacing `--no-interactive` if present), then attach or send. + Restarting with `--interactive` enables manual input; it does not make + the wrapper a supported signal target. - **Flutter web: wait for the browser.** `flutter run -d chrome` prints `Flutter run key commands` before the browser has connected; a reload in that gap only recompiles (`No client connected`). If a script reloads @@ -630,8 +644,9 @@ If your agent doesn't load skills, paste this into `AGENTS.md` or `CLAUDE.md`: - On an error, read `error.code` and do the first item of `error.next`. Never answer `E_PORT_IN_USE` or `E_NOT_OWNER` with `kill`, `pkill` or `--force`. - Read recent output with `taba logs --tail 100 --json`. -- After editing a Flutter or Vite app, run `taba reload ` (Flutter hot - restart: `--restart`), not a restart of the service. +- After editing a Flutter or Vite app, use `taba reload ` (Flutter on + Linux or Vite dev), not a restart of the service. For Flutter on macOS, + use `taba send --key r` (hot restart: `--key R`). - Stop only your own scope: `taba stop --scope `, then clean up with `taba rm --scope `. Never touch other scopes or processes taba didn't start. @@ -710,7 +725,7 @@ that. Measurements against Docker are in [docs/benchmarks.md](docs/benchmarks.md | `taba logs S/N [--tail N] [-f] [--json]` (or a bare name in your scope) | Print the log, or its last `N` lines. Add `-f` to follow it until the service exits; for an interactive service on a terminal, `i` types into it. `--json` returns up to 16 KiB of log data in `log` and is incompatible with `-f`. | | `taba attach S/N` | Follow an interactive service's log in input mode; `Ctrl+]` stops typing, `q` quits. From a pipe: forward stdin until EOF. | | `taba send S/N TEXT \| --key K [--no-newline]` | Write to an interactive service's stdin. | -| `taba reload S/N [--restart]` | Hot reload `flutter run` (SIGUSR1; `--restart`: SIGUSR2), restart Vite (`r`). | +| `taba reload S/N [--restart]` | Hot reload a verified `flutter run` leader on Linux (SIGUSR1; `--restart`: SIGUSR2), or restart Vite dev (`r`). On macOS, send Flutter's `r` / `R` keys instead. | | `taba signal S/N USR1\|USR2\|HUP` | Signal a service's main process (macOS, Linux). | | `taba stop S/N` (or `N` in your scope) | Stop one service of your own scope. | | `taba stop --scope S` | Stop every service in scope `S`. | @@ -769,7 +784,7 @@ single quotes). The exit status follows the code: | `E_BUSY` | 3 | Another `stop` or starting `run` of that service is in progress, or another taba process held the state lock for the whole lock timeout (`details.holder_pid` when recorded). | | `E_CONFLICT` | 3 | Same name already running with a different command, directory, port or interactive mode. | | `E_NO_INPUT` | 3 | `send` or `attach` to a service that is not interactive (or whose input holder is gone). Restart it with `--interactive`. | -| `E_NO_RELOAD` | 3 | `reload` of something that is not `flutter run` or Vite. Use `taba send S/N --key ...` with its own key. | +| `E_NO_RELOAD` | 3 | No supported reload method for this service (including Flutter on macOS, an unverified Flutter signal target, or Vite preview). If the service accepts input, send its manual reload key; Flutter uses `r` (hot reload) and `R` (hot restart). | | `E_NOT_RUNNING` | 3 | `send`, `attach`, `reload` or `signal` of a service that has exited. | | `E_STILL_RUNNING` | 3 | `rm` of a running service. | | `E_PORT_IN_USE`, `E_PORT_CLAIMED` | 4 | The port is held by a process, or reserved by another taba service. | diff --git a/src/gc.rs b/src/gc.rs index f270def..50626fa 100644 --- a/src/gc.rs +++ b/src/gc.rs @@ -341,6 +341,7 @@ mod tests { stop_requested_at: None, discovered_ports: Vec::new(), input: None, + dev_kind: None, }; store.put(&svc).unwrap(); svc diff --git a/src/input.rs b/src/input.rs index ec8ee6b..f00edc5 100644 --- a/src/input.rs +++ b/src/input.rs @@ -54,7 +54,6 @@ use std::path::{Path, PathBuf}; use std::time::Duration; /// How long a write waits for a service that does not read its stdin. -#[cfg(unix)] const WRITE_TIMEOUT: Duration = Duration::from_secs(5); /// The byte that leaves input mode (Ctrl+]). const DETACH: u8 = 0x1d; @@ -77,12 +76,15 @@ pub fn unsupported(what: &str) -> TabaError { // ------------------------------------------------------------ detection /// Dev servers taba knows how to drive. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum Kind { /// `flutter run`: `r` hot reload, `R` hot restart; also SIGUSR1/SIGUSR2. Flutter, - /// `vite` (dev or preview): `r` + Enter restarts the server. + /// `vite` dev: `r` + Enter restarts the server. Vite, + /// Preview accepts terminal shortcuts, but not `r`. + VitePreview, Other, } @@ -90,7 +92,7 @@ impl Kind { pub fn name(self) -> &'static str { match self { Kind::Flutter => "flutter", - Kind::Vite => "vite", + Kind::Vite | Kind::VitePreview => "vite", Kind::Other => "other", } } @@ -101,21 +103,25 @@ impl Kind { /// `sh -c '...'`) and one level of package.json scripts (`npm run dev`, /// `pnpm dev`, `yarn dev`, `bun run dev`). pub fn detect(command: &[String], cwd: &Path) -> Kind { - detect_words(&split(command), Some(cwd)) + detect_words(command, Some(cwd), true) } -fn split(command: &[String]) -> Vec { - command - .iter() - .flat_map(|w| w.split_whitespace()) - .map(|w| w.trim_matches(|c| c == '"' || c == '\'').to_string()) - .collect() +/// Only parse strings that really are passed to a shell. Do not try to +/// predict expansion, redirection or which part of a compound command runs. +fn simple_shell_words(line: &str) -> Option> { + if line.contains([ + ';', '&', '|', '(', ')', '<', '>', '`', '$', '\n', '\r', '*', '?', '[', '~', + ]) { + return None; + } + shlex::split(line) } /// The program name of `word`: lower case, without directory and without /// `.exe`/`.bat`/`.cmd`/`.js`/`.mjs`. fn base(word: &str) -> String { - let file = word.rsplit(['/', '\\']).next().unwrap_or(word); + let separators: &[_] = if cfg!(windows) { &['/', '\\'] } else { &['/'] }; + let file = word.rsplit(separators).next().unwrap_or(word); let file = file.to_ascii_lowercase(); for ext in [".exe", ".bat", ".cmd", ".js", ".mjs"] { if let Some(stem) = file.strip_suffix(ext) { @@ -125,52 +131,111 @@ fn base(word: &str) -> String { file } -fn first_arg(words: &[String]) -> Option<&str> { - words - .iter() - .map(String::as_str) - .find(|w| !w.starts_with('-')) +fn flutter_run(args: &[String]) -> bool { + args.iter().map(String::as_str).find(|a| { + !matches!( + *a, + "-v" | "--verbose" | "--no-version-check" | "--suppress-analytics" + ) + }) == Some("run") } -fn detect_words(words: &[String], cwd: Option<&Path>) -> Kind { - for (i, w) in words.iter().enumerate() { - let rest = &words[i + 1..]; - match base(w).as_str() { - "flutter" if first_arg(rest) == Some("run") => return Kind::Flutter, - "vite" if !matches!(first_arg(rest), Some("build" | "optimize")) => { - return Kind::Vite; +fn vite_kind(args: &[String]) -> Kind { + // Skip values of common global/dev options so a value is not mistaken + // for the command. For unknown options before a positional, fail closed. + let mut args = args.iter().map(String::as_str).peekable(); + while let Some(arg) = args.next() { + match arg { + "preview" => return Kind::VitePreview, + "build" | "optimize" | "-h" | "--help" | "-v" | "--version" => return Kind::Other, + "--" => return Kind::Vite, + "--port" | "--config" | "-c" | "--mode" | "-m" | "--base" | "--logLevel" | "-l" + | "--filter" | "-f" | "--configLoader" => { + args.next(); } - pm @ ("npm" | "pnpm" | "yarn" | "bun") => { - if let Some(cwd) = cwd - && let Some(script) = script_name(pm, rest) - && let Some(body) = package_script(cwd, script) - { - let kind = detect_words(&split(&[body]), None); - if kind != Kind::Other { - return kind; - } + "--host" | "--open" | "--debug" | "-d" => { + if args.peek().is_some_and(|next| !next.starts_with('-')) { + args.next(); } } - _ => {} + "--strictPort" | "--force" | "--clearScreen" | "--cors" => {} + opt if opt.starts_with('-') && opt.contains('=') => {} + opt if opt.starts_with('-') => return Kind::Other, + // The Vite command or root positional. Later args cannot name the command. + _ => return Kind::Vite, + } + } + Kind::Vite +} + +fn detect_words(words: &[String], cwd: Option<&Path>, wrappers: bool) -> Kind { + let Some((program, args)) = words.split_first() else { + return Kind::Other; + }; + match base(program).as_str() { + "flutter" if flutter_run(args) => Kind::Flutter, + "vite" => vite_kind(args), + "node" + if args + .first() + .is_some_and(|s| matches!(s.rsplit('/').next(), Some("vite.js" | "vite.mjs"))) => + { + vite_kind(&args[1..]) + } + "fvm" if args.first().is_some_and(|s| s == "flutter") && flutter_run(&args[1..]) => { + Kind::Flutter + } + "npx" | "bunx" if wrappers => { + let args = after_option(args, "--yes"); + let args = after_option(args, "--"); + detect_words(args, None, false) } + "sh" | "bash" | "zsh" if wrappers && args.first().is_some_and(|s| s == "-c") => args + .get(1) + .and_then(|s| simple_shell_words(s)) + .map_or(Kind::Other, |args| { + let command = if args.first().is_some_and(|s| s == "exec") { + &args[1..] + } else { + &args + }; + detect_words(command, cwd, false) + }), + pm @ ("npm" | "pnpm" | "yarn" | "bun") => { + let Some((script, forwarded)) = script_invocation(pm, args) else { + return Kind::Other; + }; + cwd.and_then(|cwd| package_script(cwd, script)) + .and_then(|body| simple_shell_words(&body)) + .map_or(Kind::Other, |mut words| { + words.extend_from_slice(after_option(forwarded, "--")); + detect_words(&words, None, true) + }) + } + _ => Kind::Other, } - Kind::Other } -/// The package.json script a package-manager call runs, if any. -fn script_name<'a>(pm: &str, rest: &'a [String]) -> Option<&'a str> { - let mut args = rest - .iter() - .map(String::as_str) - .filter(|w| !w.starts_with('-')); - match (pm, args.next()?) { - (_, "run" | "run-script") => args.next(), - ("npm", "start") => Some("start"), - ("npm", _) => None, - (_, script) => Some(script), +fn after_option<'a>(args: &'a [String], option: &str) -> &'a [String] { + if args.first().is_some_and(|arg| arg == option) { + &args[1..] + } else { + args } } +/// The package.json script and its extra args, not arbitrary tokens beyond it. +fn script_invocation<'a>(pm: &str, args: &'a [String]) -> Option<(&'a str, &'a [String])> { + let (subcommand, rest) = args.split_first()?; + let (script, forwarded) = match (pm, subcommand.as_str()) { + (_, "run" | "run-script") => rest.split_first()?, + ("npm", "start") => (subcommand, rest), + ("npm", _) => return None, + _ => (subcommand, rest), + }; + (!script.starts_with('-')).then_some((script, forwarded)) +} + fn package_script(cwd: &Path, script: &str) -> Option { let text = std::fs::read_to_string(cwd.join("package.json")).ok()?; let pkg: serde_json::Value = serde_json::from_str(&text).ok()?; @@ -181,7 +246,7 @@ fn package_script(cwd: &Path, script: &str) -> Option { /// The terminal of an interactive service being started. pub struct Terminal { - pub fifo: PathBuf, + fifo: PendingFifo, /// The PTY slave: the child's stdin. pub stdin: File, master: File, @@ -189,6 +254,26 @@ pub struct Terminal { reader: File, } +struct PendingFifo { + path: PathBuf, + keep: bool, +} + +impl Drop for PendingFifo { + fn drop(&mut self) { + if !self.keep { + let _ = crate::state::remove_file_and_empty_parent(&self.path); + } + } +} + +impl Terminal { + /// The service record now owns cleanup of the FIFO. + pub fn keep_fifo(&mut self) { + self.fifo.keep = true; + } +} + /// Creates the input FIFO of `scope/name` (replacing a stale one) and a PTY /// with echo off. #[cfg(unix)] @@ -211,13 +296,21 @@ pub fn create(store: &Store, scope: &str, name: &str) -> Result { if unsafe { libc::mkfifo(c.as_ptr(), 0o600) } != 0 { return Err(os("create the input FIFO")); } + let fifo = PendingFifo { path, keep: false }; // Read-write: opening does not wait for a writer, and the holder never // reads EOF while nobody is sending. let reader = std::fs::OpenOptions::new() .read(true) .write(true) - .open(&path) - .map_err(|e| TabaError::state(format!("cannot open {}: {e}", path.display())))?; + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .open(&fifo.path) + .map_err(|e| TabaError::state(format!("cannot open {}: {e}", fifo.path.display())))?; + if fifo_identity(&reader).is_none() { + return Err(TabaError::state("cannot identify the newly opened FIFO")); + } + if unsafe { libc::fcntl(reader.as_raw_fd(), libc::F_SETFL, 0) } == -1 { + return Err(os("configure the input FIFO")); + } let fd = unsafe { libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY) }; if fd < 0 { @@ -225,8 +318,8 @@ pub fn create(store: &Store, scope: &str, name: &str) -> Result { } let master = unsafe { File::from_raw_fd(fd) }; let m = master.as_raw_fd(); - unsafe { - libc::fcntl(m, libc::F_SETFD, libc::FD_CLOEXEC); + if unsafe { libc::fcntl(m, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 { + return Err(os("configure the pseudo-terminal")); } if unsafe { libc::grantpt(m) } != 0 || unsafe { libc::unlockpt(m) } != 0 { return Err(os("set up the pseudo-terminal")); @@ -261,7 +354,7 @@ pub fn create(store: &Store, scope: &str, name: &str) -> Result { libc::ioctl(m, libc::TIOCSWINSZ, &ws); } Ok(Terminal { - fifo: path, + fifo, stdin, master, reader, @@ -276,12 +369,14 @@ pub fn create(_store: &Store, _scope: &str, _name: &str) -> Result { /// Starts the holder of the service `spawned` (see the module docs); /// `stderr` is the service's log. #[cfg(unix)] -pub fn spawn_holder(t: Terminal, spawned: &crate::proc::Spawned, stderr: File) -> Result { +pub fn spawn_holder(t: &Terminal, spawned: &crate::proc::Spawned, stderr: File) -> Result { use std::os::fd::AsRawFd; use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; let exe = std::env::current_exe() .map_err(|e| TabaError::state(format!("cannot find the taba executable: {e}")))?; + let identity = fifo_identity(&t.reader) + .ok_or_else(|| TabaError::state("cannot identify the input holder's FIFO"))?; let (m, r) = (t.master.as_raw_fd(), t.reader.as_raw_fd()); let mut cmd = Command::new(exe); cmd.arg("__hold") @@ -313,14 +408,19 @@ pub fn spawn_holder(t: Terminal, spawned: &crate::proc::Spawned, stderr: File) - ) })?; Ok(Input { - fifo: t.fifo, + fifo: t.fifo.path.clone(), holder_pid: holder.pid, holder_start_time: holder.start_time, + fifo_identity: Some(identity), }) } #[cfg(windows)] -pub fn spawn_holder(_t: Terminal, _spawned: &crate::proc::Spawned, _stderr: File) -> Result { +pub fn spawn_holder( + _t: &Terminal, + _spawned: &crate::proc::Spawned, + _stderr: File, +) -> Result { Err(unsupported("run --interactive")) } @@ -341,7 +441,12 @@ pub fn hold(master: i32, fifo: i32, pid: i32, pgid: i32, start_time: u64) -> u8 } } let mut drain = unsafe { File::from_raw_fd(master) }; - let mut fifo = unsafe { File::from_raw_fd(fifo) }; + let fifo_pin = unsafe { File::from_raw_fd(fifo) }; + // Keep the inode pinned even if the forwarding thread exits first. + let Ok(mut fifo) = fifo_pin.try_clone() else { + eprintln!("taba __hold: cannot duplicate the FIFO"); + return 1; + }; let Ok(mut to_master) = drain.try_clone() else { eprintln!("taba __hold: cannot duplicate the terminal"); return 1; @@ -360,6 +465,8 @@ pub fn hold(master: i32, fifo: i32, pid: i32, pgid: i32, start_time: u64) -> u8 Err(_) => break, } } + // Do not keep accepting FIFO writes after forwarding has failed. + std::process::exit(1); }); // With echo off this is usually silent; draining keeps a program that // writes to its terminal from blocking. @@ -382,65 +489,66 @@ pub fn hold(master: i32, fifo: i32, pid: i32, pgid: i32, start_time: u64) -> u8 // ------------------------------------------------------------ writing -/// Writes `bytes` to the service's input without blocking forever on a -/// service that does not read. #[cfg(unix)] -pub fn write(svc: &Service, input: &Input, bytes: &[u8]) -> Result<()> { +fn fifo_identity(file: &File) -> Option<(u64, u64)> { + use std::os::unix::fs::{FileTypeExt, MetadataExt}; + let m = file.metadata().ok()?; + m.file_type().is_fifo().then(|| (m.dev(), m.ino())) +} + +/// One nonblocking write under the same state lock that authorised `svc`. +/// Reopen and verify the descriptor before every attempt, not just the path. +#[cfg(unix)] +fn try_write(store: &Store, svc: &Service, bytes: &[u8]) -> Result { use std::io::{ErrorKind, Write}; - use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; - let path = &input.fifo; - let is_fifo = path + use std::os::unix::fs::OpenOptionsExt; + let input = svc.input.as_ref().ok_or_else(|| no_input(svc))?; + let path = store.input_path(&svc.scope, &svc.name); + let invalid_fifo = || { + TabaError::new( + "E_NO_INPUT", + format!("{}: cannot verify its input FIFO", svc.id()), + ) + .details(json!({ "service": svc.id(), "path": path })) + .next(restart_interactive(svc)) + }; + let identity = input.fifo_identity.ok_or_else(invalid_fifo)?; + use std::os::unix::fs::{FileTypeExt, MetadataExt}; + if !path .symlink_metadata() - .is_ok_and(|m| m.file_type().is_fifo()); - if !is_fifo { - return Err(no_input(svc).details(json!({ "service": svc.id(), "path": path }))); + .is_ok_and(|m| m.file_type().is_fifo() && (m.dev(), m.ino()) == identity) + { + return Err(invalid_fifo()); } let mut f = std::fs::OpenOptions::new() .write(true) - .custom_flags(libc::O_NONBLOCK) - .open(path) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .open(&path) .map_err(|e| match e.raw_os_error() { - // No reader: the holder is gone. Some(libc::ENXIO) if svc.is_running() => holder_gone(svc, input), Some(libc::ENXIO) => not_running(svc), + Some(libc::ENOENT | libc::ELOOP) => invalid_fifo(), _ => TabaError::state(format!("cannot open {}: {e}", path.display())), })?; - let deadline = std::time::Instant::now() + WRITE_TIMEOUT; - let mut rest = bytes; - while !rest.is_empty() { - match f.write(rest) { - Ok(n) => rest = &rest[n..], - Err(e) if e.kind() == ErrorKind::WouldBlock => { - if std::time::Instant::now() >= deadline { - return Err(TabaError::new( - "E_INPUT_BLOCKED", - format!( - "{} is not reading its input; {} of {} bytes were not written", - svc.id(), - rest.len(), - bytes.len() - ), - ) - .details(json!({ "service": svc.id(), "unwritten": rest.len() })) - .next(Next::run( - "check the service", - format!("taba logs {}", svc.id()), - ))); - } - std::thread::sleep(Duration::from_millis(20)); - } - Err(e) if e.kind() == ErrorKind::Interrupted => {} - Err(e) if e.raw_os_error() == Some(libc::EPIPE) => { - return Err(holder_gone(svc, input)); - } - Err(e) => return Err(TabaError::state(format!("cannot write input: {e}"))), - } + if fifo_identity(&f) != Some(identity) { + return Err(invalid_fifo()); + } + if !crate::proc::is_alive(input.holder_pid, input.holder_start_time) { + return Err(holder_gone(svc, input)); + } + if !svc.is_running() { + return Err(not_running(svc)); + } + match f.write(bytes) { + Ok(n) => Ok(n), + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => Ok(0), + Err(e) if e.raw_os_error() == Some(libc::EPIPE) => Err(holder_gone(svc, input)), + Err(e) => Err(TabaError::state(format!("cannot write input: {e}"))), } - Ok(()) } #[cfg(windows)] -pub fn write(_svc: &Service, _input: &Input, _bytes: &[u8]) -> Result<()> { +fn try_write(_store: &Store, _svc: &Service, _bytes: &[u8]) -> Result { Err(unsupported("service input")) } @@ -459,6 +567,13 @@ fn no_input(svc: &Service) -> TabaError { )) } +fn restart_interactive(svc: &Service) -> Next { + Next::run( + "stop the instance, then rerun the original `taba run --interactive ...` command (add --interactive before the service command, replacing --no-interactive if present)", + format!("taba stop {}", svc.id()), + ) +} + fn holder_gone(svc: &Service, input: &Input) -> TabaError { TabaError::new( "E_NO_INPUT", @@ -481,62 +596,135 @@ fn not_running(svc: &Service) -> TabaError { .next(Next::run("read its log", format!("taba logs {}", svc.id()))) } -/// The service `target` names, if `caller` may write to or signal it (the -/// `stop` rules, see the module docs). Records a `--force` override. -pub(crate) fn authorise( - store: &Store, - caller: &Caller, - target: &str, - verb: &str, - force_reason: Option<&str>, - needs_input: bool, -) -> Result { - let (scope, name) = crate::resolve_target(target, caller)?; - let _lock = store.lock()?; - let svc = store - .get(&scope, &name)? - .ok_or_else(|| crate::not_found(&scope, &name))?; - let owner = caller.scope.as_deref() == Some(svc.scope.as_str()); - if owner && force_reason.is_none() { - let cfg = config::Config::load(store.root())?; - lease::touch(store, &cfg, caller, &scope, lease::Access::Mutate, None)?; - } - let live = borrows::live(store, &svc)?; - let exclusive = live.iter().find(|b| b.exclusive); - let holds_exclusive = exclusive.is_some_and(|b| b.owned(caller)); - if force_reason.is_none() { - if !owner && !holds_exclusive { - return Err(crate::not_owner(caller, &svc, verb)); +#[derive(Clone, Copy)] +struct Access<'a> { + store: &'a Store, + caller: &'a Caller, + target: &'a str, + verb: &'a str, + force_reason: Option<&'a str>, +} + +impl Access<'_> { + /// The current service, under the lock held by the operation. With an + /// expected instance, never retarget an attachment or a partial write. + fn authorise( + &self, + _lock: &crate::state::Lock, + expected: Option<&Service>, + audit: bool, + ) -> Result { + let Self { + store, + caller, + target, + verb, + force_reason, + } = *self; + let (scope, name) = crate::resolve_target(target, caller)?; + let svc = store + .get(&scope, &name)? + .ok_or_else(|| crate::not_found(&scope, &name))?; + if expected.is_some_and(|old| { + (old.pid, old.pgid, old.start_time) != (svc.pid, svc.pgid, svc.start_time) + || old.instance() != svc.instance() + || old.input != svc.input + }) { + return Err(TabaError::new( + "E_CONFLICT", + format!("{} changed; attach or send again", svc.id()), + )); } - if let Some(b) = exclusive.filter(|_| !holds_exclusive) { - return Err(borrows::locked(&svc, b)); + let owner = caller.scope.as_deref() == Some(svc.scope.as_str()); + if owner && force_reason.is_none() { + let cfg = config::Config::load(store.root())?; + lease::touch(store, &cfg, caller, &scope, lease::Access::Mutate, None)?; } + let live = borrows::live(store, &svc)?; + let exclusive = live.iter().find(|b| b.exclusive); + let holds_exclusive = exclusive.is_some_and(|b| b.owned(caller)); + if force_reason.is_none() { + if !owner && !holds_exclusive { + return Err(crate::not_owner(caller, &svc, verb)); + } + if let Some(b) = exclusive.filter(|_| !holds_exclusive) { + return Err(borrows::locked(&svc, b)); + } + } + if let Some(op) = store.live_op(&scope, &name)? { + return Err(crate::busy(&svc.id(), &op)); + } + if !svc.is_running() { + return Err(not_running(&svc)); + } + if let Some(reason) = force_reason.filter(|_| audit) { + let overrode: &[&str] = if owner || holds_exclusive { + &[] + } else { + &["E_NOT_OWNER"] + }; + crate::record_force( + store, + &format!("force_{verb}"), + caller, + &svc, + reason, + overrode, + )?; + } + Ok(svc) } - if let Some(op) = store.live_op(&scope, &name)? { - return Err(crate::busy(&svc.id(), &op)); - } - if !svc.is_running() { - return Err(not_running(&svc)); - } - if needs_input && svc.input.is_none() { - return Err(no_input(&svc)); + + fn attach(&self, expected: Option<&Service>) -> Result { + let lock = self.store.lock()?; + let svc = self.authorise(&lock, expected, true)?; + svc.input.as_ref().ok_or_else(|| no_input(&svc))?; + Ok(svc) } - if let Some(reason) = force_reason { - let overrode: &[&str] = if owner || holds_exclusive { - &[] - } else { - &["E_NOT_OWNER"] - }; - crate::record_force( - store, - &format!("force_{verb}"), - caller, - &svc, - reason, - overrode, - )?; + + fn write(&self, expected: Option<&Service>, bytes: &[u8], mut audit: bool) -> Result { + let deadline = std::time::Instant::now() + WRITE_TIMEOUT; + let mut rest = bytes; + let mut pinned = None; + loop { + let (svc, n) = { + let lock = self.store.lock()?; + let svc = self.authorise(&lock, expected.or(pinned.as_ref()), audit)?; + let n = if rest.is_empty() { + 0 + } else { + try_write(self.store, &svc, rest)? + }; + (svc, n) + }; + rest = &rest[n..]; + if rest.is_empty() { + svc.input.as_ref().ok_or_else(|| no_input(&svc))?; + return Ok(svc); + } + if std::time::Instant::now() >= deadline { + return Err(TabaError::new( + "E_INPUT_BLOCKED", + format!( + "{} is not reading its input; {} of {} bytes were not written", + svc.id(), + rest.len(), + bytes.len() + ), + ) + .details(json!({ "service": svc.id(), "unwritten": rest.len() })) + .next(Next::run( + "check the service", + format!("taba logs {}", svc.id()), + ))); + } + pinned = Some(svc); + audit = false; + if n == 0 { + std::thread::sleep(Duration::from_millis(20)); + } + } } - Ok(svc) } // ------------------------------------------------------------ send @@ -605,9 +793,14 @@ pub fn cmd_send(a: SendArgs) -> Result { } let caller = scope::resolve(a.scope, a.agent)?; let store = Store::open()?; - let svc = authorise(&store, &caller, &a.target, "send", reason.as_deref(), true)?; - let input = svc.input.clone().expect("checked"); - write(&svc, &input, &bytes)?; + let access = Access { + store: &store, + caller: &caller, + target: &a.target, + verb: "send", + force_reason: reason.as_deref(), + }; + let svc = access.write(None, &bytes, true)?; let mut body = json!({ "service": svc.id(), "bytes": bytes.len(), @@ -661,15 +854,16 @@ pub fn cmd_signal(a: SignalArgs) -> Result { } let caller = scope::resolve(a.scope, a.agent)?; let store = Store::open()?; - let svc = authorise( - &store, - &caller, - &a.target, - "signal", - reason.as_deref(), - false, - )?; - send_signal(&svc, a.signal)?; + let access = Access { + store: &store, + caller: &caller, + target: &a.target, + verb: "signal", + force_reason: reason.as_deref(), + }; + let lock = store.lock()?; + let svc = access.authorise(&lock, None, true)?; + send_signal(&svc, a.signal, false)?; let mut body = json!({ "service": svc.id(), "signal": a.signal.name(), @@ -693,17 +887,96 @@ pub fn cmd_signal(a: SignalArgs) -> Result { /// Signals the service's main process only: the default action of SIGUSR1 /// and SIGUSR2 is to terminate, so the rest of the group is left alone. #[cfg(unix)] -fn send_signal(svc: &Service, sig: Signal) -> Result<()> { +fn send_signal(svc: &Service, sig: Signal, flutter: bool) -> Result<()> { + // Automatic Flutter signals require a verified handler and stable + // process handle. On macOS, the only supported Flutter path is input. + #[cfg(target_os = "macos")] + if flutter { + let key = if sig == Signal::Usr2 { "R" } else { "r" }; + let mut error = TabaError::new( + "E_NO_RELOAD", + format!("{}: automatic Flutter reload and restart are disabled on macOS; use interactive r (reload) or R (restart) via taba attach or taba send", svc.id()), + ) + .details(json!({ "service": svc.id(), "command": svc.template() })) + .next(Next::run( + "send the Flutter key if the service takes input", + format!("taba send {} --key {key}", svc.id()), + )); + // No input and input without an identity both require a restart. + // Only input with an identity skips that advice. + if svc.input.as_ref().is_none_or(|i| i.fifo_identity.is_none()) { + error = error.next(restart_interactive(svc)); + } + return Err(error); + } let n = match sig { Signal::Usr1 => libc::SIGUSR1, Signal::Usr2 => libc::SIGUSR2, Signal::Hup => libc::SIGHUP, }; - // Re-verify the identity right before signalling, as `stop` does. if !crate::proc::is_alive(svc.pid, svc.start_time) { return Err(not_running(svc)); } - if unsafe { libc::kill(svc.pid, n) } != 0 { + // On Linux, signal through a stable handle, never a recycled PID. + #[cfg(target_os = "linux")] + let pidfd = { + use std::os::fd::FromRawFd; + let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, svc.pid, 0u32) }; + if fd >= 0 { + Some(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as i32) }) + } else { + let e = std::io::Error::last_os_error(); + match e.raw_os_error() { + Some(libc::ESRCH) => return Err(not_running(svc)), + Some(libc::ENOSYS | libc::EPERM | libc::EACCES) if flutter => { + return Err(no_reload( + svc, + "cannot pin the Flutter signal target on this system", + )); + } + // Keep explicit `signal` available on older kernels. + Some(libc::ENOSYS | libc::EPERM | libc::EACCES) => None, + _ => { + return Err(TabaError::new( + "E_SIGNAL_FAILED", + format!("{}: cannot pin its process: {e}", svc.id()), + )); + } + } + } + }; + #[cfg(target_os = "linux")] + if flutter && !verified_flutter_leader(svc.pid, n) { + return Err(no_reload( + svc, + "the service leader is not a verified Flutter signal target", + ) + .next(restart_interactive(svc))); + } + if !crate::proc::is_alive(svc.pid, svc.start_time) { + return Err(not_running(svc)); + } + #[cfg(target_os = "linux")] + let sent = { + use std::os::fd::AsRawFd; + if let Some(pidfd) = &pidfd { + unsafe { + libc::syscall( + libc::SYS_pidfd_send_signal, + pidfd.as_raw_fd(), + n, + std::ptr::null::(), + 0u32, + ) + } + } else { + unsafe { libc::kill(svc.pid, n) }.into() + } + }; + // macOS has no pidfd equivalent: recheck the leader immediately before kill. + #[cfg(target_os = "macos")] + let sent = unsafe { libc::kill(svc.pid, n) }; + if sent != 0 { let e = std::io::Error::last_os_error(); return Err(TabaError::new( "E_SIGNAL_FAILED", @@ -715,10 +988,73 @@ fn send_signal(svc: &Service, sig: Signal) -> Result<()> { } #[cfg(windows)] -fn send_signal(_svc: &Service, _sig: Signal) -> Result<()> { +fn send_signal(_svc: &Service, _sig: Signal, _flutter: bool) -> Result<()> { Err(unsupported("taba signal")) } +/// Flutter's Unix SDK launcher execs Dart. Recognise its tool only in +/// Dart's script position, or a direct native Flutter leader, not a shell, +/// package manager or FVM parent. Never search descendants for a target. +#[cfg(target_os = "linux")] +fn verified_flutter_leader(pid: i32, sig: i32) -> bool { + let Some(argv) = crate::proc::argv(pid) else { + return false; + }; + let Some((program, args)) = argv.split_first() else { + return false; + }; + let run_args = match base(program).as_str() { + "flutter" => args, + "dart" => { + let vm_options = args + .iter() + .take_while(|s| { + s.starts_with("--packages=") + || s.starts_with("--observe=") + || matches!(s.as_str(), "--enable-asserts" | "--disable-dart-dev") + }) + .count(); + let Some((script, rest)) = args[vm_options..].split_first() else { + return false; + }; + if Path::new(script).file_name().and_then(|s| s.to_str()) + != Some("flutter_tools.snapshot") + { + return false; + } + rest + } + _ => return false, + }; + if !flutter_run(run_args) + || run_args + .iter() + .any(|a| matches!(a.as_str(), "--machine" | "--no-hot")) + { + return false; + } + // USR1/2 terminate by default. The correct executable alone does + // not mean it has installed its reload handler yet. + std::fs::read_to_string(format!("/proc/{pid}/status")) + .ok() + .and_then(|status| { + let mask = status + .lines() + .find_map(|line| line.strip_prefix("SigCgt:"))?; + u64::from_str_radix(mask.trim(), 16).ok() + }) + .is_some_and(|mask| mask & (1 << (sig - 1)) != 0) +} + +fn no_reload(svc: &Service, why: &str) -> TabaError { + TabaError::new("E_NO_RELOAD", format!("{}: {why}", svc.id())) + .details(json!({ "service": svc.id(), "command": svc.template() })) + .next(Next::run( + "if it takes input, send its reload key directly", + format!("taba send {} --key r", svc.id()), + )) +} + pub struct ReloadArgs { pub target: String, pub restart: bool, @@ -729,44 +1065,30 @@ pub struct ReloadArgs { } /// `taba reload`: the most reliable reload for the kind of dev server. -/// `flutter run`: SIGUSR1 (hot reload) or SIGUSR2 (`--restart`, hot -/// restart), which needs no stdin. Vite: `r` + Enter on stdin (restarts the +/// Linux `flutter run`: SIGUSR1 (hot reload) or SIGUSR2 (`--restart`, hot +/// restart), which needs no stdin. On macOS, use Flutter's keys via attach +/// or send instead. Vite: `r` + Enter on stdin (restarts the /// dev server; open pages reload), so it needs `--interactive`. pub fn cmd_reload(a: ReloadArgs) -> Result { let reason = crate::check_force(a.force, a.reason)?; let caller = scope::resolve(a.scope, a.agent)?; let store = Store::open()?; - let (scope, name) = crate::resolve_target(&a.target, &caller)?; - let peek = store - .get(&scope, &name)? - .ok_or_else(|| crate::not_found(&scope, &name))?; - let kind = detect(peek.template(), &peek.cwd); - if kind == Kind::Other { - return Err(TabaError::new( - "E_NO_RELOAD", - format!( - "{} is not a dev server taba knows how to reload (flutter run, vite)", - peek.id() - ), - ) - .details(json!({ "service": peek.id(), "command": peek.template() })) - .next(Next::run( - "send its reload key yourself", - format!("taba send {} --key r", peek.id()), - ))); - } if cfg!(windows) { return Err(unsupported("taba reload")); } - let id = peek.id(); - let svc = authorise( - &store, - &caller, - &id, - "reload", - reason.as_deref(), - kind == Kind::Vite, - )?; + let access = Access { + store: &store, + caller: &caller, + target: &a.target, + verb: "reload", + force_reason: reason.as_deref(), + }; + let lock = store.lock()?; + let svc = access.authorise(&lock, None, true)?; + let id = svc.id(); + let kind = svc + .dev_kind + .unwrap_or_else(|| detect_words(&svc.command, None, true)); let (method, text) = match kind { Kind::Flutter => { let sig = if a.restart { @@ -774,7 +1096,7 @@ pub fn cmd_reload(a: ReloadArgs) -> Result { } else { Signal::Usr1 }; - send_signal(&svc, sig)?; + send_signal(&svc, sig, true)?; let what = if a.restart { "hot restart" } else { @@ -789,9 +1111,16 @@ pub fn cmd_reload(a: ReloadArgs) -> Result { ), ) } - _ => { - let input = svc.input.clone().expect("checked"); - write(&svc, &input, b"r\n")?; + Kind::VitePreview => return Err(no_reload(&svc, "Vite preview does not support reload")), + Kind::Other => { + return Err( + no_reload(&svc, "not a supported dev server (flutter run or Vite dev)") + .next(restart_interactive(&svc)), + ); + } + Kind::Vite => { + drop(lock); + access.write(Some(&svc), b"r\n", false)?; ( "stdin".to_string(), format!("{id}: sent r (Vite restarts the dev server; open pages reload)"), @@ -831,28 +1160,19 @@ pub fn cmd_attach(a: AttachArgs) -> Result> { } let caller = scope::resolve(a.scope, a.agent)?; let store = Store::open()?; - let svc = authorise( - &store, - &caller, - &a.target, - "attach", - reason.as_deref(), - true, - )?; + let access = Access { + store: &store, + caller: &caller, + target: &a.target, + verb: "attach", + force_reason: reason.as_deref(), + }; + let svc = access.attach(None)?; let (log, pos) = open_tail(&svc)?; if std::io::stdin().is_terminal() { - view( - &store, - &caller, - &svc, - log, - pos, - true, - false, - reason.as_deref(), - ) + view(access, &svc, log, pos, true, false) } else { - forward_pipe(&svc, log, pos) + forward_pipe(access, &svc, log, pos) }?; Ok(None) } @@ -860,9 +1180,16 @@ pub fn cmd_attach(a: AttachArgs) -> Result> { /// `taba ui`: `i` on an interactive service. Input mode right away; Ctrl+] /// returns to the TUI. pub(crate) fn attach_from_ui(store: &Store, caller: &Caller, target: &str) -> Result<()> { - let svc = authorise(store, caller, target, "attach", None, true)?; + let access = Access { + store, + caller, + target, + verb: "attach", + force_reason: None, + }; + let svc = access.attach(None)?; let (log, pos) = open_tail(&svc)?; - view(store, caller, &svc, log, pos, true, true, None) + view(access, &svc, log, pos, true, true) } /// `taba logs -f` on a terminal, for an interactive service: read-only @@ -871,7 +1198,15 @@ pub(crate) fn follow(store: &Store, caller: &Caller, svc: &Service, log: File) - use std::io::Seek; let mut log = log; let pos = log.stream_position()?; - view(store, caller, svc, log, pos, false, false, None) + let id = svc.id(); + let access = Access { + store, + caller, + target: &id, + verb: "attach", + force_reason: None, + }; + view(access, svc, log, pos, false, false) } fn open_tail(svc: &Service) -> Result<(File, u64)> { @@ -921,16 +1256,13 @@ fn banner(id: &str, typing: bool, leave_to_ui: bool) { /// each key to the service. `i` enters input mode (if the caller may type), /// Ctrl+] leaves it (or the view, with `leave_on_detach`), `q` / Ctrl+C /// quits. The service keeps running. -#[allow(clippy::too_many_arguments)] fn view( - store: &Store, - caller: &Caller, + access: Access<'_>, svc: &Service, mut log: File, mut pos: u64, mut typing: bool, leave_on_detach: bool, - force_reason: Option<&str>, ) -> Result<()> { use std::io::{Read, Seek, SeekFrom, Write}; let id = svc.id(); @@ -967,11 +1299,10 @@ fn view( Some(i) => (&bytes[..i], true), None => (&bytes[..], false), }; - if !send.is_empty() { - let input = svc.input.as_ref().expect("interactive"); - if let Err(e) = write(svc, input, send) { - status(&e.message); - } + if !send.is_empty() + && let Err(e) = access.write(Some(svc), send, false) + { + status(&e.message); } if detach { if leave_on_detach { @@ -985,7 +1316,7 @@ fn view( for &b in &bytes { match b { b'i' => { - match authorise(store, caller, &id, "attach", force_reason, true) { + match access.attach(Some(svc)) { Ok(_) => { typing = true; banner(&id, typing, leave_on_detach); @@ -1008,9 +1339,8 @@ fn view( /// `taba attach` from a pipe: forwards stdin until EOF, then shows the log /// a little longer so the answer to the last input is not cut off. -fn forward_pipe(svc: &Service, mut log: File, mut pos: u64) -> Result<()> { +fn forward_pipe(access: Access<'_>, svc: &Service, mut log: File, mut pos: u64) -> Result<()> { use std::io::{Read, Seek, SeekFrom, Write}; - let input = svc.input.clone().expect("interactive"); eprintln!( "taba: attached to {} (EOF detaches; the service keeps running)", svc.id() @@ -1045,7 +1375,9 @@ fn forward_pipe(svc: &Service, mut log: File, mut pos: u64) -> Result<()> { match read_stdin(Duration::from_millis(50))? { None => {} Some(bytes) if bytes.is_empty() => linger = Some(std::time::Instant::now()), - Some(bytes) => write(svc, &input, &bytes)?, + Some(bytes) => { + access.write(Some(svc), &bytes, false)?; + } } }; match outcome { @@ -1162,18 +1494,50 @@ mod tests { assert_eq!(d("vite"), Kind::Vite); assert_eq!(d("npx vite --port 5173"), Kind::Vite); assert_eq!(d("node node_modules/vite/bin/vite.js"), Kind::Vite); - assert_eq!(d("vite preview"), Kind::Vite); + assert_eq!(d("vite preview"), Kind::VitePreview); + assert_eq!(d("vite --port 4173 preview"), Kind::VitePreview); + assert_eq!(d("vite --config preview"), Kind::Vite); + assert_eq!(d("vite --host preview"), Kind::Vite); assert_eq!(d("vite build"), Kind::Other); assert_eq!(d("python3 -m http.server"), Kind::Other); assert_eq!(d("node vite.config.ts"), Kind::Other); - // A shell command line is split into words. + assert_eq!(d("echo vite"), Kind::Other); + assert_eq!(d("node server.js vite"), Kind::Other); + assert_eq!(d("npx echo vite"), Kind::Other); + assert_eq!( + detect(&["echo".into(), "flutter run".into()], none), + Kind::Other + ); assert_eq!( detect( - &["sh".into(), "-c".into(), "cd app && flutter run".into()], + &["/opt/tools with spaces/flutter".into(), "run".into()], + none + ), + Kind::Flutter + ); + assert_eq!( + detect(&["flutter".into(), "run test".into()], none), + Kind::Other + ); + // Only an actual shell payload is parsed, with quotes preserved. + assert_eq!( + detect( + &[ + "sh".into(), + "-c".into(), + "exec '/opt/my tools/flutter' run".into() + ], none ), Kind::Flutter ); + assert_eq!( + detect( + &["sh".into(), "-c".into(), "cd app && flutter run".into()], + none + ), + Kind::Other + ); } #[test] @@ -1181,7 +1545,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); std::fs::write( dir.path().join("package.json"), - r#"{"scripts":{"dev":"vite --host","build":"vite build","start":"vite","serve":"node server.js"}}"#, + r#"{"scripts":{"dev":"vite --host","preview":"vite preview","build":"vite build","start":"vite","serve":"node server.js","info":"echo vite"}}"#, ) .unwrap(); let d = |s: &str| detect(&words(s), dir.path()); @@ -1194,5 +1558,8 @@ mod tests { assert_eq!(d("npm run serve"), Kind::Other); assert_eq!(d("npm install"), Kind::Other); assert_eq!(d("npm run missing"), Kind::Other); + assert_eq!(d("npm run info"), Kind::Other); + assert_eq!(d("npm run preview"), Kind::VitePreview); + assert_eq!(d("npm start -- preview"), Kind::VitePreview); } } diff --git a/src/main.rs b/src/main.rs index 34fe3ab..a505ef7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1223,6 +1223,35 @@ struct RunArgs { prompt: bool, } +/// Until the service is published, this invocation owns both processes. +/// Runs before the state lock and pending terminal are dropped on failure. +struct PendingStart { + service: proc::Spawned, + holder: Option<(i32, u64)>, + published: bool, +} + +impl Drop for PendingStart { + fn drop(&mut self) { + if self.published { + return; + } + if let Some((pid, start)) = self.holder + && proc::is_alive(pid, start) + { + let _ = proc::stop_group(pid, pid, start, Duration::from_secs(2)); + } + let proc::Spawned { + pid, + pgid, + start_time, + } = self.service; + if proc::group_is_ours(pid, pgid, start_time) { + let _ = proc::stop_group(pid, pgid, start_time, Duration::from_secs(2)); + } + } +} + fn cmd_run(mut a: RunArgs) -> Result { let command = std::mem::take(&mut a.command); let spec = match runform::command_spec(a.shape, command.clone(), &a.raw) { @@ -1464,7 +1493,7 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { let log_offset = log.metadata()?.len(); let log_err = log.try_clone()?; - let terminal = if interactive { + let mut terminal = if interactive { Some(input::create(&store, &scope, &name)?) } else { None @@ -1513,23 +1542,22 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { start_failed(format!("{id} exited immediately; see taba logs {id}")) } })?; + let mut pending = PendingStart { + service: spawned, + holder: None, + published: false, + }; // Interactive: the holder keeps the terminal open and feeds it input. - let input = match (terminal, holder_err) { - (Some(t), Some(err)) => match input::spawn_holder(t, &spawned, err) { - Ok(i) => Some(i), - Err(e) => { - let _ = proc::stop_group( - spawned.pid, - spawned.pgid, - spawned.start_time, - Duration::from_secs(2), - ); - return Err(e); - } - }, + let input = match (terminal.as_ref(), holder_err) { + (Some(t), Some(err)) => { + let input = input::spawn_holder(t, &spawned, err)?; + pending.holder = Some((input.holder_pid, input.holder_start_time)); + Some(input) + } _ => None, }; let pid = spawned.pid; + let kind = input::detect(&command, &dir); let mut svc = Service { scope: scope.clone(), name: name.clone(), @@ -1553,13 +1581,31 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { stop_requested_at: None, discovered_ports: Vec::new(), input, + dev_kind: (kind != input::Kind::Other).then_some(kind), }; - store.put(&svc)?; - if let Some(borrow) = &delegation { - borrows::rebind(&store, borrow, &svc)?; - } let op = if replacing { "replace" } else { "start" }; - store.put_op(&scope, &name, &OpLock::mine(op, &caller.agent))?; + let publish = || -> Result<()> { + store.put_op(&scope, &name, &OpLock::mine(op, &caller.agent))?; + store.put(&svc)?; + if let (Some(borrow), Some(previous)) = (&delegation, &existing) + && let Err(e) = borrows::rebind(&store, borrow, &svc) + { + let _ = borrows::rebind(&store, borrow, previous); + return Err(e); + } + Ok(()) + }; + if let Err(e) = publish() { + let restored = store.rollback_start(&svc, existing.as_ref()); + let _ = store.release_op(&scope, &name); + restored?; + return Err(e); + } + pending.published = true; + if let Some(t) = &mut terminal { + t.keep_fifo(); + } + drop(terminal); // The port is reserved by the record now; wait without the global lock. drop(lock); @@ -2859,6 +2905,7 @@ mod stop_tests { stop_requested_at: None, discovered_ports: Vec::new(), input: None, + dev_kind: None, }) .unwrap(); } diff --git a/src/proc/unix.rs b/src/proc/unix.rs index dd33f87..14230d6 100644 --- a/src/proc/unix.rs +++ b/src/proc/unix.rs @@ -124,10 +124,15 @@ pub fn spawn_detached(mut cmd: Command) -> Result { Ok(()) }); } - let child = cmd.spawn().map_err(SpawnError::Start)?; + let mut child = cmd.spawn().map_err(SpawnError::Start)?; let pid = child.id() as i32; - drop(child); - let info = info(pid).ok_or(SpawnError::Vanished)?; + let Some(info) = info(pid) else { + // The direct child has not been reaped and its PID cannot have + // been reused. Do not leave it running without an identity record. + let _ = child.kill(); + let _ = child.wait(); + return Err(SpawnError::Vanished); + }; Ok(Spawned { pid, pgid: pid, diff --git a/src/state.rs b/src/state.rs index 3d09522..07e0c86 100644 --- a/src/state.rs +++ b/src/state.rs @@ -150,6 +150,10 @@ pub struct Service { /// forwards it to the service's terminal (see `input.rs`). #[serde(default, skip_serializing_if = "Option::is_none")] pub input: Option, + /// Detected at launch, so editing a package script doesn't change what + /// `reload` thinks the running service is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dev_kind: Option, } /// The input side of an interactive service. Its stdin is a pseudo-terminal; @@ -161,6 +165,10 @@ pub struct Input { pub holder_pid: i32, /// Holder start time, in the units of `Service::start_time`. pub holder_start_time: u64, + /// The FIFO opened by this holder (device and inode). Older records + /// cannot prove this identity and must be restarted before taking input. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fifo_identity: Option<(u64, u64)>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -503,6 +511,26 @@ impl Store { write_json(&self.record_path(&svc.scope, &svc.name), svc) } + /// Roll back a failed publish, including errors after the record rename. + /// Leave claims and logs in place. Call under the global lock. + pub(crate) fn rollback_start( + &self, + svc: &Service, + previous: Option<&Service>, + ) -> io::Result<()> { + if self + .get(&svc.scope, &svc.name)? + .is_some_and(|cur| cur.instance() == svc.instance()) + { + if let Some(previous) = previous { + self.put(previous)?; + } else { + remove_file_and_empty_parent(&self.record_path(&svc.scope, &svc.name))?; + } + } + Ok(()) + } + /// The operation lock of `scope/name`, if a record exists (it may be stale). pub fn get_op(&self, scope: &str, name: &str) -> io::Result> { read_json(&self.op_path(scope, name)) diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 5965e77..97b0eab 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -329,6 +329,7 @@ mod tests { stop_requested_at: None, discovered_ports: Vec::new(), input: None, + dev_kind: None, }) .unwrap(); } diff --git a/tests/input.rs b/tests/input.rs index 8e1b7dd..a16316a 100644 --- a/tests/input.rs +++ b/tests/input.rs @@ -68,14 +68,17 @@ mod unix { .to_string() } - /// The holder pid from the service record. - fn holder_pid(f: &Fixture, svc: &Value) -> i32 { - let rec = f - .home() + fn record_path(f: &Fixture, svc: &Value) -> std::path::PathBuf { + f.home() .join("services") .join(svc["scope"].as_str().unwrap()) - .join(format!("{}.json", svc["name"].as_str().unwrap())); - let rec: Value = serde_json::from_slice(&std::fs::read(rec).unwrap()).unwrap(); + .join(format!("{}.json", svc["name"].as_str().unwrap())) + } + + /// The holder pid from the service record. + fn holder_pid(f: &Fixture, svc: &Value) -> i32 { + let rec: Value = + serde_json::from_slice(&std::fs::read(record_path(f, svc)).unwrap()).unwrap(); rec["input"]["holder_pid"].as_i64().expect("holder_pid") as i32 } @@ -85,13 +88,17 @@ mod unix { unsafe { libc::kill(pid, 0) == 0 } } - /// An executable `name` in a fresh bin dir, running the Python `body`. fn fake_tool(f: &Fixture, name: &str, body: &str) -> String { + script_tool(f, name, "/usr/bin/env python3", body) + } + + /// An executable script in the fixture's private bin directory. + fn script_tool(f: &Fixture, name: &str, interpreter: &str, body: &str) -> String { use std::os::unix::fs::PermissionsExt; let dir = f.root.join("bin"); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join(name); - std::fs::write(&path, format!("#!/usr/bin/env python3\n{body}")).unwrap(); + std::fs::write(&path, format!("#!{interpreter}\n{body}")).unwrap(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); path.to_str().unwrap().to_string() } @@ -196,6 +203,91 @@ mod unix { assert!(!fifo.exists()); } + #[test] + fn a_piped_attachment_rechecks_permission_for_each_input() { + struct ReleaseOnDrop<'a> { + fixture: &'a Fixture, + id: &'a str, + armed: bool, + } + + impl Drop for ReleaseOnDrop<'_> { + fn drop(&mut self) { + if self.armed { + // Release only this fixture's borrow before its owner stops the service. + let _ = self + .fixture + .cmd(&self.fixture.wt_b, &["release", self.id]) + .output(); + } + } + } + + let f = Fixture::new("input-attach-permission"); + let svc = start(&f, &f.wt_a, "echo", true); + let id = svc["service"].as_str().unwrap(); + let mut child = f + .cmd(&f.wt_a, &["attach", id]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(b"first line\n").unwrap(); + wait_log(&f, &f.wt_a, id, "got:first line"); + let mut cleanup = ReleaseOnDrop { + fixture: &f, + id, + armed: true, + }; + let borrow = f.taba(&f.wt_b, &["borrow", id, "--mut"]); + assert_eq!(exit(&borrow), 0, "{}", text(&borrow)); + stdin.write_all(b"second line\n").unwrap(); + drop(stdin); + let out = child.wait_with_output().unwrap(); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert!(!log(&f, &f.wt_a, id).contains("got:second line")); + let release = f.taba(&f.wt_b, &["release", id]); + assert_eq!(exit(&release), 0, "{}", text(&release)); + cleanup.armed = false; + } + + fn assert_interactive_restart(out: &std::process::Output, id: &str) { + let v = json(out); + let next = v["error"]["next"].as_array().unwrap(); + assert!( + next.iter().any(|action| { + action["command"] == format!("taba stop {id}") + && action["do"] + .as_str() + .unwrap() + .contains("taba run --interactive") + }), + "{}", + text(out) + ); + } + + #[test] + fn legacy_input_is_refused_with_restart_instructions() { + let f = Fixture::new("input-legacy"); + let service = start(&f, &f.wt_a, "echo", true); + let id = service["service"].as_str().unwrap(); + let path = record_path(&f, &service); + let mut record: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + record["input"] + .as_object_mut() + .unwrap() + .remove("fifo_identity") + .unwrap(); + std::fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap(); + let out = f.taba(&f.wt_a, &["send", id, "legacy input", "--json"]); + assert_eq!(code(&out), "E_NO_INPUT"); + assert_interactive_restart(&out, id); + assert!(!log(&f, &f.wt_a, id).contains("got:legacy input")); + } + #[test] fn a_service_without_input_is_refused() { let f = Fixture::new("input-none"); @@ -277,24 +369,39 @@ mod unix { wait_log(&f, &f.wt_a, id, "got:owner"); } - /// Like `flutter run`: keys in cbreak mode, hot reload on SIGUSR1 and - /// hot restart on SIGUSR2. + /// Like Flutter: single-key input and an observable receipt of each signal. const FAKE_FLUTTER: &str = r#" -import os, signal, sys, tty -signal.signal(signal.SIGUSR1, lambda *a: print("reloaded", flush=True)) -signal.signal(signal.SIGUSR2, lambda *a: print("restarted", flush=True)) -print("args=" + " ".join(sys.argv[1:]), flush=True) -if sys.stdin.isatty(): - tty.setcbreak(0) -print("Flutter run key commands.", flush=True) -while True: - c = os.read(0, 1) - if not c: - print("EOF", flush=True) - signal.pause() - print("key:" + c.decode(), flush=True) +trap 'printf "signal:USR1\n"' USR1 +trap 'printf "signal:USR2\n"' USR2 +printf 'Flutter run key commands.\n' +if [[ -t 0 ]]; then + while :; do + if IFS= read -r -n 1 key; then + printf 'key:%s\n' "$key" + fi + done +else + printf 'EOF\n' + while :; do /bin/sleep 1; done +fi "#; + // Use system Bash on both Unix platforms. Preserve Dart's argv layout + // without renaming/symlinking a Python executable or depending on PATH. + fn flutter_launcher(f: &Fixture) -> String { + let flutter = script_tool( + f, + "flutter", + "/bin/bash", + r#" +bin_dir=${0%/*} +exec -a "$bin_dir/dart" /bin/bash "$bin_dir/flutter_tools.snapshot" "$@" +"#, + ); + std::fs::write(f.root.join("bin/flutter_tools.snapshot"), FAKE_FLUTTER).unwrap(); + flutter + } + /// Like `vite`: line-based shortcuts. const FAKE_VITE: &str = r#" import sys @@ -305,9 +412,9 @@ for line in sys.stdin: "#; #[test] - fn flutter_run_is_interactive_by_default_and_reloads_by_signal() { + fn flutter_reload_respects_the_platform_policy() { let f = Fixture::new("input-flutter"); - let flutter = fake_tool(&f, "flutter", FAKE_FLUTTER); + let flutter = flutter_launcher(&f); let out = f.taba( &f.wt_a, &[ @@ -335,22 +442,56 @@ for line in sys.stdin: assert_eq!(exit(&f.taba(&f.wt_a, &["send", &id, "--key", "r"])), 0); wait_log(&f, &f.wt_a, &id, "key:r"); - let out = f.taba(&f.wt_a, &["reload", &id, "--json"]); - assert_eq!(exit(&out), 0, "{}", text(&out)); - let v = json(&out); - assert_eq!(v["kind"], "flutter"); - assert_eq!(v["method"], "SIGUSR1"); - wait_log(&f, &f.wt_a, &id, "reloaded"); - let out = f.taba(&f.wt_a, &["reload", &id, "--restart", "--json"]); - assert_eq!(exit(&out), 0, "{}", text(&out)); - assert_eq!(json(&out)["method"], "SIGUSR2"); - wait_log(&f, &f.wt_a, &id, "restarted"); + let reload = f.taba(&f.wt_a, &["reload", &id, "--json"]); + let restart = f.taba(&f.wt_a, &["reload", &id, "--restart", "--json"]); + #[cfg(target_os = "linux")] + { + assert_eq!(exit(&reload), 0, "{}", text(&reload)); + let v = json(&reload); + assert_eq!(v["kind"], "flutter"); + assert_eq!(v["method"], "SIGUSR1"); + wait_log(&f, &f.wt_a, &id, "signal:USR1"); + assert_eq!(exit(&restart), 0, "{}", text(&restart)); + assert_eq!(json(&restart)["method"], "SIGUSR2"); + wait_log(&f, &f.wt_a, &id, "signal:USR2"); + } + #[cfg(target_os = "macos")] + { + for (out, key) in [(&reload, "r"), (&restart, "R")] { + assert_eq!(exit(out), 3, "{}", text(out)); + let v = json(out); + assert_eq!(v["error"]["code"], "E_NO_RELOAD"); + assert!( + v["error"]["message"] + .as_str() + .unwrap() + .contains("taba attach") + ); + assert_eq!( + v["error"]["next"][0]["command"], + format!("taba send {id} --key {key}") + ); + } + // Both keys still reach the same live instance. The fixture + // logs either signal before consuming the next terminal input. + for key in ["r", "R"] { + let out = f.taba(&f.wt_a, &["send", &id, "--key", key, "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["instance"], row["instance"]); + } + wait_log(&f, &f.wt_a, &id, "key:R"); + let log = log(&f, &f.wt_a, &id); + assert!(!log.contains("signal:USR"), "{log}"); + let live = f.ps(&[]).into_iter().find(|r| r["service"] == id).unwrap(); + assert_eq!(live["status"], "running"); + assert_eq!(live["instance"], row["instance"]); + } // Another scope may not reload it. let out = f.taba(&f.wt_b, &["reload", &id, "--json"]); assert_eq!(code(&out), "E_NOT_OWNER"); - // --no-interactive: stdin is /dev/null (EOF), but reload still works. + // --no-interactive: stdin is /dev/null (EOF), so manual input is refused. let out = f.taba( &f.wt_a, &[ @@ -371,6 +512,12 @@ for line in sys.stdin: assert_eq!(json(&out)["interactive"], false); let plain = format!("{}/plain", f.scope_of(&f.wt_a)); wait_log(&f, &f.wt_a, &plain, "EOF"); + #[cfg(target_os = "macos")] + { + let out = f.taba(&f.wt_a, &["reload", &plain, "--json"]); + assert_eq!(code(&out), "E_NO_RELOAD"); + assert_interactive_restart(&out, &plain); + } let out = f.taba(&f.wt_a, &["send", &plain, "x", "--json"]); assert_eq!(code(&out), "E_NO_INPUT"); } @@ -414,6 +561,89 @@ for line in sys.stdin: assert_eq!(code(&out), "E_NO_RELOAD"); } + #[test] + fn preview_is_interactive_but_does_not_offer_reload() { + let f = Fixture::new("input-preview"); + let vite = fake_tool(&f, "vite", FAKE_VITE); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "preview", + "--wait", + "--ready", + "log:VITE ready", + "--json", + "--", + &vite, + "preview", + ], + ); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let value = json(&out); + assert_eq!(value["interactive"], true); + let id = value["service"].as_str().unwrap(); + let out = f.taba(&f.wt_a, &["reload", id, "--json"]); + assert_eq!(code(&out), "E_NO_RELOAD"); + } + + #[test] + fn flutter_reload_refuses_a_non_flutter_wrapper_leader() { + let f = Fixture::new("input-flutter-wrapper"); + let fvm = fake_tool(&f, "fvm", SLEEPER); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "app", + "--no-interactive", + "--wait", + "--ready", + "log:ready", + "--json", + "--", + &fvm, + "flutter", + "run", + ], + ); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let value = json(&out); + let id = value["service"].as_str().unwrap(); + let out = f.taba(&f.wt_a, &["reload", id, "--json"]); + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NO_RELOAD"); + assert_interactive_restart(&out, id); + assert!(!log(&f, &f.wt_a, id).contains("usr1")); + } + + #[test] + fn a_failed_interactive_spawn_does_not_leave_a_fifo() { + let f = Fixture::new("input-failed-start"); + let out = f.taba( + &f.wt_a, + &[ + "run", + "--name", + "broken", + "--interactive", + "--json", + "--", + "./missing-program", + ], + ); + assert_eq!(code(&out), "E_START_FAILED"); + let fifo = f + .home() + .join("inputs") + .join(f.scope_of(&f.wt_a)) + .join("broken.fifo"); + assert!(!fifo.exists()); + assert!(f.ps(&[]).is_empty()); + } + /// `logs -f` on a terminal: read-only until `i`, Ctrl+] stops typing, /// q quits; the service keeps running. #[test] From 1b418572d55024d5b99295ba6fec46e6dd518c73 Mon Sep 17 00:00:00 2001 From: Buchi-dev-dzn <208559603+Buchi-dev-dzn@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:07:53 +0900 Subject: [PATCH 8/8] Preserve queued notices during input authorization --- src/input.rs | 9 ++++++++- src/lease.rs | 8 +++++++- tests/input.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/input.rs b/src/input.rs index a04d913..b14473b 100644 --- a/src/input.rs +++ b/src/input.rs @@ -638,7 +638,14 @@ impl Access<'_> { let owner = caller.scope.as_deref() == Some(svc.scope.as_str()); if owner && force_reason.is_none() { let cfg = config::Config::load(store.root())?; - lease::touch(store, &cfg, caller, &scope, lease::Access::Mutate, None)?; + lease::touch( + store, + &cfg, + caller, + &scope, + lease::Access::MutateKeepNotices, + None, + )?; } let live = borrows::live(store, &svc)?; let exclusive = live.iter().find(|b| b.exclusive); diff --git a/src/lease.rs b/src/lease.rs index 8833d64..2bb260d 100644 --- a/src/lease.rs +++ b/src/lease.rs @@ -206,6 +206,9 @@ pub enum Access { /// `stop`, `rm`, `keep`, `disown`: renew, take over, or `E_SCOPE_HELD`; /// no record is created. Mutate, + /// Input authorization: like `Mutate`, but leave queued notices for + /// a subsequent command that can report them. + MutateKeepNotices, /// `whoami`: renew or take over, but report a live foreign holder /// instead of failing. Observe, @@ -399,7 +402,10 @@ pub fn touch( rec.branch = Some(b.clone()); changed = true; } - if (access != Access::Peek || state.is_live()) && !rec.notices.is_empty() { + if access != Access::MutateKeepNotices + && (access != Access::Peek || state.is_live()) + && !rec.notices.is_empty() + { for n in rec.notices.drain(..) { out.warnings.push(Warning { code: notice_code(&n.code), diff --git a/tests/input.rs b/tests/input.rs index a16316a..970151f 100644 --- a/tests/input.rs +++ b/tests/input.rs @@ -203,6 +203,53 @@ mod unix { assert!(!fifo.exists()); } + fn send_with_queued_borrow_warning(interactive: bool) { + let f = Fixture::new("input-borrow-warning"); + let input = start(&f, &f.wt_b, "input", interactive); + let id = input["service"].as_str().unwrap(); + let other = start(&f, &f.wt_a, "other", false); + let target = other["service"].as_str().unwrap(); + let out = f.taba(&f.wt_b, &["borrow", target, "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let borrow = json(&out); + let borrow_id = borrow["borrow"].as_str().unwrap(); + let out = f.taba(&f.wt_a, &["stop", target, "--force", "--reason", "test"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + + let out = f.taba(&f.wt_b, &["send", id, "hello", "--json"]); + if interactive { + assert_eq!(exit(&out), 0, "{}", text(&out)); + assert_eq!(json(&out)["bytes"], 6); + } else { + assert_eq!(exit(&out), 3, "{}", text(&out)); + assert_eq!(code(&out), "E_NO_INPUT"); + } + + // Observe before any other command can drain the borrow notice. + let out = f.taba(&f.wt_b, &["ps", "--json"]); + assert_eq!(exit(&out), 0, "{}", text(&out)); + let ps = json(&out); + let warnings = ps["warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{ps}"); + let warning = &warnings[0]; + assert_eq!(warning["code"], "W_BORROW_BROKEN"); + assert_eq!(warning["details"]["borrow"], borrow_id); + assert_eq!(warning["details"]["service"], target); + let release = format!("taba release {borrow_id}"); + assert_eq!(warning["details"]["release_command"], release); + assert!(warning["message"].as_str().unwrap().contains(&release)); + } + + #[test] + fn successful_send_preserves_queued_borrow_warning() { + send_with_queued_borrow_warning(true); + } + + #[test] + fn refused_send_preserves_queued_borrow_warning() { + send_with_queued_borrow_warning(false); + } + #[test] fn a_piped_attachment_rechecks_permission_for_each_input() { struct ReleaseOnDrop<'a> {