diff --git a/Cargo.lock b/Cargo.lock index 62b9e93..006fa71 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 32b0bd9..196c780 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 9877577..bb87b38 100644 --- a/README.md +++ b/README.md @@ -365,10 +365,13 @@ taba down # stop this scope's services declared in the file its parents. The scope is still yours (the git worktree, `$TABA_SCOPE` or `--scope`), so two worktrees of the same project get separate services from one file. Each service goes through `taba run` with `--wait`: `port` and -`ready` take the same values as `--port` and `--ready`, and `service_ttl` -the same as `--service-ttl`. The table's key is the service name, and `cmd` -is an array, or a plain string split on spaces; taba runs no shell (unlike a -quoted `taba run` command). `taba up` stops at the first service that fails +`ready` take the same values as `--port` and `--ready`, `service_ttl` +the same as `--service-ttl`, and `interactive = true` / `false` is `-i` / +`--no-interactive` (unset: `flutter run` and `vite` are +[interactive](#interactive-dev-servers-flutter-vite)). The table's key is the +service name, and `cmd` is an array, or a plain string split on spaces; taba +runs no shell (unlike a quoted `taba run` command). `taba up` stops at the +first service that fails to start or become ready, leaves the ones already started running, and lists what it did. `taba down` leaves services the file doesn't declare alone. @@ -388,7 +391,9 @@ Only environment variable names and a keyed fingerprint are kept in taba's state, so re-running with another value is a conflict without storing or printing the value. `--save` writes the definition to the nearest `taba.toml` (or the worktree root); it refuses a different existing definition -unless `--force`, and `taba up api` then starts it the same way. Saved env +unless `--force`, and `taba up api` then starts it the same way. An explicit +`--interactive` or `--no-interactive` is saved as `interactive = true` or +`false`; omitting both leaves any existing setting unchanged. Saved env values must be written to `taba.toml` in plain text, so taba warns and secrets should not be saved or committed. On Unix, new files are owner-only and updates keep the existing file's permissions. Saves serialize through a persistent @@ -413,6 +418,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. | @@ -441,6 +447,78 @@ 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; 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` | 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`). | + +`taba ps --json` shows `"interactive": true` for such services. + +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 + 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: @@ -590,6 +668,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, 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. @@ -656,7 +737,7 @@ that. Measurements against Docker are in [docs/benchmarks.md](docs/benchmarks.md | Command | What it does | | --- | --- | | `taba run CMD...` | The short form. Start `CMD` with a name taken from it (`npm run dev` → `dev`) and wait up to 30 s for the port it listens on. See [Quick start](#quick-start) and [Writing the command](#writing-the-command). | -| `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. `discovered_ports` in the reply lists the ports its processes listen on. | +| `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. `discovered_ports` in the reply lists the ports its processes listen on. `-i` makes it [interactive](#interactive-dev-servers-flutter-vite) (default for `flutter run` and `vite`). | | `taba up [NAME...] [--scope S] [--ttl DURATION] [--json]` | Start the services declared in the nearest `taba.toml` (all, or `NAME...` in that order), each like `run --wait`, reusing ones already running. Stops at the first failure and leaves started ones running. See [Project services](#project-services-tabatoml). | | `taba down [NAME...] [--scope S] [--timeout SECS] [--json]` | Stop your scope's services that the nearest `taba.toml` declares (all, or `NAME...`). | | `taba` | List services, like `taba ps`. | @@ -665,7 +746,11 @@ that. Measurements against Docker are in [docs/benchmarks.md](docs/benchmarks.md | `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 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`. | | `taba stop ... --timeout SECS` | Seconds to wait between SIGTERM and SIGKILL (Windows: Ctrl+Break and job termination; default 5). | @@ -689,8 +774,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 @@ -720,7 +806,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 | 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. | | `E_NO_FREE_PORT` | 4 | `--port auto` found no free port in its range. | @@ -732,6 +821,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, a `taba.toml` entry (`details.source` is `project`), `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. | @@ -900,6 +991,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 @@ -994,6 +1086,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 0dda1c1..21c8833 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 up [NAME...] [--scope S] [--json] # services declared in taba.toml taba down [NAME...] [--scope S] [--json] taba ps [--scope S] [--running] [--json] @@ -47,6 +50,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 @@ -149,6 +154,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. | @@ -178,6 +185,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/borrows.rs b/src/borrows.rs index 6000ec3..4b8f745 100644 --- a/src/borrows.rs +++ b/src/borrows.rs @@ -152,7 +152,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..a6f1bf1 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 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()); store.move_service(&svc.scope, &moved)?; diff --git a/src/error.rs b/src/error.rs index 66c13c7..8c45c92 100644 --- a/src/error.rs +++ b/src/error.rs @@ -162,7 +162,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" => 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" | "E_NO_PROJECT" => 5, diff --git a/src/gc.rs b/src/gc.rs index 8ebea81..6734b5c 100644 --- a/src/gc.rs +++ b/src/gc.rs @@ -342,6 +342,8 @@ mod tests { env_keys: Vec::new(), env_hash: 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 new file mode 100644 index 0000000..b14473b --- /dev/null +++ b/src/input.rs @@ -0,0 +1,1572 @@ +//! Interactive services (#68): `run --interactive`, `send`, `attach`, +//! `reload`, `signal`, and typing into a service from its log view. +//! +//! # How input reaches the service (Unix) +//! +//! 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. +//! +//! ```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::{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 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 (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, 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: `r` + Enter restarts the server. + Vite, + /// Preview accepts terminal shortcuts, but not `r`. + VitePreview, + Other, +} + +impl Kind { + pub fn name(self) -> &'static str { + match self { + Kind::Flutter => "flutter", + Kind::Vite | Kind::VitePreview => "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(command, Some(cwd), true) +} + +/// 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 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) { + return stem.to_string(); + } + } + file +} + +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 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(); + } + "--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, + } +} + +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()?; + pkg["scripts"][script].as_str().map(str::to_string) +} + +// ------------------------------------------------------------ setup (run) + +/// The terminal of an interactive service being started. +pub struct Terminal { + fifo: PendingFifo, + /// 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, +} + +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)] +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 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) { + 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(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) + .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 { + return Err(os("open a pseudo-terminal")); + } + let master = unsafe { File::from_raw_fd(fd) }; + let m = master.as_raw_fd(); + 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")); + } + // 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")); + } + 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, + stdin, + 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 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") + .args([ + m.to_string(), + r.to_string(), + spawned.pid.to_string(), + spawned.pgid.to_string(), + spawned.start_time.to_string(), + ]) + .env_remove("TABA_AGENT") + .env_remove("TABA_AGENT_PID") + .env_remove("TABA_OUTPUT") + .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.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 { + Err(unsupported("run --interactive")) +} + +/// `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 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; + }; + 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, + } + } + // 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. + 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 + +#[cfg(unix)] +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::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() && (m.dev(), m.ino()) == identity) + { + return Err(invalid_fifo()); + } + let mut f = std::fs::OpenOptions::new() + .write(true) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .open(&path) + .map_err(|e| match e.raw_os_error() { + 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())), + })?; + 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}"))), + } +} + +#[cfg(windows)] +fn try_write(_store: &Store, _svc: &Service, _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 takes no input", + svc.id() + ), + ) + .details(json!({ "service": svc.id() })) + .next(restart_interactive(svc)) +} + +fn restart_interactive(svc: &Service) -> Next { + let hint = "stop the instance, then rerun the original `taba run --interactive ...` command (add --interactive before the service command, replacing --no-interactive if present)"; + let hint = if svc.env_keys.is_empty() { + hint.to_string() + } else { + format!("{hint}; supply the original environment values again") + }; + Next::run(&hint, format!("taba stop {}", svc.id())) +} + +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(restart_interactive(svc)) +} + +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()))) +} + +#[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()), + )); + } + 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::MutateKeepNotices, + 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) + } + + 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) + } + + 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)); + } + } + } +} + +// ------------------------------------------------------------ send + +/// 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() { + // 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()), + "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")), + }; + if cfg!(windows) { + return Err(unsupported("taba send")); + } + let caller = scope::resolve(a.scope, a.agent)?; + let store = Store::open()?; + 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(), + "instance": svc.instance(), + }); + if reason.is_some() { + body["forced"] = json!(true); + } + Ok(Output::new( + body, + format!("{}: sent {} byte(s)", svc.id(), bytes.len()), + )) +} + +// ------------------------------------------------------------ signal, reload + +/// `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 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(), + "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, 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, + }; + if !crate::proc::is_alive(svc.pid, svc.start_time) { + return Err(not_running(svc)); + } + // 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", + 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, _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, + pub scope: Option, + pub agent: Option, + pub force: bool, + pub reason: Option, +} + +/// `taba reload`: the most reliable reload for the kind of dev server. +/// 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()?; + if cfg!(windows) { + return Err(unsupported("taba reload")); + } + 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 { + Signal::Usr2 + } else { + Signal::Usr1 + }; + send_signal(&svc, sig, true)?; + 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 + ), + ) + } + 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)"), + ) + } + }; + 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, + pub agent: Option, + pub force: bool, + 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()?; + 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(access, &svc, log, pos, true, false) + } else { + forward_pipe(access, &svc, log, pos) + }?; + Ok(None) +} + +/// `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 access = Access { + store, + caller, + target, + verb: "attach", + force_reason: None, + }; + let svc = access.attach(None)?; + let (log, pos) = open_tail(&svc)?; + view(access, &svc, log, pos, true, true) +} + +/// `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()?; + 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)> { + 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) { + let _ = ratatui::crossterm::terminal::disable_raw_mode(); + } +} + +/// 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. +fn view( + access: Access<'_>, + svc: &Service, + mut log: File, + mut pos: u64, + mut typing: bool, + leave_on_detach: bool, +) -> Result<()> { + 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 Err(e) = access.write(Some(svc), send, false) + { + 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 access.attach(Some(svc)) { + 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(()) +} + +/// `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(access: Access<'_>, svc: &Service, mut log: File, mut pos: u64) -> Result<()> { + use std::io::{Read, Seek, SeekFrom, Write}; + eprintln!( + "taba: attached to {} (EOF detaches; the service keeps running)", + svc.id() + ); + let mut stdout = std::io::stdout().lock(); + let mut chunk = Vec::new(); + 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; + if stdout + .write_all(&chunk) + .and_then(|_| stdout.flush()) + .is_err() + { + break "closed"; + } + } else if !running { + break "exited"; + } + if let Some(t) = linger { + if t.elapsed() >= Duration::from_millis(500) { + break "detached"; + } + std::thread::sleep(Duration::from_millis(50)); + continue; + } + match read_stdin(Duration::from_millis(50))? { + None => {} + Some(bytes) if bytes.is_empty() => linger = Some(std::time::Instant::now()), + Some(bytes) => { + access.write(Some(svc), &bytes, false)?; + } + } + }; + match outcome { + "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. Uses select(2), which (unlike poll) +/// works on terminals on macOS. +#[cfg(unix)] +fn read_stdin(timeout: Duration) -> Result>> { + 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, + ) + }; + if n < 0 { + let e = std::io::Error::last_os_error(); + if e.kind() == std::io::ErrorKind::Interrupted { + return Ok(None); + } + // EBADF: stdin is closed. + return Ok(Some(Vec::new())); + } + if n == 0 { + return Ok(None); + } + let mut buf = vec![0u8; 4096]; + 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!( + 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::*; + + 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"\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]); + 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"); + } + + #[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::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); + 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( + &["/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] + fn detects_vite_behind_package_scripts() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("package.json"), + 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()); + 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); + 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/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/src/main.rs b/src/main.rs index 9f6842e..88ef54e 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; @@ -91,6 +92,14 @@ enum Cmd { /// already_running re-run), independent of the lease #[arg(long, value_parser = config::parse_service_ttl_flag)] service_ttl: Option, + /// 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, /// Set an environment variable for the service (repeatable). Values /// are never stored in taba state or printed. #[arg(long = "env", value_name = "KEY=VALUE")] @@ -109,6 +118,102 @@ enum Cmd { #[arg(required = true, trailing_var_arg = true, value_name = "CMD")] command: Vec, }, + /// 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, + /// 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 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, + /// 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, + }, + /// 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 { + /// 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, + }, /// Start the services declared in the nearest taba.toml (all, or NAME... /// in that order) and wait until each is ready; running ones are reused Up { @@ -419,6 +524,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)] @@ -537,6 +652,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)] + { + 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 raw: Vec = std::env::args().collect(); let (args, shape) = match runform::prepare(raw.clone()) { Ok(prepared) => prepared, @@ -570,6 +702,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, @@ -579,6 +721,8 @@ fn main() -> ExitCode { ready, ttl, service_ttl, + interactive, + no_interactive, env, save, force, @@ -586,7 +730,7 @@ fn main() -> ExitCode { command, } => { let json = json || env_json(); - let interactive = !json + let prompt = !json && std::env::var_os("TABA_AGENT").is_none_or(|a| a.is_empty()) && io::stdin().is_terminal() && io::stderr().is_terminal(); @@ -603,6 +747,11 @@ fn main() -> ExitCode { ready, ttl, service_ttl, + interactive: if no_interactive { + Some(false) + } else { + interactive.then_some(true) + }, command, cwd: None, env, @@ -610,12 +759,92 @@ fn main() -> ExitCode { force, shape, raw, - interactive, + prompt, }) }) .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::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, + scope, + agent, + force, + reason, + json, + } => ( + json || env_json(), + input::cmd_signal(input::SignalArgs { + target, + signal, + scope, + agent, + force, + reason, + }) + .map(Some), + ), Cmd::Up { names, scope, @@ -996,6 +1225,8 @@ struct RunArgs { ready: Option, ttl: Option, service_ttl: Option, + /// `-i` (Some(true)), `--no-interactive` (Some(false)), else detected. + interactive: Option, /// The command as clap collected it; [`runform::command_spec`] turns it /// into the argv to start. command: Vec, @@ -1009,7 +1240,36 @@ struct RunArgs { /// The original arguments, program name first (for corrections). raw: Vec, /// A person at a terminal: a correctable command is offered to run. - interactive: bool, + 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 { @@ -1023,7 +1283,7 @@ fn cmd_run(mut a: RunArgs) -> Result { .and_then(|d| d["corrected"].as_str()) .map(String::from); match fixed { - Some(fixed) if a.interactive && confirm_corrected(&fixed) => { + Some(fixed) if a.prompt && confirm_corrected(&fixed) => { let shape = runform::Shape { separator: true, ..a.shape @@ -1050,6 +1310,7 @@ fn cmd_run(mut a: RunArgs) -> Result { env: a.env.clone(), cwd, service_ttl: a.service_ttl, + interactive: a.interactive, }, a.force, )?) @@ -1066,7 +1327,7 @@ fn cmd_run(mut a: RunArgs) -> Result { ); out.body.insert("saved".into(), json!({"path": plan.path, "name": plan.def.name, "result": plan.result, "definition": shown})); if !plan.def.env.is_empty() && plan.result != "unchanged" { - out.warnings.push(Warning { code: "W_ENV_SAVED", message: "environment values were saved to taba.toml in plain text; do not commit secrets".into() }); + out.warnings.push(Warning { code: "W_ENV_SAVED", message: "environment values were saved to taba.toml in plain text; do not commit secrets".into(), details: None }); } } Ok(out) @@ -1127,6 +1388,13 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { )); } }; + 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, &dir) != input::Kind::Other); if let Some(r) = &a.ready && r.needs_port() && a.port.is_none() @@ -1203,6 +1471,7 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { if ex.template() == template.as_slice() && ex.cwd == dir && ex.port_request() == port_request + && ex.input.is_some() == interactive && ex.env_keys == env_keys && ex.env_hash == env_hash { @@ -1220,14 +1489,15 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { return Err(TabaError::new( "E_CONFLICT", format!( - "{} is already running with a different command, directory, port or environment; stop it first", + "{} is already running with a different command, directory, port, environment or \ + interactive mode; stop it first", ex.id(), ), ) .details(json!({ "service": ex.id(), "command": ex.template(), "directory": ex.cwd, "port": ex.port, "port_request": ex.port_request(), "instance": ex.instance(), - "env": ex.env_keys, + "interactive": ex.input.is_some(), "env": ex.env_keys, })) .next(Next::run( "stop it, then run again", @@ -1285,6 +1555,19 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { let log_offset = log.metadata()?.len(); let log_err = log.try_clone()?; + let mut terminal = if interactive { + Some(input::create(&store, &scope, &name)?) + } else { + None + }; + 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])); #[cfg(windows)] if let Some(line) = runform::shell_line(&command) { @@ -1306,7 +1589,7 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { .envs(a.env.iter().map(|(k, v)| (k, v))) .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 { @@ -1327,7 +1610,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.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(), @@ -1352,13 +1650,32 @@ fn run_service(a: RunArgs, form: runform::RunForm) -> Result { env_keys, env_hash, 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); @@ -1489,12 +1806,18 @@ fn short_text(svc: &Service, started: bool, short: &Short) -> String { } None => {} } - format!( + let mut text = format!( "{head}\n command: {}\n name {:?} (from {:?}; set another with --name)\n logs: taba logs {label} · stop: taba stop {label}", runform::display_command(svc.template()), svc.name, short.derived.source_text(), - ) + ); + if svc.input.is_some() { + text.push_str(&format!( + "\n interactive: yes (type: taba attach {label}; i in taba logs -f)" + )); + } + text } fn run_result( @@ -1534,6 +1857,7 @@ fn run_result( "directory": svc.cwd, "log_path": svc.log_path, "discovered_ports": svc.discovered_ports, + "interactive": svc.input.is_some(), }); if !svc.env_keys.is_empty() { body["env"] = json!(svc.env_keys); @@ -1549,6 +1873,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 !svc.env_keys.is_empty() { text.push_str(&format!( "\n env {} (values not shown)", @@ -1627,6 +1956,7 @@ fn cmd_up( ready: def.ready.clone(), ttl, service_ttl: def.service_ttl, + interactive: def.interactive, command: def.command.clone(), cwd: Some(def.cwd.clone()), env: def.env.clone(), @@ -1634,7 +1964,7 @@ fn cmd_up( force: false, shape: runform::Shape::default(), raw: Vec::new(), - interactive: false, + prompt: false, }; let form = runform::resolve( args.name.clone(), @@ -1886,6 +2216,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), + "interactive": s.input.is_some(), })); borrowers.push(borrows.iter().map(|b| b.scope.clone()).collect()); } @@ -2049,6 +2380,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 { @@ -2574,6 +2912,9 @@ mod cli_tests { let Some(long) = a.get_long() else { continue }; let takes_value = a.get_action().takes_values(); let equals_only = a.is_require_equals_set(); + if let Some(short) = a.get_short().filter(|_| !takes_value && long != "help") { + switches.push(format!("-{short}")); + } if takes_value && !equals_only { values.push(format!("--{long}")); } else if long != "help" { @@ -2646,6 +2987,8 @@ mod stop_tests { env_keys: Vec::new(), env_hash: 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/project.rs b/src/project.rs index 7421c62..5590717 100644 --- a/src/project.rs +++ b/src/project.rs @@ -27,6 +27,8 @@ pub struct ServiceDef { /// Absolute: `cwd` resolved against the file's directory. pub cwd: PathBuf, pub service_ttl: Option, + /// `interactive = true/false`; unset: detected as for `run`. + pub interactive: Option, } #[derive(Debug, Clone)] @@ -151,6 +153,7 @@ fn parse_service(path: &Path, dir: &Path, name: &str, value: &toml::Value) -> Re let mut env = Vec::new(); let mut cwd = crate::util::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); let mut service_ttl = None; + let mut interactive = None; for (k, v) in t { let key = at(k); let string = |v: &toml::Value| { @@ -221,11 +224,18 @@ fn parse_service(path: &Path, dir: &Path, name: &str, value: &toml::Value) -> Re service_ttl = Some(parse_service_ttl_flag(&string(v)?).map_err(|m| err(path, &key, m))?) } + "interactive" => { + interactive = Some( + v.as_bool() + .ok_or_else(|| err(path, &key, "must be true or false"))?, + ) + } _ => { return Err(err( path, &key, - "unknown key (known: cmd, port, ready, wait, env, cwd, service_ttl)", + "unknown key (known: cmd, port, ready, wait, env, cwd, service_ttl, \ + interactive)", )); } } @@ -253,6 +263,7 @@ fn parse_service(path: &Path, dir: &Path, name: &str, value: &toml::Value) -> Re env, cwd, service_ttl, + interactive, }) } @@ -326,8 +337,8 @@ pub fn ready_text(r: &ReadySpec) -> String { } } -/// What `run --save` asks to write. `wait`, `ready` and `service_ttl` are -/// `None` when the run did not give them: the file's value is kept. +/// What `run --save` asks to write. `wait`, `ready`, `service_ttl` and +/// `interactive` are `None` when omitted: the file's value is kept. #[derive(Clone)] pub struct SaveRequest { pub name: String, @@ -338,6 +349,7 @@ pub struct SaveRequest { pub env: Vec<(String, String)>, pub cwd: PathBuf, pub service_ttl: Option, + pub interactive: Option, } /// A checked `run --save`, written by `write_save` once the run succeeded. @@ -368,6 +380,7 @@ fn same_def(a: &ServiceDef, b: &ServiceDef) -> bool { && ae == be && a.cwd == b.cwd && a.service_ttl == b.service_ttl + && a.interactive == b.interactive } /// Checks a `run --save` before anything starts: reads the file (an invalid @@ -404,6 +417,7 @@ pub fn plan_save(path: PathBuf, req: SaveRequest, force: bool) -> Result toml_edit::Tabl if let Some(ttl) = def.service_ttl { t.insert("service_ttl", value(crate::config::format_duration(ttl))); } + if let Some(interactive) = def.interactive { + t.insert("interactive", value(interactive)); + } t } @@ -596,6 +613,7 @@ mod tests { env: vec![("TOKEN".into(), "dummy-save-secret".into())], cwd: crate::util::canonicalize(dir).unwrap(), service_ttl: None, + interactive: None, } } @@ -724,6 +742,7 @@ port = 5432 cmd = ["python3", "worker.py"] ready = "log:started" service_ttl = "2h" +interactive = true "#) .unwrap(); let names: Vec<_> = pr.services.iter().map(|s| s.name.as_str()).collect(); @@ -739,6 +758,8 @@ service_ttl = "2h" assert_eq!(pr.services[1].port, Some(PortSpec::Fixed(5432))); assert_eq!(pr.services[1].wait, DEFAULT_WAIT); assert_eq!(pr.services[2].service_ttl, Some(7200)); + assert_eq!(pr.services[2].interactive, Some(true)); + assert_eq!(pr.services[0].interactive, None); let sel = pr .select(&["worker".into(), "web".into(), "worker".into()]) .unwrap(); diff --git a/src/runform.rs b/src/runform.rs index 51e2184..1855ca4 100644 --- a/src/runform.rs +++ b/src/runform.rs @@ -99,7 +99,17 @@ pub const RUN_VALUE_FLAGS: &[&str] = &[ "--env", ]; /// taba's `run` flags without a separate value. -pub const RUN_SWITCHES: &[&str] = &["--wait", "--save", "--force", "--json", "--help", "-h"]; +pub const RUN_SWITCHES: &[&str] = &[ + "--wait", + "--interactive", + "-i", + "--no-interactive", + "--save", + "--force", + "--json", + "--help", + "-h", +]; /// How the command was written on the `run` command line, read from the /// raw arguments (clap cannot tell these apart). @@ -626,6 +636,21 @@ mod tests { words.iter().map(|s| s.to_string()).collect() } + #[test] + fn prepare_knows_the_interactive_switches() { + for flag in ["-i", "--interactive", "--no-interactive"] { + let (args, _) = prepare(strings(&["taba", "run", "flutter run", flag])).unwrap(); + assert_eq!( + args, + strings(&["taba", "run", flag, "--", "flutter run"]), + "{flag}" + ); + let (args, shape) = prepare(strings(&["taba", "run", flag, "vite"])).unwrap(); + assert_eq!(args, strings(&["taba", "run", flag, "vite"]), "{flag}"); + assert!(shape.options_first, "{flag}"); + } + } + #[test] fn prepare_moves_options_after_a_quoted_command_in_front_of_it() { let shape = |raw: &[&str]| prepare(strings(raw)).unwrap(); diff --git a/src/state.rs b/src/state.rs index 6f3f9e6..9d5a083 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 input of a service started with `run --interactive` (Unix) //! events.jsonl append-only audit log //! env.key random key for `env_hash` (see `env_fingerprint`) //! version state schema version @@ -153,6 +154,29 @@ pub struct Service { /// TCP ports discovered for the short `run` form. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub discovered_ports: Vec, + /// `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, + /// 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; +/// 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, + /// 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)] @@ -463,6 +487,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") @@ -486,6 +518,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)) @@ -682,6 +734,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); @@ -741,6 +803,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)?; } @@ -759,6 +822,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..4ec7a95 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, + /// Interactive (`run --interactive`): `i` types into 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,35 @@ 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()) + } + + /// `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), @@ -532,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); @@ -609,6 +644,7 @@ impl App { } } } + KeyCode::Char('i') => return self.attach_key(), KeyCode::Char('l') => match self.selected_row() { Some(r) => { let path = r.log_path.clone(); @@ -697,6 +733,7 @@ pub(crate) mod tests { locked_by: None, pending_gc: None, lease_expired: false, + input: false, } } @@ -732,6 +769,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 8445f8a..36e8b28 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 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 //! terminals). The state and key handling live in `app.rs` and drawing in @@ -135,6 +137,30 @@ fn event_loop( running = Some((handle, rx, action)); } Effect::OpenLog(path) => tail = Some(LogTail::new(path)), + Effect::Attach(scope, name) => { + // 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_from_ui(store, caller, &format!("{scope}/{name}")); + *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 => {} } } @@ -304,6 +330,8 @@ mod tests { env_keys: Vec::new(), env_hash: None, discovered_ports: Vec::new(), + input: None, + dev_kind: None, }) .unwrap(); } diff --git a/src/ui/view.rs b/src/ui/view.rs index 1ec78f4..a32f5d1 100644 --- a/src/ui/view.rs +++ b/src/ui/view.rs @@ -490,10 +490,14 @@ 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() + " ↑↓ 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..970151f --- /dev/null +++ b/tests/input.rs @@ -0,0 +1,798 @@ +//! Interactive services (#68): `run --interactive`, `send`, `attach`, +//! `reload`, `signal`, and input mode in `logs -f`. +mod common; +use common::*; + +/// 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, 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) +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() + } + + 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())) + } + + /// 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 + } + + 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 } + } + + 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!("#!{interpreter}\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"); + 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["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)); + 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: 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"); + 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()); + } + + 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> { + 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"); + 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["interactive"], 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"); + } + + /// Like Flutter: single-key input and an observable receipt of each signal. + const FAKE_FLUTTER: &str = r#" +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 +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_reload_respects_the_platform_policy() { + let f = Fixture::new("input-flutter"); + let flutter = flutter_launcher(&f); + 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 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), so manual input is refused. + 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"); + #[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"); + } + + #[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"); + } + + #[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] + 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"); + 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()); +} diff --git a/tests/run_env_save.rs b/tests/run_env_save.rs index 2dcb447..33860eb 100644 --- a/tests/run_env_save.rs +++ b/tests/run_env_save.rs @@ -95,7 +95,7 @@ fn correction_diagnostics_do_not_echo_env_values() { let inline = format!("--env={token}"); for env in [vec!["--env", token.as_str()], vec![inline.as_str()]] { for quoted in [false, true] { - let mut args = vec!["run", "--name", "web"]; + let mut args = vec!["run", "--name", "web", "--interactive", "--save"]; args.extend_from_slice(&env); if quoted { args.extend_from_slice(&["npm run dev", "--open"]); @@ -184,7 +184,12 @@ fn child_drops_caller_identity_but_honors_deliberate_env_overrides() { "vars=['deliberate', '123', 'text']", ), ] { - let args = run_args(name, &env, &["--save"], &command); + let switches = if cfg!(unix) { + vec!["--interactive", "--save"] + } else { + vec!["--no-interactive", "--save"] + }; + let args = run_args(name, &env, &switches, &command); let out = f .cmd(&f.wt_a, &args) .env("TABA_AGENT", "agent-a") @@ -194,6 +199,13 @@ fn child_drops_caller_identity_but_honors_deliberate_env_overrides() { .unwrap(); assert_eq!(exit(&out), 0, "{}", text(&out)); let v = json(&out); + assert_eq!(v["interactive"], cfg!(unix)); + assert!( + v["saved"]["definition"] + .as_str() + .unwrap() + .contains(&format!("interactive = {}", cfg!(unix))) + ); let log = std::fs::read_to_string(v["log_path"].as_str().unwrap()).unwrap(); assert!(log.contains(expected), "{log}"); let stopped = f @@ -210,6 +222,7 @@ fn child_drops_caller_identity_but_honors_deliberate_env_overrides() { .output() .unwrap(); assert_eq!(exit(&up), 0, "{}", text(&up)); + assert_eq!(json(&up)["results"][0]["interactive"], cfg!(unix)); let logs = f.taba(&f.wt_a, &["logs", name]); assert!(text(&logs).contains(expected), "{}", text(&logs)); let stopped = f @@ -280,6 +293,7 @@ fn env_values_never_reach_state_events_logs_or_output() { v["error"]["details"]["env"], serde_json::json!(["API_TOKEN", "MODE"]) ); + assert_eq!(v["error"]["details"]["interactive"], false); let out = run(&f, &f.wt_a, &run_args("api", &changed, &[], &cmd)); assert_eq!(exit(&out), 3); assert_no_secret("human error", &out); diff --git a/tests/short_run.rs b/tests/short_run.rs index c3e70ff..3a45165 100644 --- a/tests/short_run.rs +++ b/tests/short_run.rs @@ -363,6 +363,7 @@ fn explicit_form_is_unchanged() { "directory", "discovered_ports", "instance", + "interactive", "log_path", "name", "ok",