Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

feat: low-latency task-pane input via a broker thread and tmux control mode (#145)

Fynn Fluegge954590231953
diff --git a/CLAUDE.md b/CLAUDE.md
index 0a26043..be24baa 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -58,7 +58,11 @@ src/
β”‚ # Notification, RunningAgent, AgentStatus
β”œβ”€β”€ tmux/
β”‚ β”œβ”€β”€ mod.rs # Tmux server "agtx", session management
-β”‚ └── operations.rs # TmuxOperations trait (mockable for testing)
+β”‚ β”œβ”€β”€ operations.rs # TmuxOperations trait (mockable for testing)
+β”‚ β”œβ”€β”€ input.rs # PaneInput/PaneInputSink, the input broker, both backends
+β”‚ β”œβ”€β”€ input_tests.rs # Coalescing, ordering, queue policy (included via #[path])
+β”‚ β”œβ”€β”€ control.rs # Persistent `tmux -C` client, frame parser, tmux command encoder
+β”‚ └── control_tests.rs # Encoder fixtures + parser tests (included via #[path])
β”œβ”€β”€ git/
β”‚ β”œβ”€β”€ mod.rs # is_git_repo, repo_root, current_branch, diff_stat/diff_full,
β”‚ # merge_branch, check_merge_conflicts, delete_branch
@@ -131,6 +135,8 @@ tests/
β”œβ”€β”€ update_tests.rs # Version policy, cache TTL, artifact naming parity, binary swap
β”œβ”€β”€ mock_infrastructure_tests.rs # Mock infrastructure tests
β”œβ”€β”€ shell_popup_tests.rs # Shell popup logic tests
+β”œβ”€β”€ tmux_control_tests.rs # Real-tmux pane input: ordering, escaping, sizing,
+β”‚ # reconnect, latency β€” opt-in via AGTX_TMUX_IT=1
└── smoke/ # Per-agent smoke tests β€” real binaries, no mocks, opt-in
β”œβ”€β”€ agent_smoke.py # The runner: scratch repo β†’ TUI in tmux β†’ phases over MCP
β”œβ”€β”€ test_agent_smoke.py # Deterministic tests for the harness itself (no tmux/auth)
@@ -265,6 +271,104 @@ So `submit_message()` counts nothing and watches the composer instead: it presse
Without `-l`, tmux resolves an argument that matches a key name *as that key*: `"Space"` arrives as `0x20`, `"Escape"` as `ESC`, `"Up"` as `\033[A` (tmux 3.5a). So `send_key` must never carry task-derived text β€” that is what `send_text` is for.
+### Typing into a Task Pane
+The two lanes above deliver a *task*. This is the third lane, and it is the only one a **human** is
+waiting on: the keys forwarded from an open task popup.
+
+```text
+crossterm key event
+ β”‚ popup_key_input() β€” Char β†’ Text, everything else β†’ Key
+ β–Ό
+ PaneInputSink::send β€” enqueue, ~1 Β΅s, never waits for tmux
+ bounded channel (1024)
+ β–Ό
+ one broker thread β€” the single ordering authority
+ β”œβ”€ coalesces adjacent Text for the same target (2 ms window, 4 KiB cap)
+ β”œβ”€ flushes before every Key, Paste, target change, popup close, shutdown
+ β”œβ”€β–Ί control backend `tmux -C attach-session` (persistent, opt-in)
+ └─► subprocess backend `tmux send-keys` (default, and the fallback)
+```
+
+**Every key used to be a process.** `send_key` starts a `tmux` client and waits for it: **~20 ms
+p95** idle, 40–50 ms under load, on the input thread, per keystroke. That is the whole reason this
+lane exists. Enqueueing costs ~1 Β΅s, and end-to-end delivery over the control connection is **0.32 ms
+p95** against 38 ms for the subprocess path (tmux 3.5a, macOS; the measurement lives in
+`tests/tmux_control_tests.rs`, and `docs/planning/tmux-control-mode-input.md` has the full table).
+
+- **`PaneInput` is typed, not a formatted command**, because the broker must be able to tell literal
+ text from a key name: text goes out with `send-keys -l` (no key-name lookup), a key without it.
+ An unmodified character is therefore **`Text`**, where it used to be a key β€” a fix, not a
+ reclassification: `send-keys -t x ";"` never arrived at all, because a standalone semicolon is how
+ tmux separates commands.
+- **Batching never delays a key.** Enter, Escape, arrows, and anything Ctrl/Alt-modified flush the
+ buffer first and go immediately. A delayed Enter is a visibly broken editor.
+- **A target change flushes.** Queued characters belong to the pane they were typed into; the popup
+ close, popup open and fullscreen-toggle paths all flush so nothing can follow the target.
+- **The control connection is on, and there is no config field for it.** A connect that fails, and a
+ connection lost later, both fall back to the subprocess backend on their own (`maybe_connect` /
+ `drop_control`), so a persisted setting could only hold a staler copy of a decision the broker
+ already makes at runtime. `AGTX_TMUX_CONTROL=0` turns it off for one run, which is what a bug
+ report needs to bisect the two lanes. The non-blocking broker is *not* conditional either way β€”
+ the backend choice only decides what the broker thread writes through, so the subprocess path gets
+ the same ordering and the same responsive input thread.
+- **`tmux -C` is attached with `-f ignore-size,no-output`.** `ignore-size` keeps it out of tmux's
+ client-size calculation, so it cannot resize the pane the popup sized by hand; `no-output` stops
+ every byte an agent paints from being mirrored down our stdout, which the popup does not read
+ (it captures panes instead). The session is an **attach point**, but only for targets that name
+ their own session: `send-keys -t "orchestrator"` is resolved *inside the attached session*, so one
+ client drives every window on the server **only** if every target is `session:window`. That is
+ what `pane_target` guarantees, and it is not a nicety β€” `orchestrator` is a window name every
+ project session has, so a bare target after a project switch delivered keystrokes to the previous
+ project's agent, while a bare `task-<slug>` drew `%error can't find pane` and was dropped in
+ silence. `set_session` re-points the *next* connect, for when the old session is killed.
+- **`tmux_quote` is not `single_quote`.** Control mode parses tmux's syntax, not the shell's: inside
+ double quotes tmux replaces `$VAR`, `#{format}`, a leading `~`, and backslash escapes, so all of
+ `\ " $ # ~` are escaped, LF/CR/tab become `\n`/`\r`/`\t`, and the rest of C0 becomes `\ooo`. A
+ raw newline is the one thing that cannot be sent: commands are newline-terminated, so it splits
+ the command and the tail is parsed as a second one.
+- **A failed control write is not replayed.** A write error is ambiguous β€” part of it may have
+ reached tmux β€” and a duplicated Enter is worse than a dropped one. The request is dropped, the
+ connection is marked dead, and the *next* one goes to the subprocess backend. A backend found
+ *dead before writing* is different: nothing was sent, so that request moves to the fallback in
+ place, keeping its order.
+- **A full queue warns rather than reordering.** Sending synchronously would put that key ahead of
+ everything already queued, so agtx keeps the prefix and tells the user.
+- **A paste stays on `load-buffer`** (it needs a pipe, not a command argument) and is issued behind a
+ `ControlClient::barrier` β€” the two travel different sockets, and only the barrier keeps the paste
+ behind the text typed before it.
+- **A pane with no tmux scrollback delegates its scroll keys to the agent.** A
+ full-screen agent UI lives in the terminal's *alternate screen*, which
+ accumulates no scrollback: `history_size` is 0, `capture-pane -S -500` returns
+ exactly the visible rows, and the session's history belongs to the agent.
+ Scrolling agtx's one-screen buffer would move nothing while the footer printed
+ a line number to match β€” which is what made an empty buffer look like a broken
+ scrollbar. So `ShellPopup::has_scrollback()` (from `PaneMetrics::history_size`,
+ free in the `display -p` the refresh already runs) switches those keys over to
+ `handle_popup_scroll`; the footer shows only the available actions. Unknown
+ metrics count as *has* scrollback, so a failed query changes nothing.
+ Scroll chords are translated rather than passed through: `C-n/p` use the same
+ Page Down/Up translation, while `C-g` uses End. Measured against
+ Claude Code 2.1.251: in its `ctrl+o`
+ transcript view all four of `Up`/`Down`/`PageUp`/`PageDown` scroll, but in the
+ main view `Up` recalls a previous prompt **into the composer** β€” overwriting
+ what the user was typing β€” while `PageUp` is inert. A raw `C-d` would be an
+ EOF that ends the session and `C-u` would kill the composer line, which is why
+ nothing is forwarded verbatim. Claude takes the alternate screen shortly after startup and never
+ gives it back, so this is the normal case for a task pane, not an edge one.
+ `C-g` maps to `End`, measured the same way: it returns the transcript view to
+ the bottom, and in the main view it only moves the composer cursor to the end
+ of the line without altering the text. `C-n/p` use that same Page Up/Down
+ translation; `C-d/u` remain explicit page navigation.
+ Unrelated but worth knowing when a key "does nothing": a user's **own** tmux
+ can eat it before agtx sees it β€” `vim-tmux-navigator` binds `C-h/C-j/C-k/C-l`
+ in the root table and only forwards them to vim-like panes.
+- Logs carry lengths, targets, key categories and timings. **Pane input is never logged.**
+- The broker's ordering authority covers **popup input**. agtx's own writes to a pane β€” a dialog
+ answer from `dismiss_launch_dialog`, a phase advance from `send_skill_and_prompt` β€” still go
+ through `TmuxOperations` on their own threads, unordered with respect to it. That was equally true
+ when both were subprocesses, and they do not overlap in practice: a pane parked on a dialog is not
+ one the user is typing into.
+
### First-Launch Dialogs
Agents gate a directory they have not seen behind an interactive dialog. `LAUNCH_DIALOGS`
(`src/tui/app.rs`) is the table, derived from `AgentSpec::dialogs`; `dismiss_launch_dialog` answers
@@ -588,13 +692,20 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)
### Task Popup (tmux view)
| Key | Action |
|-----|--------|
-| `Ctrl+j/k` or `Ctrl+n/p` | Scroll up/down |
-| `Ctrl+d/u` or `PageDown/PageUp` | Page down/up |
+| `Ctrl+d/u` or `PageDown/PageUp` | Page down/up β€” the pair the footer advertises |
+| `Ctrl+n/p` or `Ctrl+Down/Up` | Scroll down/up five lines β€” bound, but not named in the footer |
| `Ctrl+g` | Jump to bottom |
| `Ctrl+f` | Toggle the task popup between windowed and fullscreen modes |
| `Ctrl+q` | Close popup |
| Other keys | Forwarded to tmux/agent (including `Esc`) |
+**All three scroll rows** are delegated to the agent when the pane has no tmux scrollback β€” see
+*Typing into a Task Pane*. There they are translated to `PageUp`/`PageDown`/`End` rather than passed
+through, so the five-line and twenty-line distinction disappears and both pairs page.
+
+The footer names only `C-d/u` because it has room for one pair, **not** because the other is
+unbound. Do not reconcile the two by unbinding `C-n/p`.
+
When an escalation note is present, the first keypress only dismisses the banner and is not forwarded.
### PR Creation Popup
@@ -831,8 +942,16 @@ cargo test --features test-mocks
# Per-agent smoke tests β€” real binaries, real auth, real tokens (opt-in, never CI)
tests/smoke/agent_smoke.py # installed agents x the agtx plugin
python3 tests/smoke/test_agent_smoke.py # tests for the harness itself
+
+# Real-tmux pane input: ordering, escaping, pane sizing, reconnect, latency (opt-in)
+AGTX_TMUX_IT=1 cargo test --test tmux_control_tests -- --nocapture
```
+`tmux_control_tests.rs` starts throwaway tmux servers and asserts on the **bytes a program in the
+pane received**, not on rendered output β€” a redraw hides a reordering that a byte comparison
+catches. Skipped tests name their reason instead of passing quietly. It has only been run on macOS
+(tmux 3.5a); run it on Linux too.
+
The smoke runner answers the one question the Rust suite cannot: **does a real agent binary actually
receive its work?** Unit tests mock `TmuxOperations` and `agent_parity_tests.rs` pins the strings
agtx builds, so neither can see "the agent ignored it" β€” the gap where every silent-hang bug so far
diff --git a/src/tmux/control.rs b/src/tmux/control.rs
new file mode 100644
index 0000000..23f0778
--- /dev/null
+++ b/src/tmux/control.rs
@@ -0,0 +1,450 @@
+//! Persistent tmux **control-mode** client.
+//!
+//! Every `send-keys` agtx runs through [`RealTmuxOps`](super::RealTmuxOps) starts
+//! a `tmux` process and waits for it. Measured against tmux 3.5a on macOS that
+//! is **~25 ms per key** β€” the dominant term in the delay between pressing a key
+//! in a task popup and seeing it echoed. A control-mode client is one long-lived
+//! process that takes commands as lines on stdin, so the same `send-keys` costs
+//! ~0.05 ms round-trip and ~0.001 ms if nothing waits for the reply.
+//!
+//! ```text
+//! tmux -L agtx -C attach-session -t <session> -f ignore-size,no-output
+//! β”‚ stdin: one tmux command per line
+//! β”‚ stdout: %begin/%end/%error blocks + %notifications
+//! ```
+//!
+//! Three things about that invocation are load-bearing, and all three were
+//! measured before this file existed (see `docs/planning/tmux-control-mode-input.md`):
+//!
+//! - **`ignore-size`.** A control client can otherwise take part in tmux's client
+//! size calculation and shrink the very panes agtx sizes by hand for the popup.
+//! On 3.5a a control client with no size set turned out to be size-neutral
+//! already, but the flag makes that a guarantee rather than an observation.
+//! - **`no-output`.** Without it every byte an agent paints is mirrored down our
+//! stdout as `%output`. The popup gets its content from `capture-pane`, so that
+//! is pure cost β€” a busy agent would push megabytes through the reader thread.
+//! - **The session is only an attach point.** Commands carry their own
+//! `session:window` target and are executed server-wide, so one client drives
+//! every window on the `agtx` server. Verified: a client attached to session
+//! `one` typed into `two`.
+//!
+//! Commands are *not* shell words. tmux parses them itself, so the quoting is
+//! tmux's, not POSIX's β€” see [`tmux_quote`].
+
+use anyhow::{Context, Result};
+use std::io::{Read, Write};
+use std::process::{Child, ChildStdin, Command, Stdio};
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::{Duration, Instant};
+
+/// Payload line the handshake command echoes back, proving the connection round
+/// trips before agtx routes a keystroke through it.
+const READY_SENTINEL: &str = "agtx-control-ready";
+
+/// How long to wait for that sentinel before giving up on the connection.
+const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// Wrap `text` as one tmux **double-quoted** argument.
+///
+/// This is not [`single_quote`](super::single_quote): that one quotes a word for
+/// `sh`, and control mode never involves a shell. tmux applies its own
+/// replacements *inside* double quotes (tmux(1), PARSING SYNTAX), and every one
+/// of them has to be defused:
+///
+/// | In the text | Encoded as | Why |
+/// |---|---|---|
+/// | `\` | `\\` | escape lead-in, and a trailing one is a line continuation |
+/// | `"` | `\"` | ends the argument |
+/// | `$` | `\$` | `$VAR` is replaced from the global environment |
+/// | `#` | `\#` | starts a comment, and `#{…}` is a format |
+/// | `~` | `\~` | a leading `~` expands to a home directory |
+/// | LF | `\n` | commands are newline-terminated; a raw LF splits the command |
+/// | CR, tab | `\r`, `\t` | same class, and clearer than an octal escape |
+/// | other C0, DEL | `\ooo` | three-digit octal, as tmux documents |
+///
+/// Single quotes are the tempting alternative β€” tmux performs no replacements
+/// inside them β€” but they cannot contain a `'`, and task panes are typed into by
+/// humans writing English. Double quotes can encode everything.
+///
+/// Everything else, UTF-8 included, is passed through untouched: verified that
+/// `ν•œκ΅­μ–΄` and `πŸ˜€` arrive byte-identical.
+pub fn tmux_quote(text: &str) -> String {
+ let mut out = String::with_capacity(text.len() + 2);
+ out.push('"');
+ for ch in text.chars() {
+ match ch {
+ '\n' => out.push_str("\\n"),
+ '\r' => out.push_str("\\r"),
+ '\t' => out.push_str("\\t"),
+ '\\' | '"' | '$' | '#' | '~' => {
+ out.push('\\');
+ out.push(ch);
+ }
+ c if (c as u32) < 0x20 || c as u32 == 0x7f => {
+ out.push_str(&format!("\\{:03o}", c as u32));
+ }
+ c => out.push(c),
+ }
+ }
+ out.push('"');
+ out
+}
+
+/// One unit of control-mode output.
+///
+/// tmux frames every command's result between `%begin` and `%end`/`%error`, and
+/// emits unsolicited `%notifications` outside those blocks. The distinction
+/// matters: a payload line may itself start with `%`, so "starts with a percent
+/// sign" is not what tells a notification from output β€” being outside a block is.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Frame {
+ /// `%begin <time> <cmd> <flags>`
+ Begin { cmd: u64 },
+ /// `%end <time> <cmd> <flags>` β€” the command succeeded.
+ End { cmd: u64 },
+ /// `%error <time> <cmd> <flags>` β€” the command failed; the payload says why.
+ Error { cmd: u64 },
+ /// A line inside a `%begin`/`%end` block.
+ Payload(String),
+ /// An unsolicited notification (`%exit`, `%window-add @2`, …).
+ Notify(String),
+}
+
+/// Incremental parser for the control-mode stream.
+///
+/// A read from a pipe is not a line and not a frame: it may split one line
+/// across two reads or carry twenty. The parser buffers bytes and yields whole
+/// frames, so the reader thread never has to care where the read boundaries fell.
+#[derive(Default)]
+pub struct FrameParser {
+ buf: Vec<u8>,
+ in_block: bool,
+}
+
+impl FrameParser {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Feed bytes straight from a `read` call.
+ pub fn push(&mut self, bytes: &[u8]) {
+ self.buf.extend_from_slice(bytes);
+ }
+
+ /// Pop the next complete frame, or `None` while the buffer holds only a
+ /// partial line.
+ pub fn next_frame(&mut self) -> Option<Frame> {
+ let idx = self.buf.iter().position(|b| *b == b'\n')?;
+ let line: Vec<u8> = self.buf.drain(..=idx).collect();
+ let line = String::from_utf8_lossy(&line[..line.len() - 1])
+ .trim_end_matches('\r')
+ .to_string();
+ Some(self.classify(line))
+ }
+
+ fn classify(&mut self, line: String) -> Frame {
+ // A `%begin` block's payload is arbitrary text, so it is classified by
+ // position, never by a leading `%`.
+ if let Some(cmd) = frame_cmd(&line, "%begin") {
+ self.in_block = true;
+ return Frame::Begin { cmd };
+ }
+ if self.in_block {
+ if let Some(cmd) = frame_cmd(&line, "%end") {
+ self.in_block = false;
+ return Frame::End { cmd };
+ }
+ if let Some(cmd) = frame_cmd(&line, "%error") {
+ self.in_block = false;
+ return Frame::Error { cmd };
+ }
+ return Frame::Payload(line);
+ }
+ Frame::Notify(line)
+ }
+}
+
+/// `%begin 1788074601 521 0` β†’ `Some(521)`. A malformed or missing command
+/// number still frames the block; it is only used for logging.
+fn frame_cmd(line: &str, tag: &str) -> Option<u64> {
+ let rest = line.strip_prefix(tag)?;
+ if !rest.is_empty() && !rest.starts_with(' ') {
+ return None; // `%endsomething` is a different notification
+ }
+ Some(
+ rest.split_whitespace()
+ .nth(1)
+ .and_then(|n| n.parse().ok())
+ .unwrap_or(0),
+ )
+}
+
+/// State the reader thread publishes and the writer waits on.
+#[derive(Debug, Default)]
+struct ClientState {
+ /// Commands whose `%end`/`%error` has been seen. Commands complete in the
+ /// order they were issued, so this doubles as a barrier counter.
+ completed: u64,
+ /// The handshake sentinel came back.
+ ready: bool,
+ /// `%exit` or EOF β€” the tmux server or this client is gone.
+ alive: bool,
+ /// Last `%error` payload, for logs. Never contains pane input: tmux errors
+ /// name the target, not the keys.
+ last_error: Option<String>,
+ errors: u64,
+}
+
+#[derive(Debug, Default)]
+struct Shared {
+ state: Mutex<ClientState>,
+ cv: Condvar,
+}
+
+impl Shared {
+ fn signal(&self, f: impl FnOnce(&mut ClientState)) {
+ if let Ok(mut st) = self.state.lock() {
+ f(&mut st);
+ }
+ self.cv.notify_all();
+ }
+}
+
+/// A live `tmux -C` connection.
+///
+/// Owned exclusively by the input broker thread: `stdin` is a single writer by
+/// construction, which is what makes command ordering a property of the type
+/// rather than a convention.
+pub struct ControlClient {
+ child: Child,
+ stdin: ChildStdin,
+ shared: Arc<Shared>,
+ /// Commands this client has written.
+ issued: u64,
+ /// `completed - issued` at the end of the handshake. Attaching produces one
+ /// framed block of its own before we send anything, so a raw
+ /// `completed >= issued` comparison would let a barrier pass one command
+ /// early.
+ offset: u64,
+ generation: u64,
+}
+
+impl ControlClient {
+ /// Attach a control client to `session` on the `-L server` tmux server.
+ ///
+ /// Returns only once the connection has round-tripped a command, so a
+ /// caller that gets a `ControlClient` has one that works.
+ pub fn connect(server: &str, session: &str, generation: u64) -> Result<Self> {
+ let mut child = Command::new("tmux")
+ .args(["-L", server, "-C", "attach-session", "-t", session])
+ // See the module docs: size-neutral, and no pane output mirrored at us.
+ .args(["-f", "ignore-size,no-output"])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .context("failed to start tmux control-mode client")?;
+
+ let stdin = child
+ .stdin
+ .take()
+ .context("tmux control client has no stdin")?;
+ let stdout = child
+ .stdout
+ .take()
+ .context("tmux control client has no stdout")?;
+
+ let shared = Arc::new(Shared {
+ state: Mutex::new(ClientState {
+ alive: true,
+ ..Default::default()
+ }),
+ cv: Condvar::new(),
+ });
+
+ let reader_shared = Arc::clone(&shared);
+ std::thread::Builder::new()
+ .name(format!("agtx-tmux-control-{generation}"))
+ .spawn(move || read_loop(stdout, reader_shared))
+ .context("failed to start the control-mode reader thread")?;
+
+ let mut client = Self {
+ child,
+ stdin,
+ shared,
+ issued: 0,
+ offset: 0,
+ generation,
+ };
+
+ client.handshake().inspect_err(|_| {
+ client.kill();
+ })?;
+ Ok(client)
+ }
+
+ /// Prove the connection works, and learn how many framed blocks tmux emitted
+ /// on its own before we said anything.
+ fn handshake(&mut self) -> Result<()> {
+ self.write_command(&format!(
+ "display-message -p {}",
+ tmux_quote(READY_SENTINEL)
+ ))?;
+ let deadline = Instant::now() + HANDSHAKE_TIMEOUT;
+ let mut st = self
+ .shared
+ .state
+ .lock()
+ .map_err(|_| anyhow::anyhow!("control-mode state poisoned"))?;
+ while !st.ready && st.alive {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ anyhow::bail!("tmux control client did not answer within {HANDSHAKE_TIMEOUT:?}");
+ }
+ let (next, _) = self
+ .shared
+ .cv
+ .wait_timeout(st, remaining)
+ .map_err(|_| anyhow::anyhow!("control-mode state poisoned"))?;
+ st = next;
+ }
+ if !st.ready {
+ anyhow::bail!("tmux control client exited during handshake");
+ }
+ self.offset = st.completed.saturating_sub(self.issued);
+ Ok(())
+ }
+
+ /// Write one command. Returns as soon as the bytes are in the pipe β€” the
+ /// reply is not waited for, because the connection is FIFO and ordering,
+ /// not acknowledgement, is what callers need.
+ ///
+ /// An `Err` here is **ambiguous**: a partial write may have reached tmux.
+ /// Callers must not retry the command on another backend; see the broker.
+ pub fn write_command(&mut self, cmd: &str) -> Result<()> {
+ self.stdin.write_all(cmd.as_bytes())?;
+ self.stdin.write_all(b"\n")?;
+ self.stdin.flush()?;
+ self.issued += 1;
+ Ok(())
+ }
+
+ /// Block until every command written so far has been executed by the server.
+ ///
+ /// Used before handing work to the subprocess path, which travels a
+ /// *different* socket and could otherwise overtake commands still queued
+ /// here. Costs one round trip (~0.05 ms measured), not one per command.
+ pub fn barrier(&mut self, timeout: Duration) -> bool {
+ let want = self.issued + self.offset;
+ let deadline = Instant::now() + timeout;
+ let Ok(mut st) = self.shared.state.lock() else {
+ return false;
+ };
+ while st.completed < want && st.alive {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return false;
+ }
+ match self.shared.cv.wait_timeout(st, remaining) {
+ Ok((next, _)) => st = next,
+ Err(_) => return false,
+ }
+ }
+ st.completed >= want
+ }
+
+ pub fn alive(&self) -> bool {
+ self.shared.state.lock().map(|st| st.alive).unwrap_or(false)
+ }
+
+ pub fn generation(&self) -> u64 {
+ self.generation
+ }
+
+ /// Number of `%error` replies and the most recent message, for logging.
+ pub fn error_report(&self) -> (u64, Option<String>) {
+ self.shared
+ .state
+ .lock()
+ .map(|st| (st.errors, st.last_error.clone()))
+ .unwrap_or((0, None))
+ }
+
+ fn kill(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+
+ /// Close stdin and reap the client. tmux exits on EOF, so this is the
+ /// graceful path; the kill is only for a client that ignores it.
+ pub fn shutdown(self) {
+ // Destructured rather than `Option`-wrapped: dropping stdin is what asks
+ // tmux to exit, and making the field optional would put an unwrap on
+ // every write instead.
+ let ControlClient {
+ mut child, stdin, ..
+ } = self;
+ drop(stdin);
+ let deadline = Instant::now() + Duration::from_millis(500);
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => return,
+ Ok(None) if Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ _ => break,
+ }
+ }
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+}
+
+fn read_loop(mut stdout: std::process::ChildStdout, shared: Arc<Shared>) {
+ let mut parser = FrameParser::new();
+ let mut buf = [0u8; 8192];
+ let mut block_payload: Vec<String> = Vec::new();
+ loop {
+ let n = match stdout.read(&mut buf) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => n,
+ };
+ parser.push(&buf[..n]);
+ while let Some(frame) = parser.next_frame() {
+ match frame {
+ Frame::Begin { .. } => block_payload.clear(),
+ Frame::End { .. } => {
+ let ready = block_payload.iter().any(|l| l == READY_SENTINEL);
+ shared.signal(|st| {
+ st.completed += 1;
+ if ready {
+ st.ready = true;
+ }
+ });
+ block_payload.clear();
+ }
+ Frame::Error { cmd } => {
+ let msg = block_payload.join("; ");
+ tracing::debug!(cmd, error = %msg, "tmux control command failed");
+ shared.signal(|st| {
+ st.completed += 1;
+ st.errors += 1;
+ st.last_error = Some(msg);
+ });
+ block_payload.clear();
+ }
+ Frame::Payload(line) => block_payload.push(line),
+ Frame::Notify(line) => {
+ if line.starts_with("%exit") {
+ shared.signal(|st| st.alive = false);
+ }
+ }
+ }
+ }
+ }
+ shared.signal(|st| st.alive = false);
+}
+
+#[cfg(test)]
+#[path = "control_tests.rs"]
+mod control_tests;
diff --git a/src/tmux/control_tests.rs b/src/tmux/control_tests.rs
new file mode 100644
index 0000000..ca9eb1b
--- /dev/null
+++ b/src/tmux/control_tests.rs
@@ -0,0 +1,214 @@
+//! Unit tests for the control-mode encoder and frame parser.
+//!
+//! Both are pure, and both are places where a wrong answer is silent: a
+//! mis-encoded argument reaches tmux as a *different valid command*, and a
+//! mis-framed stream desynchronises every later reply. The real-tmux half of the
+//! contract lives in `tests/tmux_control_tests.rs`.
+
+use super::*;
+
+// --- encoder ---
+
+#[test]
+fn plain_text_is_just_quoted() {
+ assert_eq!(tmux_quote("hello"), "\"hello\"");
+ assert_eq!(tmux_quote(""), "\"\"");
+ assert_eq!(tmux_quote("has space"), "\"has space\"");
+}
+
+#[test]
+fn the_five_replacement_characters_are_escaped() {
+ // Each of these is replaced by tmux inside double quotes, so each must be
+ // defused. Verified against tmux 3.5a: unescaped, `$HOME` became the home
+ // directory and `#{…}` a format expansion.
+ assert_eq!(tmux_quote(r#"a"b"#), r#""a\"b""#);
+ assert_eq!(tmux_quote(r"a\b"), r#""a\\b""#);
+ assert_eq!(tmux_quote("$HOME"), r#""\$HOME""#);
+ assert_eq!(tmux_quote("#{pane_id}"), r#""\#{pane_id}""#);
+ assert_eq!(tmux_quote("~/src"), r#""\~/src""#);
+}
+
+#[test]
+fn a_trailing_backslash_cannot_continue_the_line() {
+ // An unescaped trailing `\` joins the next line β€” the next *command* β€” into
+ // this one's argument.
+ assert_eq!(tmux_quote("end\\"), "\"end\\\\\"");
+}
+
+#[test]
+fn whitespace_controls_become_escapes_not_raw_bytes() {
+ // A raw newline would end the command: commands are newline-terminated.
+ assert_eq!(tmux_quote("a\nb"), r#""a\nb""#);
+ assert_eq!(tmux_quote("a\rb"), r#""a\rb""#);
+ assert_eq!(tmux_quote("a\tb"), r#""a\tb""#);
+}
+
+#[test]
+fn other_control_characters_become_octal() {
+ assert_eq!(tmux_quote("\u{1}x"), "\"\\001x\"");
+ assert_eq!(tmux_quote("\u{1b}"), "\"\\033\"");
+ assert_eq!(tmux_quote("\u{7f}"), "\"\\177\"");
+}
+
+#[test]
+fn unicode_passes_through_untouched() {
+ assert_eq!(tmux_quote("ν•œκ΅­μ–΄"), "\"ν•œκ΅­μ–΄\"");
+ assert_eq!(tmux_quote("πŸ˜€"), "\"πŸ˜€\"");
+ assert_eq!(tmux_quote("naΓ―ve"), "\"naΓ―ve\"");
+}
+
+#[test]
+fn text_that_spells_a_key_name_is_still_text() {
+ // The encoder does not care β€” `-l` is what keeps these literal β€” but the
+ // quoting must not mangle them either.
+ for name in ["Space", "Enter", "Up", "C-c", "-x", "--"] {
+ assert_eq!(tmux_quote(name), format!("\"{name}\""));
+ }
+}
+
+#[test]
+fn a_semicolon_does_not_start_a_second_command() {
+ // Inside double quotes a `;` is literal, which is why it needs no escape β€”
+ // asserted so a future "escape everything" rewrite has to justify itself.
+ assert_eq!(tmux_quote("a;b"), "\"a;b\"");
+}
+
+// --- frame parser ---
+
+fn frames(chunks: &[&str]) -> Vec<Frame> {
+ let mut parser = FrameParser::new();
+ let mut out = Vec::new();
+ for chunk in chunks {
+ parser.push(chunk.as_bytes());
+ while let Some(frame) = parser.next_frame() {
+ out.push(frame);
+ }
+ }
+ out
+}
+
+#[test]
+fn a_command_block_is_framed() {
+ assert_eq!(
+ frames(&["%begin 1788074601 521 0\nhello\n%end 1788074601 521 0\n"]),
+ vec![
+ Frame::Begin { cmd: 521 },
+ Frame::Payload("hello".to_string()),
+ Frame::End { cmd: 521 },
+ ]
+ );
+}
+
+#[test]
+fn an_error_block_carries_its_message() {
+ assert_eq!(
+ frames(&["%begin 1 7 1\ncan't find window: w2\n%error 1 7 1\n"]),
+ vec![
+ Frame::Begin { cmd: 7 },
+ Frame::Payload("can't find window: w2".to_string()),
+ Frame::Error { cmd: 7 },
+ ]
+ );
+}
+
+#[test]
+fn reads_may_split_a_line_anywhere() {
+ // A pipe read is not a line. Splitting mid-token must not lose or duplicate
+ // a frame.
+ assert_eq!(
+ frames(&["%beg", "in 1 3 0\npay", "load\n%end 1 ", "3 0\n"]),
+ vec![
+ Frame::Begin { cmd: 3 },
+ Frame::Payload("payload".to_string()),
+ Frame::End { cmd: 3 },
+ ]
+ );
+}
+
+#[test]
+fn one_read_may_carry_many_frames() {
+ let out = frames(&["%begin 1 1 0\n%end 1 1 0\n%window-add @2\n%begin 1 2 0\n%end 1 2 0\n"]);
+ assert_eq!(out.len(), 5);
+ assert_eq!(out[2], Frame::Notify("%window-add @2".to_string()));
+}
+
+#[test]
+fn a_partial_trailing_line_yields_nothing_yet() {
+ let mut parser = FrameParser::new();
+ parser.push(b"%begin 1 1 0\n%en");
+ assert_eq!(parser.next_frame(), Some(Frame::Begin { cmd: 1 }));
+ assert_eq!(parser.next_frame(), None);
+ parser.push(b"d 1 1 0\n");
+ assert_eq!(parser.next_frame(), Some(Frame::End { cmd: 1 }));
+}
+
+#[test]
+fn notifications_outside_a_block_are_notifications() {
+ assert_eq!(
+ frames(&["%session-changed $0 s\n%exit\n"]),
+ vec![
+ Frame::Notify("%session-changed $0 s".to_string()),
+ Frame::Notify("%exit".to_string()),
+ ]
+ );
+}
+
+#[test]
+fn a_payload_line_starting_with_percent_is_payload() {
+ // `display-message -p` can print anything, `%exit` included. Position in the
+ // stream decides, not the leading character β€” otherwise a pane full of
+ // percent signs would look like the server going away.
+ assert_eq!(
+ frames(&["%begin 1 1 0\n%exit\n%end 1 1 0\n"]),
+ vec![
+ Frame::Begin { cmd: 1 },
+ Frame::Payload("%exit".to_string()),
+ Frame::End { cmd: 1 },
+ ]
+ );
+}
+
+#[test]
+fn a_malformed_begin_still_frames_the_block() {
+ // Losing the command number costs a log field. Losing the framing would
+ // desynchronise every later reply, so the parser is lenient here.
+ assert_eq!(
+ frames(&["%begin\npayload\n%end\n"]),
+ vec![
+ Frame::Begin { cmd: 0 },
+ Frame::Payload("payload".to_string()),
+ Frame::End { cmd: 0 },
+ ]
+ );
+}
+
+#[test]
+fn a_notification_that_merely_starts_like_a_tag_is_not_one() {
+ assert_eq!(
+ frames(&["%begin 1 1 0\n%end 1 1 0\n%exit-something-else\n"])
+ .last()
+ .cloned(),
+ Some(Frame::Notify("%exit-something-else".to_string()))
+ );
+}
+
+#[test]
+fn crlf_line_endings_are_tolerated() {
+ assert_eq!(
+ frames(&["%begin 1 1 0\r\nline\r\n%end 1 1 0\r\n"]),
+ vec![
+ Frame::Begin { cmd: 1 },
+ Frame::Payload("line".to_string()),
+ Frame::End { cmd: 1 },
+ ]
+ );
+}
+
+#[test]
+fn invalid_utf8_does_not_stall_the_parser() {
+ let mut parser = FrameParser::new();
+ parser.push(b"%begin 1 1 0\n\xff\xfe\n%end 1 1 0\n");
+ assert_eq!(parser.next_frame(), Some(Frame::Begin { cmd: 1 }));
+ assert!(matches!(parser.next_frame(), Some(Frame::Payload(_))));
+ assert_eq!(parser.next_frame(), Some(Frame::End { cmd: 1 }));
+}
diff --git a/src/tmux/input.rs b/src/tmux/input.rs
new file mode 100644
index 0000000..6cf1829
--- /dev/null
+++ b/src/tmux/input.rs
@@ -0,0 +1,821 @@
+//! Non-blocking pane input: the path a keystroke takes from the popup to tmux.
+//!
+//! ```text
+//! crossterm key event
+//! β”‚
+//! β–Ό
+//! PaneInputSink::send (TUI thread β€” enqueue only, never waits for tmux)
+//! β”‚
+//! bounded channel
+//! β”‚
+//! β–Ό
+//! one broker thread ── coalesces adjacent text, flushes before every key
+//! β”‚
+//! β”œβ”€β–Ί control-mode client (persistent process, ~0.05 ms/command)
+//! └─► subprocess fallback (`tmux send-keys`, ~25 ms/command)
+//! ```
+//!
+//! The broker is the **single ordering authority** for popup input. Nothing else
+//! may write keys to a task pane while a popup is open: `Text("abc")`,
+//! `Key("Left")`, `Text("X")`, `Key("Enter")` must reach tmux in that order, and
+//! they do because one thread executes them in receive order β€” across batching,
+//! across a backend switch, and across a reconnect.
+//!
+//! Coalescing is what makes fast typing cheap: adjacent characters for the same
+//! target become one `send-keys -l`. It is bounded by a few milliseconds and by
+//! a byte cap, and **never** delays a key that is not literal text, because a
+//! delayed Enter is a visibly broken editor.
+
+use anyhow::Result;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, TrySendError};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use super::control::{tmux_quote, ControlClient};
+use super::TmuxOperations;
+
+/// One request to put something into a pane.
+///
+/// Typed rather than preformatted tmux commands: the broker has to be able to
+/// tell literal text from a key name to decide what may be batched, and a
+/// formatted `send-keys` string has already thrown that distinction away.
+#[derive(Debug, Clone)]
+pub enum PaneInput {
+ /// Literal text (`send-keys -l`). Never goes through tmux's key-name lookup,
+ /// so text that spells `Space` or `Up` stays text.
+ Text { target: String, text: String },
+ /// A tmux **key name** (`Enter`, `Escape`, `C-c`, `M-b`, `F5`).
+ Key { target: String, key: String },
+ /// A whole block of text, bracketed-paste semantics.
+ Paste { target: String, text: String },
+ /// Deliver everything buffered now. Sent when a popup closes or changes
+ /// target, so queued text can never land in a different task's pane.
+ Flush,
+ /// Flush and acknowledge only after the active backend has executed every
+ /// preceding command. This is the ownership boundary used before the TUI
+ /// performs a synchronous tmux operation outside the broker.
+ Barrier { ack: std::sync::mpsc::Sender<bool> },
+ /// Flush, then stop the broker.
+ Shutdown,
+}
+
+impl PaneInput {
+ /// The pane this request is for, if it names one.
+ pub fn target(&self) -> Option<&str> {
+ match self {
+ PaneInput::Text { target, .. }
+ | PaneInput::Key { target, .. }
+ | PaneInput::Paste { target, .. } => Some(target),
+ PaneInput::Flush | PaneInput::Barrier { .. } | PaneInput::Shutdown => None,
+ }
+ }
+}
+
+impl PartialEq for PaneInput {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::Text { target: a, text: b }, Self::Text { target: c, text: d }) => {
+ a == c && b == d
+ }
+ (Self::Key { target: a, key: b }, Self::Key { target: c, key: d }) => a == c && b == d,
+ (Self::Paste { target: a, text: b }, Self::Paste { target: c, text: d }) => {
+ a == c && b == d
+ }
+ (Self::Flush, Self::Flush)
+ | (Self::Barrier { .. }, Self::Barrier { .. })
+ | (Self::Shutdown, Self::Shutdown) => true,
+ _ => false,
+ }
+ }
+}
+
+impl Eq for PaneInput {}
+
+/// Why an enqueue failed. Named, because the caller's recovery differs per case
+/// and "the input was dropped" must never be silent.
+#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
+pub enum InputError {
+ /// The broker is behind and the bounded queue is full.
+ #[error("pane input queue is full")]
+ QueueFull,
+ /// The broker thread is gone.
+ #[error("pane input broker is not running")]
+ Disconnected,
+ /// An acknowledged flush was not answered in time. The queued prefix is
+ /// still being delivered β€” it is *late*, not lost, which is why this is not
+ /// `Disconnected`: that variant tells the user to restart agtx, and here
+ /// there is nothing wrong to restart.
+ #[error("pane input did not drain in time")]
+ Timeout,
+}
+
+/// Where popup input is handed off. Implementations must not block the caller.
+pub trait PaneInputSink: Send + Sync {
+ fn send(&self, input: PaneInput) -> std::result::Result<(), InputError>;
+
+ fn text(&self, target: &str, text: &str) -> std::result::Result<(), InputError> {
+ self.send(PaneInput::Text {
+ target: target.to_string(),
+ text: text.to_string(),
+ })
+ }
+
+ fn key(&self, target: &str, key: &str) -> std::result::Result<(), InputError> {
+ self.send(PaneInput::Key {
+ target: target.to_string(),
+ key: key.to_string(),
+ })
+ }
+
+ fn paste(&self, target: &str, text: &str) -> std::result::Result<(), InputError> {
+ self.send(PaneInput::Paste {
+ target: target.to_string(),
+ text: text.to_string(),
+ })
+ }
+
+ fn flush(&self) -> std::result::Result<(), InputError> {
+ self.send(PaneInput::Flush)
+ }
+
+ /// Flush and wait until tmux has executed the queued prefix.
+ ///
+ /// The default keeps test/embedding sinks simple. The production broker
+ /// overrides this with an acknowledged barrier.
+ fn flush_sync(&self) -> std::result::Result<(), InputError> {
+ self.flush()
+ }
+
+ /// Deliver what is queued and stop. Called when agtx exits, so the last
+ /// characters typed into a pane are not lost with the process.
+ fn shutdown(&self) {
+ let _ = self.flush();
+ }
+
+ /// Point future control-mode connections at a different session.
+ ///
+ /// agtx switches project in place, and a session that no longer exists is
+ /// one the control client cannot attach to. An **already open** connection
+ /// is left alone on purpose: commands carry their own target and are
+ /// executed server-wide, so a client attached to the previous project still
+ /// delivers correctly. This only matters for the next connect.
+ fn set_session(&self, _session: &str) {}
+}
+
+/// What the broker writes through. Two implementations ship: the persistent
+/// control client and the one-process-per-command fallback.
+pub(crate) trait PaneBackend: Send {
+ fn text(&mut self, target: &str, text: &str) -> Result<()>;
+ fn key(&mut self, target: &str, key: &str) -> Result<()>;
+ fn paste(&mut self, target: &str, text: &str) -> Result<()>;
+ /// Block until everything written so far has actually been executed.
+ /// A no-op for a backend that is synchronous anyway.
+ fn barrier(&mut self) -> bool {
+ true
+ }
+ fn healthy(&self) -> bool {
+ true
+ }
+ fn label(&self) -> &'static str;
+}
+
+/// The historical path: one `tmux` process per command, via [`TmuxOperations`]
+/// so test mocks keep working unchanged.
+pub(crate) struct SubprocessBackend {
+ ops: Arc<dyn TmuxOperations>,
+}
+
+impl SubprocessBackend {
+ pub(crate) fn new(ops: Arc<dyn TmuxOperations>) -> Self {
+ Self { ops }
+ }
+}
+
+impl PaneBackend for SubprocessBackend {
+ fn text(&mut self, target: &str, text: &str) -> Result<()> {
+ self.ops.send_text(target, text)
+ }
+ fn key(&mut self, target: &str, key: &str) -> Result<()> {
+ self.ops.send_key(target, key)
+ }
+ fn paste(&mut self, target: &str, text: &str) -> Result<()> {
+ self.ops.paste_text(target, text)
+ }
+ fn label(&self) -> &'static str {
+ "subprocess"
+ }
+}
+
+/// The persistent path. Keys and text go down the control connection; a paste
+/// still goes through `load-buffer`, which needs a pipe rather than a command
+/// argument, so it is delegated β€” behind a barrier, because the two travel
+/// different sockets and only the barrier keeps them ordered.
+pub(crate) struct ControlBackend {
+ /// `Option` only so [`Drop`] can move the client out and close it. A dropped
+ /// `ControlClient` would otherwise leave an attached `tmux -C` process
+ /// running for the life of the server β€” one per reconnect.
+ client: Option<ControlClient>,
+ paste_via: SubprocessBackend,
+}
+
+impl ControlBackend {
+ pub(crate) fn new(client: ControlClient, ops: Arc<dyn TmuxOperations>) -> Self {
+ Self {
+ client: Some(client),
+ paste_via: SubprocessBackend::new(ops),
+ }
+ }
+
+ fn client(&mut self) -> Result<&mut ControlClient> {
+ self.client
+ .as_mut()
+ .ok_or_else(|| anyhow::anyhow!("control client already closed"))
+ }
+}
+
+impl Drop for ControlBackend {
+ fn drop(&mut self) {
+ if let Some(client) = self.client.take() {
+ client.shutdown();
+ }
+ }
+}
+
+/// How long a barrier waits before giving up and letting the paste race. Chosen
+/// well above the measured ~0.05 ms round trip: reaching it means tmux is wedged,
+/// and blocking the broker further would not help.
+const BARRIER_TIMEOUT: Duration = Duration::from_millis(250);
+
+impl PaneBackend for ControlBackend {
+ fn text(&mut self, target: &str, text: &str) -> Result<()> {
+ let cmd = format!(
+ "send-keys -t {} -l -- {}",
+ tmux_quote(target),
+ tmux_quote(text)
+ );
+ self.client()?.write_command(&cmd)
+ }
+ fn key(&mut self, target: &str, key: &str) -> Result<()> {
+ // No `-l`: this is exactly the key-name lookup `send_key` documents, and
+ // the reason a key and literal text cannot share one request type.
+ let cmd = format!("send-keys -t {} -- {}", tmux_quote(target), tmux_quote(key));
+ self.client()?.write_command(&cmd)
+ }
+ fn paste(&mut self, target: &str, text: &str) -> Result<()> {
+ // `load-buffer` needs a pipe, not a command argument, so a paste stays on
+ // the subprocess path. It travels a *different* socket, so without the
+ // barrier it could overtake text still queued on this connection.
+ let _ = self.barrier();
+ // Reported, never propagated. The broker reads an `Err` from this
+ // backend as an *ambiguous control write* and tears the connection
+ // down β€” but nothing was written to it here, and the request already
+ // ran on the fallback it would be moved to. Propagating would kill a
+ // healthy connection over an unrelated failure.
+ if let Err(e) = self.paste_via.paste(target, text) {
+ tracing::warn!(error = %e, "pane paste failed on the subprocess backend");
+ }
+ Ok(())
+ }
+ fn barrier(&mut self) -> bool {
+ if let Some(client) = self.client.as_mut() {
+ let completed = client.barrier(BARRIER_TIMEOUT);
+ if !completed {
+ tracing::debug!("tmux control barrier timed out");
+ }
+ completed
+ } else {
+ false
+ }
+ }
+ fn healthy(&self) -> bool {
+ self.client.as_ref().map(|c| c.alive()).unwrap_or(false)
+ }
+ fn label(&self) -> &'static str {
+ "control"
+ }
+}
+
+/// Why the broker decided to deliver its buffered text.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum FlushReason {
+ /// The batching window elapsed.
+ Window,
+ /// A non-text request came next.
+ BeforeKey,
+ /// The next text is for a different pane.
+ TargetChange,
+ /// The buffer hit its byte cap.
+ Full,
+ /// A `Flush` request.
+ Explicit,
+ /// The broker is stopping.
+ Shutdown,
+}
+
+/// How long adjacent characters may wait to be combined.
+///
+/// Two milliseconds is short enough to be invisible next to the ~16 ms a typical
+/// key repeat takes and the 50 ms pane refresh, and long enough to sweep up a
+/// burst of pasted-as-keystrokes characters. It is the plan's starting value;
+/// raising it trades echo latency for fewer commands, which only pays on the
+/// subprocess backend.
+pub const DEFAULT_BATCH_WINDOW: Duration = Duration::from_millis(2);
+
+/// Byte cap on one coalesced `send-keys`. Well under any command-length limit,
+/// and it bounds how much text a single failed write can lose.
+const MAX_BATCH_BYTES: usize = 4096;
+
+/// Bounded queue depth. Deep enough that a human cannot fill it (it is ~40
+/// seconds of typing at 25 keys/s) and shallow enough to bound memory if tmux
+/// stops consuming.
+pub const DEFAULT_QUEUE_CAPACITY: usize = 1024;
+
+/// Reconnect backoff bounds for the control client.
+const RECONNECT_MIN: Duration = Duration::from_millis(250);
+const RECONNECT_MAX: Duration = Duration::from_secs(5);
+
+/// How long an acknowledged flush waits for the broker to answer.
+///
+/// **Not** a second copy of [`BARRIER_TIMEOUT`]. The barrier sits *behind the
+/// queue*, so this wait is dominated by draining whatever is already in it β€” and
+/// on the subprocess backend every queued command is a ~25 ms process, so a
+/// barrier-sized budget expires mid-drain and hands back a guarantee that was
+/// not kept. Measured: 20 queued keys at 25 ms each returned an error after
+/// 300 ms with half of them still in flight.
+///
+/// So this is the "the broker is wedged" guard instead. The work it waits on is
+/// the user's own keystrokes, so in practice it returns in microseconds; the cap
+/// only exists so a hung tmux cannot freeze the TUI thread forever.
+const FLUSH_SYNC_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// Bounds on quitting: how long to keep trying to enqueue the stop request, and
+/// how long to wait for the broker's final flush afterwards.
+const SHUTDOWN_ENQUEUE_WAIT: Duration = Duration::from_millis(200);
+const SHUTDOWN_DRAIN_WAIT: Duration = Duration::from_millis(500);
+
+/// How to build the input pipeline.
+#[derive(Debug, Clone)]
+pub struct InputConfig {
+ /// tmux server name (`-L`).
+ pub server: String,
+ /// Session the control client attaches to. Commands still carry their own
+ /// targets; this is only an attach point.
+ pub session: String,
+ /// Try the persistent control-mode backend. On by default; a failure to
+ /// connect, or a connection lost later, falls back to the subprocess
+ /// backend on its own. See `control_mode_enabled` for the escape hatch.
+ pub control_mode: bool,
+ pub batch_window: Duration,
+ pub capacity: usize,
+}
+
+impl InputConfig {
+ pub fn new(server: impl Into<String>, session: impl Into<String>) -> Self {
+ Self {
+ server: server.into(),
+ session: session.into(),
+ control_mode: true,
+ batch_window: DEFAULT_BATCH_WINDOW,
+ capacity: DEFAULT_QUEUE_CAPACITY,
+ }
+ }
+}
+
+/// Handle held by the TUI. `send` is an enqueue and nothing else.
+pub struct BrokerSink {
+ tx: SyncSender<PaneInput>,
+ depth: Arc<AtomicUsize>,
+ high_water: Arc<AtomicUsize>,
+ /// Read by the control factory at every connect, so a project switch is
+ /// picked up without restarting the broker.
+ session: Arc<Mutex<String>>,
+ /// Set by the broker as the last thing it does. Lets shutdown wait for the
+ /// final flush *without* an unbounded `join` β€” see below.
+ finished: Arc<AtomicBool>,
+ join: Mutex<Option<std::thread::JoinHandle<()>>>,
+}
+
+impl BrokerSink {
+ /// Queue depth right now, and the deepest it has ever been. Diagnostics only.
+ pub fn depth(&self) -> (usize, usize) {
+ (
+ self.depth.load(Ordering::Relaxed),
+ self.high_water.load(Ordering::Relaxed),
+ )
+ }
+}
+
+impl PaneInputSink for BrokerSink {
+ fn set_session(&self, session: &str) {
+ if let Ok(mut current) = self.session.lock() {
+ if *current != session {
+ tracing::debug!(session, "control-mode attach point changed");
+ *current = session.to_string();
+ }
+ }
+ }
+
+ /// Flush, stop the broker thread, and wait for it β€” but never forever.
+ ///
+ /// Quitting must not be able to hang. The broker can be blocked inside a
+ /// `tmux` subprocess that is not coming back, and both a blocking `send` and
+ /// a plain `join` would then wait for it with no bound. So both steps are
+ /// bounded, and if the broker misses its window the thread is simply left to
+ /// the exiting process. Safe to call twice.
+ fn shutdown(&self) {
+ let deadline = Instant::now() + SHUTDOWN_ENQUEUE_WAIT;
+ let mut queued = false;
+ while Instant::now() < deadline {
+ self.depth.fetch_add(1, Ordering::Relaxed);
+ match self.tx.try_send(PaneInput::Shutdown) {
+ Ok(()) => {
+ queued = true;
+ break;
+ }
+ // Backed up: give the broker a moment to drain, since what is
+ // queued is the user's last keystrokes.
+ Err(TrySendError::Full(_)) => {
+ self.depth.fetch_sub(1, Ordering::Relaxed);
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ Err(TrySendError::Disconnected(_)) => {
+ self.depth.fetch_sub(1, Ordering::Relaxed);
+ queued = true;
+ break;
+ }
+ }
+ }
+ if !queued {
+ tracing::warn!("pane input broker did not accept shutdown; leaving it to exit");
+ return;
+ }
+ let deadline = Instant::now() + SHUTDOWN_DRAIN_WAIT;
+ while !self.finished.load(Ordering::Relaxed) {
+ if Instant::now() >= deadline {
+ tracing::warn!("pane input broker did not finish draining in time");
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ if let Ok(mut join) = self.join.lock() {
+ if let Some(handle) = join.take() {
+ let _ = handle.join();
+ }
+ }
+ }
+
+ fn flush_sync(&self) -> std::result::Result<(), InputError> {
+ let (ack, done) = std::sync::mpsc::channel();
+ self.send(PaneInput::Barrier { ack })?;
+ match done.recv_timeout(FLUSH_SYNC_TIMEOUT) {
+ Ok(true) => Ok(()),
+ // The control barrier gave up; the broker is alive and answered.
+ Ok(false) => Err(InputError::Timeout),
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(InputError::Timeout),
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(InputError::Disconnected),
+ }
+ }
+
+ fn send(&self, input: PaneInput) -> std::result::Result<(), InputError> {
+ // Counted *before* the send, and rolled back if it fails. The other
+ // order is a race: the broker can receive and decrement between the
+ // successful `try_send` and this `fetch_add`, taking the counter below
+ // zero β€” which on a `usize` is not a small error but `usize::MAX`.
+ // Over-counting for a few nanoseconds is the harmless direction.
+ let depth = self.depth.fetch_add(1, Ordering::Relaxed) + 1;
+ self.high_water.fetch_max(depth, Ordering::Relaxed);
+ match self.tx.try_send(input) {
+ Ok(()) => Ok(()),
+ Err(TrySendError::Full(_)) => {
+ self.depth.fetch_sub(1, Ordering::Relaxed);
+ Err(InputError::QueueFull)
+ }
+ Err(TrySendError::Disconnected(_)) => {
+ self.depth.fetch_sub(1, Ordering::Relaxed);
+ Err(InputError::Disconnected)
+ }
+ }
+ }
+}
+
+/// Start the broker thread and return the sink the TUI enqueues into.
+pub fn spawn(config: InputConfig, ops: Arc<dyn TmuxOperations>) -> Arc<BrokerSink> {
+ let (tx, rx) = std::sync::mpsc::sync_channel(config.capacity);
+ let depth = Arc::new(AtomicUsize::new(0));
+ let high_water = Arc::new(AtomicUsize::new(0));
+ let session = Arc::new(Mutex::new(config.session.clone()));
+ let finished = Arc::new(AtomicBool::new(false));
+
+ let control_factory: Option<ControlFactory> = if config.control_mode {
+ let server = config.server.clone();
+ let session = Arc::clone(&session);
+ let ops = Arc::clone(&ops);
+ Some(Box::new(move |generation| {
+ let attach = session
+ .lock()
+ .map(|s| s.clone())
+ .map_err(|_| anyhow::anyhow!("attach session poisoned"))?;
+ let client = ControlClient::connect(&server, &attach, generation)?;
+ Ok(Box::new(ControlBackend::new(client, Arc::clone(&ops))) as Box<dyn PaneBackend>)
+ }))
+ } else {
+ None
+ };
+
+ let broker = Broker {
+ rx,
+ depth: Arc::clone(&depth),
+ batch_window: config.batch_window,
+ fallback: Box::new(SubprocessBackend::new(ops)),
+ control: None,
+ control_factory,
+ generation: 0,
+ next_attempt: Some(Instant::now()),
+ backoff: RECONNECT_MIN,
+ pending: None,
+ deadline: None,
+ fallbacks: 0,
+ finished: Arc::clone(&finished),
+ };
+
+ let join = std::thread::Builder::new()
+ .name("agtx-pane-input".to_string())
+ .spawn(move || broker.run())
+ .ok();
+ if join.is_none() {
+ // Nothing will ever set `finished`, and `shutdown` would then wait out
+ // its whole drain budget on every quit. Mark it done now; the sink's
+ // sends fail with `Disconnected`, which the TUI already surfaces.
+ tracing::error!("failed to start the pane input broker thread");
+ finished.store(true, Ordering::Relaxed);
+ }
+
+ Arc::new(BrokerSink {
+ tx,
+ depth,
+ high_water,
+ session,
+ finished,
+ join: Mutex::new(join),
+ })
+}
+
+type ControlFactory = Box<dyn FnMut(u64) -> Result<Box<dyn PaneBackend>> + Send>;
+
+pub(crate) struct Broker {
+ rx: Receiver<PaneInput>,
+ depth: Arc<AtomicUsize>,
+ batch_window: Duration,
+ fallback: Box<dyn PaneBackend>,
+ control: Option<Box<dyn PaneBackend>>,
+ control_factory: Option<ControlFactory>,
+ generation: u64,
+ next_attempt: Option<Instant>,
+ backoff: Duration,
+ pending: Option<(String, String)>,
+ deadline: Option<Instant>,
+ fallbacks: u64,
+ finished: Arc<AtomicBool>,
+}
+
+impl Broker {
+ pub(crate) fn run(mut self) {
+ loop {
+ let next = match self.deadline {
+ Some(deadline) => {
+ let wait = deadline.saturating_duration_since(Instant::now());
+ match self.rx.recv_timeout(wait) {
+ Ok(input) => Some(input),
+ Err(RecvTimeoutError::Timeout) => {
+ self.flush(FlushReason::Window);
+ continue;
+ }
+ Err(RecvTimeoutError::Disconnected) => None,
+ }
+ }
+ None => self.rx.recv().ok(),
+ };
+
+ let Some(input) = next else {
+ // Every sink handle was dropped: deliver what is buffered rather
+ // than losing the last word the user typed.
+ self.flush(FlushReason::Shutdown);
+ break;
+ };
+ self.depth.fetch_sub(1, Ordering::Relaxed);
+
+ match input {
+ PaneInput::Text { target, text } => self.push_text(target, text),
+ PaneInput::Key { target, key } => {
+ self.flush(FlushReason::BeforeKey);
+ self.dispatch(|b| b.key(&target, &key), "key");
+ }
+ PaneInput::Paste { target, text } => {
+ self.flush(FlushReason::BeforeKey);
+ let len = text.len();
+ self.dispatch(|b| b.paste(&target, &text), "paste");
+ tracing::debug!(bytes = len, "pane paste delivered");
+ }
+ PaneInput::Flush => self.flush(FlushReason::Explicit),
+ PaneInput::Barrier { ack } => {
+ self.flush(FlushReason::Explicit);
+ let completed = self.barrier();
+ let _ = ack.send(completed);
+ }
+ PaneInput::Shutdown => {
+ self.flush(FlushReason::Shutdown);
+ break;
+ }
+ }
+ }
+ if let Some(control) = self.control.take() {
+ drop(control);
+ }
+ self.finished.store(true, Ordering::Relaxed);
+ }
+
+ fn push_text(&mut self, target: String, text: String) {
+ match &mut self.pending {
+ Some((pending_target, buf)) if *pending_target == target => {
+ buf.push_str(&text);
+ if buf.len() >= MAX_BATCH_BYTES {
+ self.flush(FlushReason::Full);
+ }
+ }
+ Some(_) => {
+ // Different pane: everything buffered belongs to the old one and
+ // must land there first.
+ self.flush(FlushReason::TargetChange);
+ self.pending = Some((target, text));
+ self.deadline = Some(Instant::now() + self.batch_window);
+ }
+ None => {
+ self.pending = Some((target, text));
+ self.deadline = Some(Instant::now() + self.batch_window);
+ }
+ }
+ }
+
+ fn flush(&mut self, reason: FlushReason) {
+ self.deadline = None;
+ let Some((target, text)) = self.pending.take() else {
+ return;
+ };
+ let chars = text.chars().count();
+ self.dispatch(|b| b.text(&target, &text), "text");
+ // Lengths and reasons only: pane input is never logged.
+ tracing::trace!(?reason, chars, "pane text flushed");
+ }
+
+ fn barrier(&mut self) -> bool {
+ match self.control.as_mut() {
+ Some(control) if control.healthy() => control.barrier(),
+ // The subprocess backend is synchronous. If control died after the
+ // preceding dispatch, that dispatch was deliberately treated as
+ // ambiguous and cannot be made safer by waiting here.
+ _ => true,
+ }
+ }
+
+ /// Run one operation on the best available backend.
+ ///
+ /// A control-mode write error is **ambiguous** β€” a partial write may already
+ /// have reached tmux β€” so the request is dropped rather than replayed on the
+ /// fallback. Repeating an Enter is worse than losing one, and the *next*
+ /// request goes to the fallback anyway because the failure marks the
+ /// connection dead.
+ fn dispatch(&mut self, op: impl FnOnce(&mut dyn PaneBackend) -> Result<()>, kind: &str) {
+ self.maybe_connect();
+ let started = Instant::now();
+ if let Some(control) = self.control.as_mut() {
+ if control.healthy() {
+ match op(control.as_mut()) {
+ Ok(()) => {
+ tracing::trace!(
+ kind,
+ backend = "control",
+ micros = started.elapsed().as_micros() as u64,
+ "pane input delivered"
+ );
+ return;
+ }
+ Err(e) => {
+ self.drop_control(&format!("write failed: {e}"));
+ tracing::warn!(kind, "pane input dropped after an ambiguous control write");
+ return;
+ }
+ }
+ }
+ self.drop_control("connection closed");
+ }
+ self.fallbacks += 1;
+ if let Err(e) = op(self.fallback.as_mut()) {
+ tracing::warn!(kind, error = %e, "pane input failed on the subprocess backend");
+ } else {
+ tracing::trace!(
+ kind,
+ backend = "subprocess",
+ micros = started.elapsed().as_micros() as u64,
+ "pane input delivered"
+ );
+ }
+ }
+
+ fn drop_control(&mut self, reason: &str) {
+ if self.control.take().is_some() {
+ tracing::info!(
+ generation = self.generation,
+ reason,
+ "tmux control connection lost; falling back to subprocess"
+ );
+ }
+ self.next_attempt = Some(Instant::now() + self.backoff);
+ self.backoff = (self.backoff * 2).min(RECONNECT_MAX);
+ }
+
+ fn maybe_connect(&mut self) {
+ if self.control.is_some() || self.control_factory.is_none() {
+ return;
+ }
+ match self.next_attempt {
+ Some(at) if Instant::now() < at => return,
+ None => return,
+ _ => {}
+ }
+ self.next_attempt = None;
+ self.generation += 1;
+ let generation = self.generation;
+ let factory = self.control_factory.as_mut().expect("checked above");
+ match factory(generation) {
+ Ok(backend) => {
+ tracing::info!(
+ generation,
+ backend = backend.label(),
+ "pane input backend ready"
+ );
+ self.control = Some(backend);
+ self.backoff = RECONNECT_MIN;
+ }
+ Err(e) => {
+ tracing::info!(generation, error = %e, "tmux control connect failed; using subprocess");
+ self.next_attempt = Some(Instant::now() + self.backoff);
+ self.backoff = (self.backoff * 2).min(RECONNECT_MAX);
+ }
+ }
+ }
+}
+
+/// A sink that records requests instead of sending them. For tests that assert
+/// what the UI enqueued without needing a tmux server.
+#[cfg(any(test, feature = "test-mocks"))]
+#[derive(Default)]
+pub struct RecordingSink {
+ sent: Mutex<Vec<PaneInput>>,
+ /// When set, every `send` fails with it β€” for exercising `QueueFull`.
+ fail_with: Mutex<Option<InputError>>,
+}
+
+#[cfg(any(test, feature = "test-mocks"))]
+impl RecordingSink {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn taken(&self) -> Vec<PaneInput> {
+ self.sent.lock().map(|s| s.clone()).unwrap_or_default()
+ }
+
+ pub fn fail_with(&self, err: InputError) {
+ if let Ok(mut slot) = self.fail_with.lock() {
+ *slot = Some(err);
+ }
+ }
+}
+
+#[cfg(any(test, feature = "test-mocks"))]
+impl PaneInputSink for RecordingSink {
+ /// Records the barrier rather than degrading to a plain `Flush`, so a test
+ /// can tell the two apart. Without this the default turns `flush_sync` into
+ /// `flush` and nothing pins which one a call site asked for.
+ fn flush_sync(&self) -> std::result::Result<(), InputError> {
+ let (ack, _done) = std::sync::mpsc::channel();
+ self.send(PaneInput::Barrier { ack })
+ }
+
+ fn send(&self, input: PaneInput) -> std::result::Result<(), InputError> {
+ if let Ok(slot) = self.fail_with.lock() {
+ if let Some(err) = slot.as_ref() {
+ return Err(err.clone());
+ }
+ }
+ if let Ok(mut sent) = self.sent.lock() {
+ sent.push(input);
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+#[path = "input_tests.rs"]
+mod input_tests;
diff --git a/src/tmux/input_tests.rs b/src/tmux/input_tests.rs
new file mode 100644
index 0000000..9fe6a90
--- /dev/null
+++ b/src/tmux/input_tests.rs
@@ -0,0 +1,701 @@
+//! Unit tests for the input broker.
+//!
+//! These assert **byte and key order**, not final visible text: a batching bug
+//! that swaps a cursor key past the characters around it produces the same pane
+//! content in a test and the wrong text in a real editor.
+
+use super::*;
+use std::sync::mpsc::sync_channel;
+
+/// What a backend was asked to do, in order.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Op {
+ Text(String, String),
+ Key(String, String),
+ Paste(String, String),
+ Barrier,
+ OutsideTmuxOperation,
+}
+
+#[derive(Clone, Default)]
+struct Recorder {
+ ops: Arc<Mutex<Vec<Op>>>,
+}
+
+impl Recorder {
+ fn ops(&self) -> Vec<Op> {
+ self.ops.lock().unwrap().clone()
+ }
+ fn push(&self, op: Op) {
+ self.ops.lock().unwrap().push(op);
+ }
+}
+
+struct RecordingBackend {
+ label: &'static str,
+ recorder: Recorder,
+ /// Fail every write, as a broken control connection does.
+ failing: bool,
+ /// Report itself as dead, as a `%exit`ed connection does.
+ dead: Arc<std::sync::atomic::AtomicBool>,
+}
+
+impl RecordingBackend {
+ fn new(label: &'static str, recorder: Recorder) -> Self {
+ Self {
+ label,
+ recorder,
+ failing: false,
+ dead: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ }
+ }
+}
+
+impl PaneBackend for RecordingBackend {
+ fn text(&mut self, target: &str, text: &str) -> Result<()> {
+ if self.failing {
+ anyhow::bail!("write failed");
+ }
+ self.recorder.push(Op::Text(
+ format!("{}:{target}", self.label),
+ text.to_string(),
+ ));
+ Ok(())
+ }
+ fn key(&mut self, target: &str, key: &str) -> Result<()> {
+ if self.failing {
+ anyhow::bail!("write failed");
+ }
+ self.recorder
+ .push(Op::Key(format!("{}:{target}", self.label), key.to_string()));
+ Ok(())
+ }
+ fn paste(&mut self, target: &str, text: &str) -> Result<()> {
+ if self.failing {
+ anyhow::bail!("write failed");
+ }
+ self.recorder.push(Op::Paste(
+ format!("{}:{target}", self.label),
+ text.to_string(),
+ ));
+ Ok(())
+ }
+ fn barrier(&mut self) -> bool {
+ self.recorder.push(Op::Barrier);
+ true
+ }
+ fn healthy(&self) -> bool {
+ !self.dead.load(std::sync::atomic::Ordering::Relaxed)
+ }
+ fn label(&self) -> &'static str {
+ self.label
+ }
+}
+
+/// A batching window long enough that only an explicit flush can end it, so a
+/// test asserting coalescing is not really asserting how fast the machine is.
+const NEVER: Duration = Duration::from_secs(3600);
+
+struct Harness {
+ tx: SyncSender<PaneInput>,
+ depth: Arc<AtomicUsize>,
+ join: std::thread::JoinHandle<()>,
+ recorder: Recorder,
+}
+
+impl Harness {
+ fn send(&self, input: PaneInput) {
+ self.depth.fetch_add(1, Ordering::Relaxed);
+ self.tx.send(input).expect("broker is running");
+ }
+ fn text(&self, target: &str, text: &str) {
+ self.send(PaneInput::Text {
+ target: target.to_string(),
+ text: text.to_string(),
+ });
+ }
+ fn key(&self, target: &str, key: &str) {
+ self.send(PaneInput::Key {
+ target: target.to_string(),
+ key: key.to_string(),
+ });
+ }
+ fn flush_sync(&self) {
+ let (ack, done) = std::sync::mpsc::channel();
+ self.send(PaneInput::Barrier { ack });
+ assert_eq!(done.recv_timeout(Duration::from_secs(1)), Ok(true));
+ }
+ /// Stop the broker and return everything the backends were asked to do.
+ fn finish(self) -> Vec<Op> {
+ self.send(PaneInput::Shutdown);
+ self.join.join().expect("broker thread");
+ self.recorder.ops()
+ }
+}
+
+fn harness(batch_window: Duration) -> Harness {
+ harness_with(batch_window, Recorder::default(), None)
+}
+
+/// Both backends record into the **same** log, so a test can assert not just
+/// what was delivered but which backend delivered it, in one order.
+fn harness_with(
+ batch_window: Duration,
+ recorder: Recorder,
+ control_factory: Option<ControlFactory>,
+) -> Harness {
+ let (tx, rx) = sync_channel(64);
+ let depth = Arc::new(AtomicUsize::new(0));
+ let broker = Broker {
+ rx,
+ depth: Arc::clone(&depth),
+ batch_window,
+ fallback: Box::new(RecordingBackend::new("sub", recorder.clone())),
+ control: None,
+ control_factory,
+ generation: 0,
+ next_attempt: Some(Instant::now()),
+ backoff: Duration::from_millis(1),
+ pending: None,
+ deadline: None,
+ fallbacks: 0,
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ };
+ let join = std::thread::spawn(move || broker.run());
+ Harness {
+ tx,
+ depth,
+ join,
+ recorder,
+ }
+}
+
+#[test]
+fn adjacent_text_for_one_target_is_coalesced() {
+ let h = harness(NEVER);
+ h.text("s:w", "a");
+ h.text("s:w", "b");
+ h.text("s:w", "c");
+ assert_eq!(h.finish(), vec![Op::Text("sub:s:w".into(), "abc".into())]);
+}
+
+#[test]
+fn text_is_never_coalesced_across_targets() {
+ // Queued characters belong to the pane they were typed into. Merging them
+ // across a target change would type one task's input into another's agent.
+ let h = harness(NEVER);
+ h.text("s:one", "ab");
+ h.text("s:two", "cd");
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("sub:s:one".into(), "ab".into()),
+ Op::Text("sub:s:two".into(), "cd".into()),
+ ]
+ );
+}
+
+#[test]
+fn a_key_flushes_buffered_text_first_and_is_never_delayed() {
+ let h = harness(NEVER);
+ h.text("s:w", "abc");
+ h.key("s:w", "Left");
+ h.text("s:w", "X");
+ h.key("s:w", "Enter");
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("sub:s:w".into(), "abc".into()),
+ Op::Key("sub:s:w".into(), "Left".into()),
+ Op::Text("sub:s:w".into(), "X".into()),
+ Op::Key("sub:s:w".into(), "Enter".into()),
+ ]
+ );
+}
+
+#[test]
+fn an_explicit_flush_delivers_the_prefix() {
+ // What a popup close does: whatever was typed lands in the pane it was typed
+ // into, before the target can change.
+ let h = harness(NEVER);
+ h.text("s:w", "half");
+ h.send(PaneInput::Flush);
+ h.text("s:w", "rest");
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("sub:s:w".into(), "half".into()),
+ Op::Text("sub:s:w".into(), "rest".into()),
+ ]
+ );
+}
+
+#[test]
+fn an_acknowledged_flush_prevents_an_external_tmux_operation_from_overtaking_input() {
+ let h = harness(NEVER);
+ h.text("s:w", "typed-before-resize");
+
+ // This models Ctrl+F: the resize is issued synchronously by the TUI after
+ // the broker boundary returns. A plain `Flush` enqueue can return before
+ // the text is delivered; the acknowledged barrier may not.
+ h.flush_sync();
+ h.recorder.push(Op::OutsideTmuxOperation);
+
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("sub:s:w".into(), "typed-before-resize".into()),
+ Op::OutsideTmuxOperation,
+ ]
+ );
+}
+
+/// A backend whose every command costs what a `tmux` subprocess costs.
+struct SlowBackend {
+ recorder: Recorder,
+ per_command: Duration,
+}
+
+impl PaneBackend for SlowBackend {
+ fn text(&mut self, target: &str, text: &str) -> Result<()> {
+ std::thread::sleep(self.per_command);
+ self.recorder
+ .push(Op::Text(format!("slow:{target}"), text.to_string()));
+ Ok(())
+ }
+ fn key(&mut self, target: &str, key: &str) -> Result<()> {
+ std::thread::sleep(self.per_command);
+ self.recorder
+ .push(Op::Key(format!("slow:{target}"), key.to_string()));
+ Ok(())
+ }
+ fn paste(&mut self, _target: &str, _text: &str) -> Result<()> {
+ Ok(())
+ }
+ fn label(&self) -> &'static str {
+ "slow"
+ }
+}
+
+#[test]
+fn an_acknowledged_flush_waits_out_a_slow_drain() {
+ // The barrier sits *behind* the queue, so the wait is dominated by draining
+ // it β€” not by the barrier round trip. Sized as a barrier round trip instead,
+ // it expired mid-drain and handed back a guarantee that had not been kept:
+ // measured at 20 queued keys x 25 ms, it reported failure with half of them
+ // still in flight, and the caller went on to resize the pane anyway.
+ let recorder = Recorder::default();
+ let (tx, rx) = sync_channel(64);
+ let depth = Arc::new(AtomicUsize::new(0));
+ let broker = Broker {
+ rx,
+ depth: Arc::clone(&depth),
+ batch_window: NEVER,
+ fallback: Box::new(SlowBackend {
+ recorder: recorder.clone(),
+ per_command: Duration::from_millis(25),
+ }),
+ control: None,
+ control_factory: None,
+ generation: 0,
+ next_attempt: None,
+ backoff: Duration::from_millis(1),
+ pending: None,
+ deadline: None,
+ fallbacks: 0,
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ };
+ std::thread::spawn(move || broker.run());
+ let sink = BrokerSink {
+ tx,
+ depth,
+ high_water: Arc::new(AtomicUsize::new(0)),
+ session: Arc::new(Mutex::new("it".to_string())),
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ join: Mutex::new(None),
+ };
+
+ // Non-text keys, because adjacent text would coalesce into one command.
+ for _ in 0..20 {
+ sink.key("s:w", "BSpace").unwrap();
+ }
+ assert_eq!(sink.flush_sync(), Ok(()));
+ assert_eq!(
+ recorder.ops().len(),
+ 20,
+ "every queued key must have been delivered before the flush returned"
+ );
+}
+
+#[test]
+fn the_batching_window_flushes_on_its_own() {
+ let h = harness(Duration::from_millis(1));
+ h.text("s:w", "a");
+ std::thread::sleep(Duration::from_millis(60));
+ h.text("s:w", "b");
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("sub:s:w".into(), "a".into()),
+ Op::Text("sub:s:w".into(), "b".into()),
+ ]
+ );
+}
+
+#[test]
+fn shutdown_delivers_what_is_still_buffered() {
+ let h = harness(NEVER);
+ h.text("s:w", "unsent");
+ assert_eq!(
+ h.finish(),
+ vec![Op::Text("sub:s:w".into(), "unsent".into())]
+ );
+}
+
+#[test]
+fn dropping_every_sender_still_delivers_the_last_word() {
+ let recorder = Recorder::default();
+ let (tx, rx) = sync_channel(8);
+ let broker = Broker {
+ rx,
+ depth: Arc::new(AtomicUsize::new(0)),
+ batch_window: NEVER,
+ fallback: Box::new(RecordingBackend::new("sub", recorder.clone())),
+ control: None,
+ control_factory: None,
+ generation: 0,
+ next_attempt: None,
+ backoff: Duration::from_millis(1),
+ pending: None,
+ deadline: None,
+ fallbacks: 0,
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ };
+ let join = std::thread::spawn(move || broker.run());
+ tx.send(PaneInput::Text {
+ target: "s:w".into(),
+ text: "tail".into(),
+ })
+ .unwrap();
+ drop(tx);
+ join.join().unwrap();
+ assert_eq!(
+ recorder.ops(),
+ vec![Op::Text("sub:s:w".into(), "tail".into())]
+ );
+}
+
+#[test]
+fn unicode_survives_coalescing() {
+ let h = harness(NEVER);
+ for ch in "ν•œκ΅­μ–΄πŸ˜€".chars() {
+ h.text("s:w", &ch.to_string());
+ }
+ assert_eq!(
+ h.finish(),
+ vec![Op::Text("sub:s:w".into(), "ν•œκ΅­μ–΄πŸ˜€".into())]
+ );
+}
+
+#[test]
+fn a_batch_is_capped_in_bytes() {
+ // The cap bounds how much one failed write can lose, and keeps a command
+ // line at a size tmux is comfortable with.
+ let h = harness(NEVER);
+ let chunk = "x".repeat(1000);
+ for _ in 0..10 {
+ h.text("s:w", &chunk);
+ }
+ let ops = h.finish();
+ assert!(
+ ops.len() > 1,
+ "10 KiB must not go out as one write: {ops:?}"
+ );
+ let mut total = 0;
+ for op in &ops {
+ match op {
+ Op::Text(_, text) => {
+ assert!(
+ text.len() <= MAX_BATCH_BYTES + chunk.len(),
+ "a batch overshot the cap by more than one request"
+ );
+ total += text.len();
+ }
+ other => panic!("expected text writes, got {other:?}"),
+ }
+ }
+ assert_eq!(total, 10_000, "no character may be lost to the cap");
+}
+
+#[test]
+fn a_paste_flushes_first_and_stays_atomic() {
+ let h = harness(NEVER);
+ h.text("s:w", "before");
+ h.send(PaneInput::Paste {
+ target: "s:w".into(),
+ text: "multi\nline".into(),
+ });
+ h.text("s:w", "after");
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("sub:s:w".into(), "before".into()),
+ Op::Paste("sub:s:w".into(), "multi\nline".into()),
+ Op::Text("sub:s:w".into(), "after".into()),
+ ]
+ );
+}
+
+// --- backend selection, failure and reconnect ---
+
+#[test]
+fn the_control_backend_is_preferred_when_it_connects() {
+ let recorder = Recorder::default();
+ let rec = recorder.clone();
+ let factory: ControlFactory =
+ Box::new(move |_| Ok(Box::new(RecordingBackend::new("ctl", rec.clone()))));
+ let h = harness_with(NEVER, recorder, Some(factory));
+ h.text("s:w", "hi");
+ h.key("s:w", "Enter");
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Text("ctl:s:w".into(), "hi".into()),
+ Op::Key("ctl:s:w".into(), "Enter".into()),
+ ]
+ );
+}
+
+#[test]
+fn an_ambiguous_control_write_is_not_replayed_on_the_fallback() {
+ // A failed write may have landed partially. Replaying it could repeat an
+ // Enter, which is worse than dropping one: the plan says so explicitly.
+ let recorder = Recorder::default();
+ let rec = recorder.clone();
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let seen = Arc::clone(&attempts);
+ let factory: ControlFactory = Box::new(move |_| {
+ seen.fetch_add(1, Ordering::Relaxed);
+ let mut backend = RecordingBackend::new("ctl", rec.clone());
+ backend.failing = true;
+ Ok(Box::new(backend))
+ });
+ let h = harness_with(NEVER, recorder, Some(factory));
+ h.key("s:w", "Enter");
+ assert_eq!(
+ h.finish(),
+ vec![],
+ "the dropped key must not reappear on the subprocess backend"
+ );
+ assert_eq!(attempts.load(Ordering::Relaxed), 1);
+}
+
+#[test]
+fn a_dead_control_connection_falls_back_without_reordering() {
+ let recorder = Recorder::default();
+ let rec = recorder.clone();
+ let dead = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let flag = Arc::clone(&dead);
+ let factory: ControlFactory = Box::new(move |_| {
+ let mut backend = RecordingBackend::new("ctl", rec.clone());
+ backend.dead = Arc::clone(&flag);
+ Ok(Box::new(backend))
+ });
+ let h = harness_with(NEVER, recorder, Some(factory));
+ h.key("s:w", "a");
+ std::thread::sleep(Duration::from_millis(20));
+ dead.store(true, std::sync::atomic::Ordering::Relaxed);
+ h.key("s:w", "b");
+ h.key("s:w", "c");
+ // A backend found dead has written nothing, so its request is *not*
+ // ambiguous: it moves to the fallback in place, keeping the order.
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Key("ctl:s:w".into(), "a".into()),
+ Op::Key("sub:s:w".into(), "b".into()),
+ Op::Key("sub:s:w".into(), "c".into()),
+ ]
+ );
+}
+
+#[test]
+fn a_control_connection_that_never_comes_up_is_retried_with_backoff() {
+ let recorder = Recorder::default();
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let seen = Arc::clone(&attempts);
+ let factory: ControlFactory = Box::new(move |_| {
+ seen.fetch_add(1, Ordering::Relaxed);
+ anyhow::bail!("no tmux here")
+ });
+ let h = harness_with(NEVER, recorder, Some(factory));
+ for _ in 0..3 {
+ h.key("s:w", "x");
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ // Nothing is lost while the control client is unavailable: every key lands
+ // on the subprocess backend.
+ assert_eq!(
+ h.finish(),
+ vec![
+ Op::Key("sub:s:w".into(), "x".into()),
+ Op::Key("sub:s:w".into(), "x".into()),
+ Op::Key("sub:s:w".into(), "x".into()),
+ ]
+ );
+ assert!(attempts.load(Ordering::Relaxed) >= 1, "it must keep trying");
+}
+
+// --- the sink's queue policy ---
+
+#[test]
+fn a_full_queue_reports_queue_full_rather_than_blocking() {
+ // The TUI thread must never wait on tmux. A full queue is a named error the
+ // caller can surface, not a stall.
+ let (tx, rx) = sync_channel(2);
+ let sink = BrokerSink {
+ tx,
+ depth: Arc::new(AtomicUsize::new(0)),
+ high_water: Arc::new(AtomicUsize::new(0)),
+ session: Arc::new(Mutex::new("it".to_string())),
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ join: Mutex::new(None),
+ };
+ assert!(sink.key("s:w", "a").is_ok());
+ assert!(sink.key("s:w", "b").is_ok());
+ assert_eq!(sink.key("s:w", "c"), Err(InputError::QueueFull));
+ let (depth, high_water) = sink.depth();
+ assert_eq!(
+ depth, 2,
+ "the rejected request must not be counted as queued"
+ );
+ // The high-water mark may include the rejected attempt: the counter is
+ // incremented before the send and rolled back after, which is the only order
+ // that cannot underflow. It is a diagnostic, and over-counting is the
+ // harmless direction.
+ assert!(high_water >= 2);
+ drop(rx);
+ assert_eq!(sink.key("s:w", "d"), Err(InputError::Disconnected));
+}
+
+#[test]
+fn changing_project_repoints_the_next_connection() {
+ // agtx switches project in place. An open connection is deliberately left
+ // alone β€” it still delivers, because every target is `session:window`
+ // (`pane_target`) and is therefore resolved server-wide rather than inside
+ // the attached session. What the switch does change is where a *reconnect*
+ // attaches, since the old project's session may be killed.
+ let (tx, _rx) = sync_channel(2);
+ let sink = BrokerSink {
+ tx,
+ depth: Arc::new(AtomicUsize::new(0)),
+ high_water: Arc::new(AtomicUsize::new(0)),
+ session: Arc::new(Mutex::new("old".to_string())),
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ join: Mutex::new(None),
+ };
+ sink.set_session("new");
+ assert_eq!(sink.session.lock().unwrap().as_str(), "new");
+}
+
+#[test]
+fn the_queue_depth_counter_cannot_go_negative() {
+ // The broker decrements this from another thread. Counting after a
+ // successful send let it decrement first, taking a `usize` to `usize::MAX`
+ // and panicking on the next increment β€” found by the latency benchmark, not
+ // by any deterministic test, which is why it is pinned here.
+ let (tx, rx) = sync_channel(64);
+ let depth = Arc::new(AtomicUsize::new(0));
+ let sink = Arc::new(BrokerSink {
+ tx,
+ depth: Arc::clone(&depth),
+ high_water: Arc::new(AtomicUsize::new(0)),
+ session: Arc::new(Mutex::new("it".to_string())),
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ join: Mutex::new(None),
+ });
+ let drain = std::thread::spawn(move || {
+ let mut seen = 0;
+ while rx.recv().is_ok() {
+ depth.fetch_sub(1, Ordering::Relaxed);
+ seen += 1;
+ }
+ seen
+ });
+ for _ in 0..2000 {
+ let _ = sink.key("s:w", "a");
+ }
+ drop(sink);
+ assert!(drain.join().unwrap() > 0);
+}
+
+#[test]
+fn quitting_cannot_hang_on_a_wedged_broker() {
+ // The broker can be blocked inside a `tmux` subprocess that is never coming
+ // back. Quitting agtx must still take a bounded amount of time, so both the
+ // enqueue and the wait for the final flush give up rather than waiting for a
+ // thread that will not answer.
+ let (tx, rx) = sync_channel(1);
+ let wedged = std::thread::spawn(move || {
+ // Holds the receiver β€” and therefore the channel β€” without ever draining.
+ std::thread::sleep(Duration::from_secs(30));
+ drop(rx);
+ });
+ let sink = BrokerSink {
+ tx,
+ depth: Arc::new(AtomicUsize::new(0)),
+ high_water: Arc::new(AtomicUsize::new(0)),
+ session: Arc::new(Mutex::new("it".to_string())),
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ join: Mutex::new(None),
+ };
+ // Fill the one slot, so the stop request cannot be enqueued either.
+ sink.key("s:w", "a").unwrap();
+
+ let started = Instant::now();
+ sink.shutdown();
+ assert!(
+ started.elapsed() < SHUTDOWN_ENQUEUE_WAIT + SHUTDOWN_DRAIN_WAIT + Duration::from_secs(1),
+ "shutdown took {:?}",
+ started.elapsed()
+ );
+ drop(sink);
+ drop(wedged);
+}
+
+#[test]
+fn the_recording_sink_captures_what_the_ui_enqueued() {
+ let sink = RecordingSink::new();
+ sink.text("s:w", "a").unwrap();
+ sink.key("s:w", "Enter").unwrap();
+ sink.flush().unwrap();
+ assert_eq!(
+ sink.taken(),
+ vec![
+ PaneInput::Text {
+ target: "s:w".into(),
+ text: "a".into()
+ },
+ PaneInput::Key {
+ target: "s:w".into(),
+ key: "Enter".into()
+ },
+ PaneInput::Flush,
+ ]
+ );
+}
+
+#[test]
+fn every_request_names_the_pane_it_is_for() {
+ // The broker keeps no "currently selected task": a stale one is exactly how
+ // queued text would reach the wrong agent.
+ assert_eq!(
+ PaneInput::Text {
+ target: "s:w".into(),
+ text: "a".into()
+ }
+ .target(),
+ Some("s:w")
+ );
+ assert_eq!(PaneInput::Flush.target(), None);
+}
diff --git a/src/tmux/mod.rs b/src/tmux/mod.rs
index f580601..bb650b8 100644
--- a/src/tmux/mod.rs
+++ b/src/tmux/mod.rs
@@ -1,7 +1,16 @@
+pub mod control;
+pub mod input;
mod operations;
+pub use control::{tmux_quote, ControlClient, Frame, FrameParser};
+pub use input::{
+ InputConfig, InputError, PaneInput, PaneInputSink, DEFAULT_BATCH_WINDOW, DEFAULT_QUEUE_CAPACITY,
+};
pub use operations::*;
+#[cfg(any(test, feature = "test-mocks"))]
+pub use input::RecordingSink;
+
#[cfg(feature = "test-mocks")]
pub use operations::MockTmuxOperations;
diff --git a/src/tmux/operations.rs b/src/tmux/operations.rs
index 909f3c2..ddbd587 100644
--- a/src/tmux/operations.rs
+++ b/src/tmux/operations.rs
@@ -65,8 +65,12 @@ pub trait TmuxOperations: Send + Sync {
/// Capture pane content with history (returns raw bytes for ANSI parsing)
fn capture_pane_with_history(&self, target: &str, history_lines: i32) -> Vec<u8>;
- /// Get cursor position and pane height: (cursor_x, cursor_y, pane_height)
- fn get_cursor_info(&self, target: &str) -> Option<(usize, usize, usize)>;
+ /// Cursor position, pane height, and how much scrollback tmux is holding.
+ ///
+ /// One `display -p` for all four: the popup refresh runs this every 50 ms,
+ /// so a second process to ask about scrollback would cost more than the
+ /// answer is worth.
+ fn pane_metrics(&self, target: &str) -> Option<PaneMetrics>;
/// Resize a tmux window
fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()>;
@@ -81,6 +85,36 @@ pub trait TmuxOperations: Send + Sync {
fn create_session(&self, session: &str, working_dir: &str) -> Result<()>;
}
+/// What tmux reports about a pane, in one query.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PaneMetrics {
+ pub cursor_x: usize,
+ pub cursor_y: usize,
+ pub pane_height: usize,
+ /// Lines tmux is holding *above* the visible screen.
+ ///
+ /// Zero for a pane in the **alternate screen**, which is where full-screen
+ /// agent UIs live: the alternate screen accumulates no scrollback, so the
+ /// session's history belongs to the agent and tmux cannot see any of it.
+ /// Measured on Claude Code 2.1.251, which takes the alternate screen shortly
+ /// after startup and never gives it back β€” `capture-pane -S -500` then
+ /// returns exactly the visible rows, and there is nothing for agtx to
+ /// scroll through.
+ pub history_size: usize,
+}
+
+impl PaneMetrics {
+ /// Where the cursor is, for rendering it in the popup.
+ pub fn cursor(&self) -> (usize, usize, usize) {
+ (self.cursor_x, self.cursor_y, self.pane_height)
+ }
+
+ /// What [`trim_content_to_cursor`](crate::tui::shell_popup::trim_content_to_cursor) needs.
+ pub fn trim_bounds(&self) -> (usize, usize) {
+ (self.cursor_y, self.pane_height)
+ }
+}
+
/// Wrap `text` as one POSIX single-quoted shell word.
///
/// [`create_window`](TmuxOperations::create_window) nests the agent's launch
@@ -254,7 +288,7 @@ impl TmuxOperations for RealTmuxOps {
.unwrap_or_default()
}
- fn get_cursor_info(&self, target: &str) -> Option<(usize, usize, usize)> {
+ fn pane_metrics(&self, target: &str) -> Option<PaneMetrics> {
let output = std::process::Command::new("tmux")
.args(["-L", super::AGENT_SERVER])
.args([
@@ -262,19 +296,21 @@ impl TmuxOperations for RealTmuxOps {
"-p",
"-t",
target,
- "#{cursor_x} #{cursor_y} #{pane_height}",
+ "#{cursor_x} #{cursor_y} #{pane_height} #{history_size}",
])
.output()
.ok()?;
if output.status.success() {
let output_str = String::from_utf8_lossy(&output.stdout);
- let parts: Vec<&str> = output_str.trim().split_whitespace().collect();
- if parts.len() == 3 {
- let cursor_x: usize = parts[0].parse().ok()?;
- let cursor_y: usize = parts[1].parse().ok()?;
- let pane_height: usize = parts[2].parse().ok()?;
- return Some((cursor_x, cursor_y, pane_height));
+ let parts: Vec<&str> = output_str.split_whitespace().collect();
+ if parts.len() == 4 {
+ return Some(PaneMetrics {
+ cursor_x: parts[0].parse().ok()?,
+ cursor_y: parts[1].parse().ok()?,
+ pane_height: parts[2].parse().ok()?,
+ history_size: parts[3].parse().ok()?,
+ });
}
}
None
diff --git a/src/tui/app.rs b/src/tui/app.rs
index e42e38e..f2e711e 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -23,7 +23,9 @@ use crate::git::{
self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps,
};
use crate::skills;
-use crate::tmux::{self, RealTmuxOps, TmuxOperations};
+use crate::tmux::{
+ self, InputConfig, InputError, PaneInput, PaneInputSink, RealTmuxOps, TmuxOperations,
+};
use crate::AppMode;
use super::board::BoardState;
@@ -49,31 +51,31 @@ fn build_footer_text(
match input_mode {
InputMode::Normal => {
if sidebar_focused {
- " [j/k] navigate [Enter] open [l] board [e] hide sidebar [q] quit ".to_string()
+ "[j/k] navigate [Enter] open [l] board Β· [e] hide sidebar [q] quit".to_string()
} else {
match selected_column {
- 0 => " [o] new [/] search [Enter] open [x] del [d] diff [D] deps [R] research [m] plan [M] run [e] sidebar [q] quit".to_string(),
+ 0 => "[o] new [/] search Β· [Enter] open [d] diff [D] deps Β· [m] plan [M] run [R] research Β· [x] delete [e] sidebar [q] quit".to_string(),
1 => if fullscreen_on_enter {
- " [o] new [/] search [Enter] open [x] del [d] diff [m] run [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [d] diff Β· [m] run Β· [x] delete [e] sidebar [q] quit".to_string()
} else {
- " [o] new [/] search [Enter] open [C-f] fullscreen [x] del [d] diff [m] run [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [m] run Β· [x] delete [e] sidebar [q] quit".to_string()
},
2 => if fullscreen_on_enter {
- " [o] new [/] search [Enter] open [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()
} else {
- " [o] new [/] search [Enter] open [C-f] fullscreen [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()
},
3 if has_cyclic_plugin => if fullscreen_on_enter {
- " [o] new [/] search [Enter] open [x] del [d] diff [m] done [r] resume [p] next phase [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [d] diff Β· [r] resume [p] next phase [m] done Β· [x] delete [e] sidebar [q] quit".to_string()
} else {
- " [o] new [/] search [Enter] open [C-f] fullscreen [x] del [d] diff [m] done [r] resume [p] next phase [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [r] resume [p] next phase [m] done Β· [x] delete [e] sidebar [q] quit".to_string()
},
3 => if fullscreen_on_enter {
- " [o] new [/] search [Enter] open [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()
} else {
- " [o] new [/] search [Enter] open [C-f] fullscreen [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string()
+ "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()
},
- _ => " [o] new [/] search [Enter] open [x] del [e] sidebar [q] quit".to_string(),
+ _ => "[o] new [/] search Β· [Enter] open Β· [x] delete [e] sidebar [q] quit".to_string(),
}
}
}
@@ -298,6 +300,9 @@ struct AppState {
available_agents: Vec<agent::Agent>,
// Tmux operations (injectable for testing)
tmux_ops: Arc<dyn TmuxOperations>,
+ // Popup keystrokes go here, never straight to tmux: enqueueing is the only
+ // thing the input thread is allowed to do with a key. See `tmux::input`.
+ input_sink: Arc<dyn PaneInputSink>,
// Git operations (injectable for testing)
git_ops: Arc<dyn git::GitOperations>,
// Git provider operations (injectable for testing)
@@ -315,7 +320,7 @@ struct AppState {
shell_popup: Option<ShellPopup>,
// At most one pane-history capture runs off the input thread at a time.
shell_refresh_rx:
- Option<mpsc::Receiver<(String, Vec<u8>, Option<(usize, usize, usize)>)>>,
+ Option<mpsc::Receiver<(String, Vec<u8>, Option<crate::tmux::PaneMetrics>)>>,
// File search dropdown
file_search: Option<FileSearchState>,
// Skill search dropdown
@@ -741,6 +746,15 @@ impl App {
let config = MergedConfig::merge(&global_config, &project_config);
+ // One broker for the process. Popup keys are enqueued onto it, so the
+ // input thread never waits for a tmux subprocess. Whether the broker
+ // then writes through a control connection or one process per key is a
+ // runtime decision it makes for itself: this only says not to try the
+ // control connection at all.
+ let mut input_config = InputConfig::new(tmux::AGENT_SERVER, &tmux_project_name);
+ input_config.control_mode = control_mode_enabled();
+ let input_sink = tmux::input::spawn(input_config, Arc::clone(&tmux_ops));
+
// If the project is untrusted, also suppress plugin init_scripts
// by forcing no_init_scripts in the flags
let mut flags = flags;
@@ -771,6 +785,7 @@ impl App {
tmux_project_name: tmux_project_name.clone(),
available_agents,
tmux_ops,
+ input_sink,
git_ops,
git_provider_ops,
agent_registry,
@@ -996,6 +1011,9 @@ impl App {
tmux_project_name,
available_agents: vec![],
tmux_ops,
+ // Tests assert what the UI *enqueued*; a broker thread would add
+ // timing to something that is a pure translation.
+ input_sink: Arc::new(crate::tmux::RecordingSink::new()),
git_ops,
git_provider_ops,
agent_registry,
@@ -1053,6 +1071,12 @@ impl App {
})
}
+ /// Swap in a recording sink so a test can assert what the UI enqueued.
+ #[cfg(feature = "test-mocks")]
+ pub fn set_input_sink(&mut self, sink: Arc<dyn PaneInputSink>) {
+ self.state.input_sink = sink;
+ }
+
pub async fn run(&mut self) -> Result<()> {
while !self.state.should_quit {
self.draw()?;
@@ -1141,12 +1165,12 @@ impl App {
// the input thread.
if let Some(ref rx) = self.state.shell_refresh_rx {
match rx.try_recv() {
- Ok((window_name, content, cursor_info)) => {
+ Ok((window_name, content, metrics)) => {
self.state.shell_refresh_rx = None;
if let Some(popup) = self.state.shell_popup.as_mut() {
if popup.window_name == window_name {
popup.cached_content = content;
- popup.cursor_info = cursor_info;
+ popup.metrics = metrics;
}
}
}
@@ -1168,12 +1192,12 @@ impl App {
popup.mark_content_refreshed();
self.state.shell_refresh_rx = Some(rx);
std::thread::spawn(move || {
- let (content, cursor_info) = capture_tmux_pane_snapshot(
+ let (content, metrics) = capture_tmux_pane_snapshot(
&window_name,
500,
tmux_ops.as_ref(),
);
- let _ = tx.send((window_name, content, cursor_info));
+ let _ = tx.send((window_name, content, metrics));
});
}
}
@@ -3983,52 +4007,49 @@ impl App {
return Ok(());
}
- // Ctrl+Space is a prefix for keys that agtx normally reserves for
- // popup navigation (for example Ctrl+q or Ctrl+u). This preserves
- // complete terminal access without leaving the in-app fullscreen.
- if popup.pass_through_next_key {
- popup.pass_through_next_key = false;
- send_key_to_tmux(&window_name, key, self.state.tmux_ops.as_ref());
- return Ok(());
- }
- if has_ctrl && matches!(key.code, KeyCode::Char(' ')) {
- popup.pass_through_next_key = true;
+ let scroll_action = match key.code {
+ KeyCode::Char('p') | KeyCode::Up if has_ctrl => Some(PopupScroll::Up(5)),
+ KeyCode::Char('n') | KeyCode::Down if has_ctrl => Some(PopupScroll::Down(5)),
+ KeyCode::Char('u') if has_ctrl => Some(PopupScroll::Up(20)),
+ KeyCode::PageUp => Some(PopupScroll::Up(20)),
+ KeyCode::Char('d') if has_ctrl => Some(PopupScroll::Down(20)),
+ KeyCode::PageDown => Some(PopupScroll::Down(20)),
+ KeyCode::Char('g') if has_ctrl => Some(PopupScroll::Bottom),
+ _ => None,
+ };
+ if let Some(action) = scroll_action {
+ handle_popup_scroll(
+ popup,
+ self.state.input_sink.as_ref(),
+ &mut self.state.warning_message,
+ &window_name,
+ action,
+ );
return Ok(());
}
match key.code {
// Ctrl+q = close popup
KeyCode::Char('q') if has_ctrl => {
+ // Anything still batched belongs to *this* pane. Deliver it
+ // before the popup β€” and with it the target β€” can change,
+ // and before agtx's own next write to this pane (a phase
+ // advance is one keystroke away on the board).
+ flush_pane_input_sync(
+ self.state.input_sink.as_ref(),
+ &mut self.state.warning_message,
+ );
self.state.shell_popup = None;
}
- // Scroll up with Ctrl+k or Ctrl+p or Ctrl+Up
- KeyCode::Char('k') | KeyCode::Char('p') | KeyCode::Up if has_ctrl => {
- popup.scroll_up(5);
- }
- // Scroll down with Ctrl+j or Ctrl+n or Ctrl+Down
- KeyCode::Char('j') | KeyCode::Char('n') | KeyCode::Down if has_ctrl => {
- popup.scroll_down(5);
- }
- // Page up with Ctrl+u or PageUp
- KeyCode::Char('u') if has_ctrl => {
- popup.scroll_up(20);
- }
- KeyCode::PageUp => {
- popup.scroll_up(20);
- }
- // Page down with Ctrl+d or PageDown
- KeyCode::Char('d') if has_ctrl => {
- popup.scroll_down(20);
- }
- KeyCode::PageDown => {
- popup.scroll_down(20);
- }
- // Ctrl+g = go to bottom (current)
- KeyCode::Char('g') if has_ctrl => {
- popup.scroll_to_bottom();
- }
// Ctrl+f toggles between centered and fullscreen in-app views.
KeyCode::Char('f') if has_ctrl => {
+ // The resize is a plain tmux subprocess on a different
+ // socket; queued text must reach the pane at the size it was
+ // typed at, so this waits rather than just enqueueing.
+ flush_pane_input_sync(
+ self.state.input_sink.as_ref(),
+ &mut self.state.warning_message,
+ );
popup.fullscreen = !popup.fullscreen;
let (pane_width, pane_height) = if popup.fullscreen {
crossterm::terminal::size()
@@ -4053,7 +4074,13 @@ impl App {
}
_ => {
// Forward all other keys to tmux window (including Esc)
- send_key_to_tmux(&window_name, key, self.state.tmux_ops.as_ref());
+ if let Some(input) = popup_key_input(&window_name, key) {
+ forward_pane_input(
+ self.state.input_sink.as_ref(),
+ &mut self.state.warning_message,
+ input,
+ );
+ }
}
}
}
@@ -4061,10 +4088,19 @@ impl App {
}
fn handle_paste(&mut self, text: String) -> Result<()> {
- // Shell popup open: forward paste to the tmux pane with proper bracketed paste sequences
+ // Shell popup open: forward paste to the tmux pane with proper bracketed
+ // paste sequences. It goes through the broker like every other request,
+ // so it cannot overtake characters typed just before it.
if let Some(ref popup) = self.state.shell_popup {
let window_name = popup.window_name.clone();
- let _ = self.state.tmux_ops.paste_text(&window_name, &text);
+ forward_pane_input(
+ self.state.input_sink.as_ref(),
+ &mut self.state.warning_message,
+ PaneInput::Paste {
+ target: window_name,
+ text,
+ },
+ );
return Ok(());
}
@@ -6993,8 +7029,11 @@ impl App {
popup.last_pane_size = Some((pane_width, pane_height));
std::thread::sleep(std::time::Duration::from_millis(200));
}
- popup.cached_content =
- capture_tmux_pane_with_history(&orch_target, 500, self.state.tmux_ops.as_ref());
+ let (content, metrics) =
+ capture_tmux_pane_snapshot(&orch_target, 500, self.state.tmux_ops.as_ref());
+ popup.cached_content = content;
+ popup.metrics = metrics;
+ let _ = self.state.input_sink.flush();
self.state.shell_popup = Some(popup);
return Ok(());
}
@@ -7074,8 +7113,11 @@ impl App {
.resize_window(&orch_target, pane_width, pane_height);
popup.last_pane_size = Some((pane_width, pane_height));
}
- popup.cached_content =
- capture_tmux_pane_with_history(&orch_target, 500, self.state.tmux_ops.as_ref());
+ let (content, metrics) =
+ capture_tmux_pane_snapshot(&orch_target, 500, self.state.tmux_ops.as_ref());
+ popup.cached_content = content;
+ popup.metrics = metrics;
+ let _ = self.state.input_sink.flush();
self.state.shell_popup = Some(popup);
// Deploy orchestrate skill to project root so the agent can discover it
@@ -7139,7 +7181,11 @@ impl App {
let task_id = task.id.clone();
let escalation_note = task.escalation_note.clone();
- let mut popup = ShellPopup::new(task.title.clone(), window_name.clone());
+ // Qualified, like the orchestrator popup's target: a bare window
+ // name resolves inside whichever session the caller is bound to,
+ // which is not necessarily this project's. See `pane_target`.
+ let target = pane_target(&self.state.tmux_project_name, window_name);
+ let mut popup = ShellPopup::new(task.title.clone(), target.clone());
popup.task_id = Some(task_id);
popup.escalation_note = escalation_note;
@@ -7150,23 +7196,28 @@ impl App {
(term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
let pane_height = popup_height.saturating_sub(4); // -4 for borders + header/footer
- let target = format!("{}:{}", self.state.tmux_project_name, window_name);
- // TODO the resize should be done on target which is
- // session_name:window_name, but for some reason that doesn't work
- // doing tmux -L agtx resize-window -t session:window -x 30 -y 30 works
- let _ =
- self.state
- .tmux_ops
- .resize_window(&window_name, pane_width, pane_height);
+ let _ = self
+ .state
+ .tmux_ops
+ .resize_window(&target, pane_width, pane_height);
popup.last_pane_size = Some((pane_width, pane_height));
// Give TUI apps (OpenCode, Gemini Ink) time to re-render after resize
std::thread::sleep(std::time::Duration::from_millis(200));
}
- // Capture initial content
- popup.cached_content =
- capture_tmux_pane_with_history(window_name, 500, self.state.tmux_ops.as_ref());
+ // Capture initial content *and* the pane metrics, so the first
+ // keypress already knows whether this pane has tmux scrollback.
+ // Reading them only in the 50 ms refresh left a window in which
+ // `has_scrollback()` fell back to its `true` default and the
+ // scroll keys moved a buffer that could not move.
+ let (content, metrics) =
+ capture_tmux_pane_snapshot(&target, 500, self.state.tmux_ops.as_ref());
+ popup.cached_content = content;
+ popup.metrics = metrics;
+ // A popup opening changes the target; nothing queued for the
+ // previous one may follow it here.
+ let _ = self.state.input_sink.flush();
self.state.shell_popup = Some(popup);
}
}
@@ -7902,6 +7953,12 @@ impl App {
&project_path,
self.state.tmux_ops.as_ref(),
);
+ // The control client attaches to a session, and the old project's may be
+ // killed later. Delivery does not depend on which one it is β€” commands
+ // carry their own target β€” but the next *connect* does.
+ self.state
+ .input_sink
+ .set_session(&self.state.tmux_project_name);
// Clear per-task caches from previous project
self.state.merge_conflict_checked.clear();
@@ -7926,6 +7983,10 @@ impl App {
impl Drop for App {
fn drop(&mut self) {
+ // Deliver what is still queued and stop the broker before the process
+ // goes away β€” the last characters typed into a pane were typed on
+ // purpose. Bounded by the queue depth, so quitting stays instant.
+ self.state.input_sink.shutdown();
match self.terminal.backend_mut() {
AppBackend::Crossterm(backend) => {
let _ = disable_raw_mode();
@@ -8625,31 +8686,24 @@ fn centered_rect_fixed_width(fixed_width: u16, percent_y: u16, r: Rect) -> Rect
}
}
-/// Capture content from a tmux pane with history (with ANSI escape sequences)
-fn capture_tmux_pane_with_history(
- window_name: &str,
- history_lines: i32,
- tmux_ops: &dyn TmuxOperations,
-) -> Vec<u8> {
- capture_tmux_pane_snapshot(window_name, history_lines, tmux_ops).0
-}
-
+/// Capture a pane's content with history (ANSI escape sequences included) and
+/// the metrics describing it, in one pass.
fn capture_tmux_pane_snapshot(
window_name: &str,
history_lines: i32,
tmux_ops: &dyn TmuxOperations,
-) -> (Vec<u8>, Option<(usize, usize, usize)>) {
+) -> (Vec<u8>, Option<crate::tmux::PaneMetrics>) {
let content = tmux_ops.capture_pane_with_history(window_name, history_lines);
// Get the cursor position and pane height to know where the "real" content ends
// Lines below the cursor are unused pane buffer space
- let cursor_info = tmux_ops.get_cursor_info(window_name);
+ let metrics = tmux_ops.pane_metrics(window_name);
// Trim content to only include lines up to cursor position
- let trim_info = cursor_info.map(|(_, y, height)| (y, height));
+ let trim_info = metrics.map(|m| m.trim_bounds());
(
shell_popup::trim_content_to_cursor(content, trim_info),
- cursor_info,
+ metrics,
)
}
@@ -8773,16 +8827,35 @@ fn push_changes_to_existing_pr(
.unwrap_or_else(|| "Changes pushed to existing PR".to_string()))
}
-/// Send a key to a tmux pane
-fn send_key_to_tmux(
- window_name: &str,
- key: crossterm::event::KeyEvent,
- tmux_ops: &dyn TmuxOperations,
-) {
+/// Translate a popup keystroke into a request for the pane input broker.
+///
+/// The split between [`PaneInput::Text`] and [`PaneInput::Key`] is the whole
+/// point of the type: text goes out with `send-keys -l`, which suppresses tmux's
+/// key-name lookup, and a key goes out without it, which is what makes `Enter`
+/// an Enter.
+///
+/// An unmodified character is therefore **text**, where it used to be a key.
+/// That is a fix, not just a reclassification: `send-keys -t x ";"` never
+/// reached the pane at all, because a standalone semicolon is how tmux separates
+/// commands β€” it was parsed as one and the keystroke vanished. The same lookup
+/// is why a batched run of characters could not have been sent as a key.
+fn popup_key_input(target: &str, key: crossterm::event::KeyEvent) -> Option<PaneInput> {
use crossterm::event::KeyModifiers;
let has_alt = key.modifiers.contains(KeyModifiers::ALT);
let has_ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
+ // Shift is already reflected in the character crossterm reports, so it is
+ // not a modifier prefix here β€” `C-A` and `C-a` are different keys to tmux,
+ // but `A` alone is just the character.
+ if let KeyCode::Char(c) = key.code {
+ if !has_ctrl && !has_alt {
+ return Some(PaneInput::Text {
+ target: target.to_string(),
+ text: c.to_string(),
+ });
+ }
+ }
+
let base = match key.code {
KeyCode::Char(c) => c.to_string(),
KeyCode::Enter => "Enter".to_string(),
@@ -8800,7 +8873,7 @@ fn send_key_to_tmux(
KeyCode::Delete => "DC".to_string(),
KeyCode::Insert => "IC".to_string(),
KeyCode::F(n) => format!("F{}", n),
- _ => return,
+ _ => return None,
};
let key_str = match (has_ctrl, has_alt) {
@@ -8810,7 +8883,155 @@ fn send_key_to_tmux(
(false, false) => base,
};
- let _ = tmux_ops.send_key(window_name, &key_str);
+ Some(PaneInput::Key {
+ target: target.to_string(),
+ key: key_str,
+ })
+}
+
+/// Hand one request to the broker, surfacing the two ways that can fail.
+///
+/// Takes the sink and the warning slot rather than `&mut App` on purpose: it is
+/// called with the popup mutably borrowed, and these are disjoint fields.
+///
+/// A full queue is **not** retried synchronously. Sending it now would put this
+/// key ahead of everything already queued, and a keystroke arriving out of order
+/// is worse than one that visibly did not arrive β€” so the queued prefix is kept
+/// and the user is told.
+fn forward_pane_input(
+ sink: &dyn PaneInputSink,
+ warning: &mut Option<(String, Instant)>,
+ input: PaneInput,
+) {
+ match sink.send(input) {
+ Ok(()) => {}
+ Err(InputError::QueueFull) => {
+ tracing::warn!("pane input queue full; keystroke dropped");
+ *warning = Some((
+ "Input is backing up; a keystroke was dropped rather than sent out of order."
+ .to_string(),
+ Instant::now(),
+ ));
+ }
+ Err(InputError::Disconnected) => {
+ tracing::error!("pane input broker stopped");
+ *warning = Some((
+ "Pane input is not running; restart agtx to type into task panes.".to_string(),
+ Instant::now(),
+ ));
+ }
+ // `send` is an enqueue and cannot time out. The arm exists because the
+ // variant shares an error type with `flush_sync`, which can.
+ Err(InputError::Timeout) => {
+ tracing::debug!("pane input enqueue reported a timeout");
+ }
+ }
+}
+
+/// Deliver everything queued and wait for tmux to have executed it.
+///
+/// Used before agtx does a synchronous tmux operation of its own on this thread:
+/// that travels a different socket, so without the wait it can overtake keys the
+/// user typed a moment earlier. The wait is bounded β€” see `FLUSH_SYNC_TIMEOUT` β€”
+/// and reaching the bound means the ordering was not achieved, which is worth a
+/// word to the user rather than a silent shrug.
+fn flush_pane_input_sync(sink: &dyn PaneInputSink, warning: &mut Option<(String, Instant)>) {
+ match sink.flush_sync() {
+ Ok(()) => {}
+ Err(InputError::Timeout) => {
+ tracing::warn!("pane input did not drain before a synchronous tmux operation");
+ *warning = Some((
+ "tmux is slow to accept input β€” your last keystrokes may arrive late.".to_string(),
+ Instant::now(),
+ ));
+ }
+ Err(e) => tracing::debug!(error = %e, "acknowledged flush failed"),
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum PopupScroll {
+ Up(i32),
+ Down(i32),
+ Bottom,
+}
+
+/// Apply one logical popup scroll action to whichever component owns history.
+///
+/// A pane in the alternate screen keeps no tmux scrollback (`history_size == 0`),
+/// so the session's history is the agent's, not ours. Rather than move a
+/// one-screen buffer by zero lines and print a line number to match, agtx sends
+/// the agent a key that scrolls *its* view.
+///
+/// **Never `Up`/`Down`.** Measured against Claude
+/// Code 2.1.251: in its detailed transcript view (`ctrl+o`) all four scroll, but
+/// in the main view `Up` recalls a previous prompt **into the composer** β€”
+/// overwriting whatever the user had typed β€” while `PageUp` is inert. A scroll
+/// key that silently rewrites the user's half-typed message is worse than one
+/// that does nothing, so `C-n/p` use the safe Page Down/Up translation.
+///
+/// The chord is **translated, never passed through**, for the same reason:
+/// forwarding a raw `C-d` would be an EOF that can end the session, and `C-u`
+/// would kill the line in the composer.
+fn handle_popup_scroll(
+ popup: &mut ShellPopup,
+ sink: &dyn PaneInputSink,
+ warning: &mut Option<(String, Instant)>,
+ target: &str,
+ action: PopupScroll,
+) {
+ if popup.has_scrollback() {
+ match action {
+ PopupScroll::Up(lines) => popup.scroll_up(lines),
+ PopupScroll::Down(lines) => popup.scroll_down(lines),
+ PopupScroll::Bottom => popup.scroll_to_bottom(),
+ }
+ return;
+ }
+
+ let key = match action {
+ PopupScroll::Up(_) => "PageUp",
+ PopupScroll::Down(_) => "PageDown",
+ PopupScroll::Bottom => "End",
+ };
+ forward_pane_input(
+ sink,
+ warning,
+ PaneInput::Key {
+ target: target.to_string(),
+ key: key.to_string(),
+ },
+ );
+}
+
+/// Address a window the way every tmux command in agtx should: `session:window`.
+///
+/// A **bare** window name is resolved inside whichever session the issuing
+/// client is bound to β€” the attached session for a control client, the
+/// most-recently-used one for a subprocess. Neither is reliably this project's
+/// after a project switch, and `orchestrator` is a window name every project
+/// session has, so a bare target could deliver a keystroke to the wrong
+/// project's agent. Qualifying makes the target absolute.
+fn pane_target(session: &str, window: &str) -> String {
+ if window.contains(':') {
+ // Already qualified β€” the orchestrator builds its target this way.
+ return window.to_string();
+ }
+ format!("{session}:{window}")
+}
+
+/// Is the persistent control-mode backend on for this run?
+///
+/// On unless `AGTX_TMUX_CONTROL` says otherwise. There is no config field: a
+/// failed or lost connection already falls back to the subprocess backend on its
+/// own, so the only thing a persisted setting could add is a second, staler copy
+/// of that decision. The variable stays as a one-run escape hatch, so a bug
+/// report can be bisected across the two lanes without editing anything.
+fn control_mode_enabled() -> bool {
+ !matches!(
+ std::env::var("AGTX_TMUX_CONTROL").ok().as_deref(),
+ Some("0") | Some("false") | Some("no")
+ )
}
const SHELL_REFRESH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 2fdade6..ebf4557 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -8,6 +8,7 @@ use crate::agent::MockAgentOperations;
use crate::git::{MockGitOperations, MockGitProviderOperations};
#[cfg(feature = "test-mocks")]
use crate::tmux::MockTmuxOperations;
+use crossterm::event::KeyModifiers;
#[test]
fn visible_columns_use_all_columns_on_wide_terminals() {
@@ -61,6 +62,13 @@ fn styled_footer_emphasizes_shortcuts_without_changing_text() {
assert_eq!(line.spans[1].style.fg, Some(styles.dimmed));
}
+#[test]
+fn footer_groups_related_shortcuts() {
+ let text = build_footer_text(InputMode::Normal, false, 1, false, false);
+ assert!(text.contains("search Β· [Enter] open"));
+ assert!(text.contains("[m] run Β· [x] delete"));
+}
+
#[test]
fn wizard_plugin_descriptions_wrap_and_align() {
let lines = wizard_plugin_option_lines(
@@ -782,219 +790,75 @@ fn test_fuzzy_score_consecutive_bonus() {
}
// =============================================================================
-// Tests for send_key_to_tmux
+// Tests for popup key translation
+//
+// These used to assert against a mock `TmuxOperations`, because a keystroke went
+// straight out as a `send-keys` subprocess. Translation is now a pure function
+// and delivery is `tmux::input`'s job, so the key names β€” the part agents
+// actually depend on β€” are pinned here without a mock in sight.
// =============================================================================
-/// Test sending character key to tmux
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_char() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- mock_tmux
- .expect_send_key()
- .with(
- mockall::predicate::eq("test-window"),
- mockall::predicate::eq("a"),
- )
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "test-window",
- crossterm::event::KeyEvent::new(KeyCode::Char('a'), crossterm::event::KeyModifiers::NONE),
- &mock_tmux,
- );
+#[cfg(test)]
+fn translated(code: KeyCode, modifiers: KeyModifiers) -> Option<PaneInput> {
+ popup_key_input("win", crossterm::event::KeyEvent::new(code, modifiers))
}
-/// Test sending Enter key to tmux
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_enter() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- mock_tmux
- .expect_send_key()
- .with(
- mockall::predicate::eq("test-window"),
- mockall::predicate::eq("Enter"),
- )
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "test-window",
- crossterm::event::KeyEvent::new(KeyCode::Enter, crossterm::event::KeyModifiers::NONE),
- &mock_tmux,
- );
+#[cfg(test)]
+fn translated_key(code: KeyCode, modifiers: KeyModifiers) -> String {
+ match translated(code, modifiers) {
+ Some(PaneInput::Key { key, .. }) => key,
+ other => panic!("expected a key name, got {other:?}"),
+ }
}
-/// Test sending special keys to tmux
#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_special_keys() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- // Test Escape
- mock_tmux
- .expect_send_key()
- .with(
- mockall::predicate::eq("win"),
- mockall::predicate::eq("Escape"),
- )
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::Esc, crossterm::event::KeyModifiers::NONE),
- &mock_tmux,
- );
-
- // Test Backspace
- let mut mock_tmux2 = MockTmuxOperations::new();
- mock_tmux2
- .expect_send_key()
- .with(
- mockall::predicate::eq("win"),
- mockall::predicate::eq("BSpace"),
- )
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::Backspace, crossterm::event::KeyModifiers::NONE),
- &mock_tmux2,
+fn a_character_becomes_literal_text_for_the_right_target() {
+ assert_eq!(
+ translated(KeyCode::Char('a'), KeyModifiers::NONE),
+ Some(PaneInput::Text {
+ target: "win".to_string(),
+ text: "a".to_string(),
+ })
);
}
-/// Test sending function key to tmux
#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_function_key() {
- let mut mock_tmux = MockTmuxOperations::new();
-
- mock_tmux
- .expect_send_key()
- .with(mockall::predicate::eq("win"), mockall::predicate::eq("F5"))
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::F(5), crossterm::event::KeyModifiers::NONE),
- &mock_tmux,
+fn enter_and_escape_keep_their_tmux_names() {
+ assert_eq!(translated_key(KeyCode::Enter, KeyModifiers::NONE), "Enter");
+ assert_eq!(translated_key(KeyCode::Esc, KeyModifiers::NONE), "Escape");
+ assert_eq!(
+ translated_key(KeyCode::Backspace, KeyModifiers::NONE),
+ "BSpace"
);
+ assert_eq!(translated_key(KeyCode::Delete, KeyModifiers::NONE), "DC");
+ assert_eq!(translated_key(KeyCode::Insert, KeyModifiers::NONE), "IC");
+ assert_eq!(translated_key(KeyCode::F(5), KeyModifiers::NONE), "F5");
}
-/// Test Alt+Left and Alt+Right send M-Left / M-Right (word-boundary navigation)
#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_alt_arrow_keys() {
- let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_send_key()
- .with(
- mockall::predicate::eq("win"),
- mockall::predicate::eq("M-Left"),
- )
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::Left, crossterm::event::KeyModifiers::ALT),
- &mock_tmux,
- );
-
- let mut mock_tmux2 = MockTmuxOperations::new();
- mock_tmux2
- .expect_send_key()
- .with(
- mockall::predicate::eq("win"),
- mockall::predicate::eq("M-Right"),
- )
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::Right, crossterm::event::KeyModifiers::ALT),
- &mock_tmux2,
- );
+fn alt_arrows_stay_word_boundary_navigation() {
+ // Option+Left/Right in a composer. Both spellings matter: macOS terminals
+ // send the arrow form, and Emacs-style bindings send M-b / M-f.
+ assert_eq!(translated_key(KeyCode::Left, KeyModifiers::ALT), "M-Left");
+ assert_eq!(translated_key(KeyCode::Right, KeyModifiers::ALT), "M-Right");
+ assert_eq!(translated_key(KeyCode::Char('b'), KeyModifiers::ALT), "M-b");
+ assert_eq!(translated_key(KeyCode::Char('f'), KeyModifiers::ALT), "M-f");
}
-/// Test Alt+b / Alt+f (macOS Option+Left/Right Emacs-style) send M-b / M-f
#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_alt_b_f() {
- let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_send_key()
- .with(mockall::predicate::eq("win"), mockall::predicate::eq("M-b"))
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::Char('b'), crossterm::event::KeyModifiers::ALT),
- &mock_tmux,
- );
-
- let mut mock_tmux2 = MockTmuxOperations::new();
- mock_tmux2
- .expect_send_key()
- .with(mockall::predicate::eq("win"), mockall::predicate::eq("M-f"))
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(KeyCode::Char('f'), crossterm::event::KeyModifiers::ALT),
- &mock_tmux2,
- );
-}
-
-/// Control modifiers must reach the pane so terminal programs can be
-/// interrupted, suspended, or otherwise controlled from the in-app popup.
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_control_char() {
- let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_send_key()
- .with(mockall::predicate::eq("win"), mockall::predicate::eq("C-c"))
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(
- KeyCode::Char('c'),
- crossterm::event::KeyModifiers::CONTROL,
- ),
- &mock_tmux,
+fn control_modifiers_reach_the_pane() {
+ // Interrupting or suspending a program from the in-app popup depends on
+ // these arriving as keys rather than as the letters they are typed with.
+ assert_eq!(
+ translated_key(KeyCode::Char('c'), KeyModifiers::CONTROL),
+ "C-c"
);
-}
-
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_send_key_to_tmux_control_alt_char() {
- let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_send_key()
- .with(
- mockall::predicate::eq("win"),
- mockall::predicate::eq("C-M-x"),
- )
- .times(1)
- .returning(|_, _| Ok(()));
-
- send_key_to_tmux(
- "win",
- crossterm::event::KeyEvent::new(
+ assert_eq!(
+ translated_key(
KeyCode::Char('x'),
- crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::ALT,
+ KeyModifiers::CONTROL | KeyModifiers::ALT
),
- &mock_tmux,
+ "C-M-x"
);
}
@@ -1005,13 +869,13 @@ fn shell_popup_uses_twenty_fps_poll_interval() {
}
// =============================================================================
-// Tests for capture_tmux_pane_with_history
+// Tests for capture_tmux_pane_snapshot
// =============================================================================
/// Test capturing tmux pane content
#[test]
#[cfg(feature = "test-mocks")]
-fn test_capture_tmux_pane_with_history() {
+fn test_capture_tmux_pane_snapshot() {
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux
@@ -1023,14 +887,24 @@ fn test_capture_tmux_pane_with_history() {
.returning(|_, _| b"Line 1\nLine 2\nLine 3\n".to_vec());
mock_tmux
- .expect_get_cursor_info()
+ .expect_pane_metrics()
.with(mockall::predicate::eq("test-window"))
- .returning(|_| Some((0, 2, 3))); // cursor at column 0, line 2, pane has 3 lines
+ .returning(|_| {
+ Some(crate::tmux::PaneMetrics {
+ cursor_x: 0,
+ cursor_y: 2,
+ pane_height: 3,
+ history_size: 0,
+ })
+ });
- let content = capture_tmux_pane_with_history("test-window", 500, &mock_tmux);
+ let (content, metrics) = capture_tmux_pane_snapshot("test-window", 500, &mock_tmux);
// Content should be trimmed to cursor position
assert!(!content.is_empty());
+ // The metrics come back with it, so a popup can seed `has_scrollback()`
+ // at open time instead of waiting for the first refresh.
+ assert_eq!(metrics.map(|m| m.history_size), Some(0));
}
// =============================================================================
@@ -1580,7 +1454,7 @@ fn test_footer_text_planning_column() {
#[test]
fn test_footer_text_running_column() {
let text = build_footer_text(InputMode::Normal, false, 2, false, false);
- assert!(text.contains("[r] move left"));
+ assert!(text.contains("[r] move back"));
assert!(text.contains("[m] move"));
}
@@ -1609,7 +1483,7 @@ fn test_footer_text_fullscreen_on_enter_hides_ctrl_f() {
#[test]
fn test_footer_text_review_column() {
let text = build_footer_text(InputMode::Normal, false, 3, false, false);
- assert!(text.contains("[r] move left"));
+ assert!(text.contains("[r] move back"));
assert!(text.contains("[m] move"));
}
@@ -8282,7 +8156,7 @@ fn test_toggle_orchestrator_spawns_new_session() {
mock_tmux
.expect_capture_pane_with_history()
.returning(|_, _| vec![]);
- mock_tmux.expect_get_cursor_info().returning(|_| None);
+ mock_tmux.expect_pane_metrics().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
mock_registry.expect_get().returning(|_| {
@@ -8321,7 +8195,7 @@ fn test_toggle_orchestrator_opens_popup_when_already_running() {
mock_tmux
.expect_capture_pane_with_history()
.returning(|_, _| vec![]);
- mock_tmux.expect_get_cursor_info().returning(|_| None);
+ mock_tmux.expect_pane_metrics().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
mock_registry
@@ -8371,7 +8245,7 @@ fn test_toggle_orchestrator_reattaches_to_live_orchestrator_from_other_instance(
mock_tmux
.expect_capture_pane_with_history()
.returning(|_, _| vec![]);
- mock_tmux.expect_get_cursor_info().returning(|_| None);
+ mock_tmux.expect_pane_metrics().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
mock_registry
@@ -8426,7 +8300,7 @@ fn test_toggle_orchestrator_clears_stale_session_and_respawns() {
mock_tmux
.expect_capture_pane_with_history()
.returning(|_, _| vec![]);
- mock_tmux.expect_get_cursor_info().returning(|_| None);
+ mock_tmux.expect_pane_metrics().returning(|_| None);
let mut mock_registry = MockAgentRegistry::new();
mock_registry.expect_get().returning(|_| {
@@ -11303,33 +11177,12 @@ fn test_task_has_live_session_returns_false_on_tmux_error() {
#[test]
#[cfg(feature = "test-mocks")]
-fn test_handle_paste_into_shell_popup_calls_paste_text() {
- // When shell popup is open, handle_paste must call paste_text exactly once
- // with the full pasted string (not send_key character by character).
- let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux.expect_window_exists().returning(|_| Ok(false));
- mock_tmux.expect_has_session().returning(|_| false);
- mock_tmux.expect_get_cursor_info().returning(|_| None);
-
- let received = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
- let received_c = received.clone();
- mock_tmux
- .expect_paste_text()
- .times(1)
- .returning(move |_, text| {
- *received_c.lock().unwrap() = text.to_string();
- Ok(())
- });
-
- let mut app = App::new_for_test(
- Some(PathBuf::from("/tmp/test-project")),
- Arc::new(mock_tmux),
- Arc::new(MockGitOperations::new()),
- Arc::new(MockGitProviderOperations::new()),
- Arc::new(MockAgentRegistry::new()),
- )
- .unwrap();
-
+fn test_handle_paste_into_shell_popup_enqueues_one_atomic_paste() {
+ // A paste is one request with the whole string, never a character at a time.
+ // It goes to the broker rather than straight to tmux, so the assertion moved
+ // from `paste_text` to what the UI enqueued β€” the delivery itself is
+ // `tmux::input`'s contract, tested there.
+ let (mut app, sink) = app_with_recording_sink();
app.state.shell_popup = Some(ShellPopup::new(
"my task".to_string(),
"proj:my-task".to_string(),
@@ -11337,23 +11190,28 @@ fn test_handle_paste_into_shell_popup_calls_paste_text() {
app.handle_paste("hello world".to_string()).unwrap();
- assert_eq!(*received.lock().unwrap(), "hello world");
+ assert_eq!(
+ sink.taken(),
+ vec![PaneInput::Paste {
+ target: "proj:my-task".to_string(),
+ text: "hello world".to_string(),
+ }]
+ );
}
#[test]
#[cfg(feature = "test-mocks")]
-fn test_handle_paste_into_shell_popup_does_not_call_send_key() {
- // Verify the old per-character path is not taken for paste events.
+fn test_handle_paste_into_shell_popup_never_touches_tmux_on_the_input_thread() {
+ // The whole point of the broker: nothing on the key path may start or wait
+ // for a tmux process. mockall panics on any unexpected call, so an
+ // expectation of `times(0)` on all three send primitives is the assertion.
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_window_exists().returning(|_| Ok(false));
mock_tmux.expect_has_session().returning(|_| false);
- mock_tmux.expect_get_cursor_info().returning(|_| None);
- mock_tmux
- .expect_paste_text()
- .times(1)
- .returning(|_, _| Ok(()));
- // send_key must NOT be called β€” mockall panics if an unexpected call occurs
+ mock_tmux.expect_pane_metrics().returning(|_| None);
mock_tmux.expect_send_key().times(0);
+ mock_tmux.expect_send_text().times(0);
+ mock_tmux.expect_paste_text().times(0);
let mut app = App::new_for_test(
Some(PathBuf::from("/tmp/test-project")),
@@ -11363,6 +11221,7 @@ fn test_handle_paste_into_shell_popup_does_not_call_send_key() {
Arc::new(MockAgentRegistry::new()),
)
.unwrap();
+ app.set_input_sink(Arc::new(crate::tmux::RecordingSink::new()));
app.state.shell_popup = Some(ShellPopup::new(
"my task".to_string(),
@@ -11370,6 +11229,10 @@ fn test_handle_paste_into_shell_popup_does_not_call_send_key() {
));
app.handle_paste("some pasted text".to_string()).unwrap();
+ app.handle_key(key_event(KeyCode::Char('a'), KeyModifiers::NONE))
+ .unwrap();
+ app.handle_key(key_event(KeyCode::Enter, KeyModifiers::NONE))
+ .unwrap();
}
#[test]
@@ -13362,3 +13225,491 @@ fn test_no_release_check_runs_in_tests() {
let app = make_test_app();
assert!(app.state.update_rx.is_none());
}
+
+// =============================================================================
+// Popup input: what a keystroke becomes, and where it goes
+// =============================================================================
+
+/// Helper: an App whose pane input is recorded instead of sent.
+#[cfg(feature = "test-mocks")]
+fn app_with_recording_sink() -> (App, Arc<crate::tmux::RecordingSink>) {
+ let mut mock_tmux = MockTmuxOperations::new();
+ mock_tmux.expect_window_exists().returning(|_| Ok(false));
+ mock_tmux.expect_has_session().returning(|_| false);
+ mock_tmux.expect_pane_metrics().returning(|_| None);
+ mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));
+ // Nothing on the key path may reach tmux directly any more.
+ mock_tmux.expect_send_key().times(0);
+ mock_tmux.expect_send_text().times(0);
+ mock_tmux.expect_paste_text().times(0);
+
+ let mut app = App::new_for_test(
+ Some(PathBuf::from("/tmp/test-project")),
+ Arc::new(mock_tmux),
+ Arc::new(MockGitOperations::new()),
+ Arc::new(MockGitProviderOperations::new()),
+ Arc::new(MockAgentRegistry::new()),
+ )
+ .unwrap();
+ let sink = Arc::new(crate::tmux::RecordingSink::new());
+ app.set_input_sink(Arc::clone(&sink) as Arc<dyn crate::tmux::PaneInputSink>);
+ (app, sink)
+}
+
+#[cfg(feature = "test-mocks")]
+fn key_event(code: KeyCode, modifiers: KeyModifiers) -> crossterm::event::KeyEvent {
+ crossterm::event::KeyEvent::new(code, modifiers)
+}
+
+/// Helper: an App with a popup open on `proj:task`, plus its recording sink.
+#[cfg(feature = "test-mocks")]
+fn app_with_open_popup() -> (App, Arc<crate::tmux::RecordingSink>) {
+ let (mut app, sink) = app_with_recording_sink();
+ app.state.shell_popup = Some(ShellPopup::new(
+ "my task".to_string(),
+ "proj:task".to_string(),
+ ));
+ (app, sink)
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn a_printable_key_is_enqueued_as_literal_text() {
+ let (mut app, sink) = app_with_open_popup();
+ for c in "aZ 9".chars() {
+ app.handle_key(key_event(KeyCode::Char(c), KeyModifiers::NONE))
+ .unwrap();
+ }
+ assert_eq!(
+ sink.taken(),
+ "aZ 9"
+ .chars()
+ .map(|c| PaneInput::Text {
+ target: "proj:task".to_string(),
+ text: c.to_string(),
+ })
+ .collect::<Vec<_>>()
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn a_character_that_tmux_would_read_as_syntax_is_still_text() {
+ // `;` used to be sent through tmux's key-name lookup, where a standalone
+ // semicolon is a command separator β€” the keystroke never reached the pane.
+ // As text it is just a semicolon.
+ let (mut app, sink) = app_with_open_popup();
+ for c in [';', '$', '#', '"', '\\'] {
+ app.handle_key(key_event(KeyCode::Char(c), KeyModifiers::NONE))
+ .unwrap();
+ }
+ assert!(
+ sink.taken()
+ .iter()
+ .all(|input| matches!(input, PaneInput::Text { .. })),
+ "punctuation must never go through key-name lookup"
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn shifted_characters_carry_no_modifier_prefix() {
+ // crossterm reports the shifted character itself, so `M-A`/`S-a` would both
+ // be wrong: the character is the whole story.
+ let (mut app, sink) = app_with_open_popup();
+ app.handle_key(key_event(KeyCode::Char('A'), KeyModifiers::SHIFT))
+ .unwrap();
+ assert_eq!(
+ sink.taken(),
+ vec![PaneInput::Text {
+ target: "proj:task".to_string(),
+ text: "A".to_string(),
+ }]
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn named_keys_are_enqueued_as_key_names() {
+ let (mut app, sink) = app_with_open_popup();
+ for code in [
+ KeyCode::Enter,
+ KeyCode::Esc,
+ KeyCode::Up,
+ KeyCode::Down,
+ KeyCode::Left,
+ KeyCode::Right,
+ KeyCode::Backspace,
+ KeyCode::Tab,
+ KeyCode::Delete,
+ KeyCode::F(5),
+ ] {
+ app.handle_key(key_event(code, KeyModifiers::NONE)).unwrap();
+ }
+ let keys: Vec<String> = sink
+ .taken()
+ .into_iter()
+ .map(|input| match input {
+ PaneInput::Key { key, .. } => key,
+ other => panic!("expected a key, got {other:?}"),
+ })
+ .collect();
+ assert_eq!(
+ keys,
+ vec!["Enter", "Escape", "Up", "Down", "Left", "Right", "BSpace", "Tab", "DC", "F5"]
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn modified_characters_are_key_names_not_text() {
+ // Ctrl+a is a key; sending it as literal text would type an "a".
+ let (mut app, sink) = app_with_open_popup();
+ app.handle_key(key_event(KeyCode::Char('a'), KeyModifiers::CONTROL))
+ .unwrap();
+ app.handle_key(key_event(KeyCode::Char('b'), KeyModifiers::ALT))
+ .unwrap();
+ assert_eq!(
+ sink.taken(),
+ vec![
+ PaneInput::Key {
+ target: "proj:task".to_string(),
+ key: "C-a".to_string(),
+ },
+ PaneInput::Key {
+ target: "proj:task".to_string(),
+ key: "M-b".to_string(),
+ },
+ ]
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn the_popups_own_shortcuts_are_never_forwarded() {
+ // Ctrl+q closes, Ctrl+f toggles fullscreen, and Ctrl+u/d/g navigate. None of
+ // them belong to the agent, and forwarding one would be invisible damage.
+ let (mut app, sink) = app_with_open_popup();
+ for code in ['u', 'd', 'g', 'f'] {
+ app.handle_key(key_event(KeyCode::Char(code), KeyModifiers::CONTROL))
+ .unwrap();
+ }
+ assert!(
+ sink.taken()
+ .iter()
+ .all(|input| matches!(input, PaneInput::Barrier { .. })),
+ "popup-local shortcuts must enqueue nothing but the fullscreen barrier"
+ );
+ assert!(app.state.shell_popup.is_some());
+
+ app.handle_key(key_event(KeyCode::Char('q'), KeyModifiers::CONTROL))
+ .unwrap();
+ assert!(app.state.shell_popup.is_none(), "Ctrl+q closes the popup");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn ctrl_j_and_k_are_not_popup_keymaps() {
+ let (mut app, sink) = app_with_open_popup();
+ for code in ['j', 'k'] {
+ app.handle_key(key_event(KeyCode::Char(code), KeyModifiers::CONTROL))
+ .unwrap();
+ }
+ assert_eq!(
+ sink.taken(),
+ vec![
+ PaneInput::Key {
+ target: "proj:task".to_string(),
+ key: "C-j".to_string(),
+ },
+ PaneInput::Key {
+ target: "proj:task".to_string(),
+ key: "C-k".to_string(),
+ },
+ ],
+ "unmapped chords should pass through without agtx translating them"
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn closing_the_popup_waits_for_the_target_it_was_typed_into() {
+ // Batched characters belong to the pane they were typed into, and agtx's own
+ // next write to that pane β€” a phase advance is one keystroke away on the
+ // board β€” must not overtake them. An *enqueued* flush returns before
+ // delivery, so this has to be the acknowledged one.
+ let (mut app, sink) = app_with_open_popup();
+ app.handle_key(key_event(KeyCode::Char('h'), KeyModifiers::NONE))
+ .unwrap();
+ app.handle_key(key_event(KeyCode::Char('q'), KeyModifiers::CONTROL))
+ .unwrap();
+ assert!(
+ matches!(sink.taken().last(), Some(PaneInput::Barrier { .. })),
+ "closing the popup must wait for the queued prefix, not just enqueue a flush"
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn toggling_fullscreen_waits_before_resizing_the_pane() {
+ // The resize is a synchronous tmux subprocess on a different socket. If the
+ // flush were only enqueued it could still be pending when the resize lands,
+ // and the text would reach the pane at the wrong size.
+ let (mut app, sink) = app_with_open_popup();
+ app.handle_key(key_event(KeyCode::Char('x'), KeyModifiers::NONE))
+ .unwrap();
+ app.handle_key(key_event(KeyCode::Char('f'), KeyModifiers::CONTROL))
+ .unwrap();
+ let sent = sink.taken();
+ assert!(
+ matches!(sent.last(), Some(PaneInput::Barrier { .. })),
+ "Ctrl+F must wait for the queued prefix before it resizes, got {sent:?}"
+ );
+}
+
+/// Give the popup a pane that reports `history_size` lines of scrollback.
+#[cfg(feature = "test-mocks")]
+fn with_scrollback(app: &mut App, history_size: usize) {
+ if let Some(popup) = app.state.shell_popup.as_mut() {
+ popup.metrics = Some(crate::tmux::PaneMetrics {
+ cursor_x: 0,
+ cursor_y: 1,
+ pane_height: 20,
+ history_size,
+ });
+ popup.cached_content = (0..200)
+ .map(|i| format!("line {i}\n"))
+ .collect::<String>()
+ .into_bytes();
+ }
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn scroll_keys_move_the_popup_when_tmux_has_history() {
+ let (mut app, sink) = app_with_open_popup();
+ with_scrollback(&mut app, 500);
+ for code in [KeyCode::Char('p'), KeyCode::Char('u')] {
+ app.handle_key(key_event(code, KeyModifiers::CONTROL))
+ .unwrap();
+ }
+ app.handle_key(key_event(KeyCode::PageUp, KeyModifiers::NONE))
+ .unwrap();
+ assert_eq!(
+ app.state.shell_popup.as_ref().unwrap().scroll_offset,
+ -45,
+ "5 + 20 + 20 lines of agtx-side scrolling"
+ );
+ assert!(
+ sink.taken().is_empty(),
+ "with real scrollback the agent must not see the scroll keys"
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn hidden_ctrl_arrow_scroll_aliases_are_preserved() {
+ let (mut app, sink) = app_with_open_popup();
+ with_scrollback(&mut app, 500);
+ app.handle_key(key_event(KeyCode::Up, KeyModifiers::CONTROL))
+ .unwrap();
+ assert_eq!(app.state.shell_popup.as_ref().unwrap().scroll_offset, -5);
+ app.handle_key(key_event(KeyCode::Down, KeyModifiers::CONTROL))
+ .unwrap();
+ assert_eq!(app.state.shell_popup.as_ref().unwrap().scroll_offset, 0);
+ assert!(sink.taken().is_empty());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn scroll_keys_go_to_the_agent_when_tmux_has_no_history() {
+ // A pane in the alternate screen keeps no tmux scrollback, so agtx's buffer
+ // is one screen and scrolling it moves nothing. The agent owns the history,
+ // so it gets the key it scrolls with.
+ let (mut app, sink) = app_with_open_popup();
+ with_scrollback(&mut app, 0);
+ for code in [
+ KeyCode::Char('p'),
+ KeyCode::Char('n'),
+ KeyCode::Char('u'),
+ KeyCode::Char('d'),
+ ] {
+ app.handle_key(key_event(code, KeyModifiers::CONTROL))
+ .unwrap();
+ }
+ app.handle_key(key_event(KeyCode::PageUp, KeyModifiers::NONE))
+ .unwrap();
+ app.handle_key(key_event(KeyCode::PageDown, KeyModifiers::NONE))
+ .unwrap();
+ app.handle_key(key_event(KeyCode::Char('g'), KeyModifiers::CONTROL))
+ .unwrap();
+
+ let keys: Vec<String> = sink
+ .taken()
+ .into_iter()
+ .map(|input| match input {
+ PaneInput::Key { key, .. } => key,
+ other => panic!("expected a key, got {other:?}"),
+ })
+ .collect();
+ // Ctrl+N/P use the safe translation. `Up`/`Down` would scroll Claude's
+ // transcript view but
+ // recall prompt history in its main view, overwriting the composer β€” see
+ // `handle_popup_scroll`.
+ assert_eq!(
+ keys,
+ vec![
+ "PageUp", "PageDown", "PageUp", "PageDown", "PageUp", "PageDown", "End"
+ ]
+ );
+ assert_eq!(
+ app.state.shell_popup.as_ref().unwrap().scroll_offset,
+ 0,
+ "agtx must not also move its own buffer"
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn a_delegated_scroll_only_ever_sends_a_paging_key() {
+ // Passing the chord through instead of translating it would send `C-d` β€”
+ // an EOF that can end the session β€” and `C-u`, which kills the line the
+ // user is typing in the agent's composer.
+ let (mut app, sink) = app_with_open_popup();
+ with_scrollback(&mut app, 0);
+ for code in [KeyCode::Char('d'), KeyCode::Char('u'), KeyCode::Char('g')] {
+ app.handle_key(key_event(code, KeyModifiers::CONTROL))
+ .unwrap();
+ }
+ for input in sink.taken() {
+ match input {
+ PaneInput::Key { key, .. } => assert!(
+ matches!(key.as_str(), "PageUp" | "PageDown" | "End"),
+ "only keys that cannot alter the composer may be delegated; got {key}"
+ ),
+ other => panic!("expected a key, got {other:?}"),
+ }
+ }
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn unknown_pane_metrics_keep_the_popups_own_scrolling() {
+ // A failed `display -p` must not silently reroute keys into the agent.
+ let (mut app, sink) = app_with_open_popup();
+ if let Some(popup) = app.state.shell_popup.as_mut() {
+ popup.metrics = None;
+ popup.cached_content = b"a\nb\nc\n".to_vec();
+ }
+ app.handle_key(key_event(KeyCode::Char('p'), KeyModifiers::CONTROL))
+ .unwrap();
+ assert!(sink.taken().is_empty());
+ assert!(app.state.shell_popup.as_ref().unwrap().scroll_offset < 0);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn a_full_queue_warns_instead_of_sending_out_of_order() {
+ // Sending this key synchronously would put it ahead of everything already
+ // queued. A dropped key the user is told about beats a reordered one.
+ let (mut app, sink) = app_with_open_popup();
+ sink.fail_with(crate::tmux::InputError::QueueFull);
+ app.handle_key(key_event(KeyCode::Char('x'), KeyModifiers::NONE))
+ .unwrap();
+ let warning = app
+ .state
+ .warning_message
+ .as_ref()
+ .map(|(text, _)| text.clone())
+ .unwrap_or_default();
+ assert!(
+ warning.contains("dropped"),
+ "the user must be told a keystroke was dropped, got {warning:?}"
+ );
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn an_escalation_banner_swallows_only_the_first_key() {
+ let (mut app, sink) = app_with_open_popup();
+ if let Some(popup) = app.state.shell_popup.as_mut() {
+ popup.escalation_note = Some("needs a human".to_string());
+ }
+ app.handle_key(key_event(KeyCode::Char('a'), KeyModifiers::NONE))
+ .unwrap();
+ assert!(sink.taken().is_empty(), "the banner ate the keystroke");
+ app.handle_key(key_event(KeyCode::Char('b'), KeyModifiers::NONE))
+ .unwrap();
+ assert_eq!(
+ sink.taken(),
+ vec![PaneInput::Text {
+ target: "proj:task".to_string(),
+ text: "b".to_string(),
+ }]
+ );
+}
+
+#[test]
+fn a_popup_target_always_names_its_session() {
+ // A bare window name is resolved inside whichever session the issuing client
+ // is bound to β€” the attached one for the control client, the
+ // most-recently-used one for a subprocess. Neither is reliably this
+ // project's after a switch, and `orchestrator` exists in every project's
+ // session, so a bare target could type into another project's agent.
+ assert_eq!(pane_target("proj", "task-abc"), "proj:task-abc");
+ assert_eq!(pane_target("proj", "orchestrator"), "proj:orchestrator");
+ // Idempotent: the orchestrator builds its target qualified already, and
+ // re-qualifying would produce `proj:proj:orchestrator`, which resolves to
+ // nothing at all.
+ assert_eq!(
+ pane_target("proj", "proj:orchestrator"),
+ "proj:orchestrator"
+ );
+}
+
+#[test]
+fn control_mode_is_on_unless_turned_off() {
+ // There is no config field: a connection that fails or dies already falls
+ // back to the subprocess backend by itself. `AGTX_TMUX_CONTROL` stays as a
+ // one-run escape hatch so a bug report can be bisected across the two lanes.
+ //
+ // Serialised on a mutex and restored afterwards: the variable is process
+ // global, and `cargo test` runs these on threads that share it.
+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let previous = std::env::var("AGTX_TMUX_CONTROL").ok();
+
+ std::env::remove_var("AGTX_TMUX_CONTROL");
+ assert!(control_mode_enabled(), "on when nothing is set");
+
+ for off in ["0", "false", "no"] {
+ std::env::set_var("AGTX_TMUX_CONTROL", off);
+ assert!(!control_mode_enabled(), "{off} turns it off");
+ }
+ for on in ["1", "true", "yes"] {
+ std::env::set_var("AGTX_TMUX_CONTROL", on);
+ assert!(control_mode_enabled(), "{on} leaves it on");
+ }
+ // Anything unrecognised must not read as "off" β€” a typo in the escape hatch
+ // should leave the default alone rather than silently change lanes.
+ std::env::set_var("AGTX_TMUX_CONTROL", "maybe");
+ assert!(control_mode_enabled());
+
+ match previous {
+ Some(value) => std::env::set_var("AGTX_TMUX_CONTROL", value),
+ None => std::env::remove_var("AGTX_TMUX_CONTROL"),
+ }
+}
+
+#[test]
+fn an_unmapped_key_is_dropped_rather_than_guessed() {
+ // A key with no tmux name has no correct encoding; inventing one would type
+ // something the user did not press.
+ assert_eq!(
+ popup_key_input(
+ "t",
+ crossterm::event::KeyEvent::new(KeyCode::CapsLock, KeyModifiers::NONE)
+ ),
+ None
+ );
+}
diff --git a/src/tui/shell_popup.rs b/src/tui/shell_popup.rs
index e89676e..8888b80 100644
--- a/src/tui/shell_popup.rs
+++ b/src/tui/shell_popup.rs
@@ -22,9 +22,7 @@ pub struct ShellPopup {
/// expensive tmux captures for every character.
pub last_content_refresh: Instant,
/// Cursor position inside the visible tmux pane and its pane height.
- pub cursor_info: Option<(usize, usize, usize)>,
- /// Forward the next key directly to tmux, even when agtx normally owns it.
- pub pass_through_next_key: bool,
+ pub metrics: Option<crate::tmux::PaneMetrics>,
}
impl ShellPopup {
@@ -39,8 +37,7 @@ impl ShellPopup {
task_id: None,
fullscreen: false,
last_content_refresh: Instant::now(),
- cursor_info: None,
- pass_through_next_key: false,
+ metrics: None,
}
}
@@ -69,6 +66,19 @@ impl ShellPopup {
self.scroll_offset >= 0
}
+ /// Does tmux hold any history above this pane's visible screen?
+ ///
+ /// `false` means agtx has nothing to scroll: the agent is drawing in the
+ /// alternate screen and owns the session's scrollback itself. The popup's
+ /// scroll keys are then handed to the agent instead β€” scrolling agtx's
+ /// one-screen buffer would move nothing while looking like it had.
+ ///
+ /// Unknown metrics count as *has* scrollback, so a failed `display -p`
+ /// leaves the existing behaviour alone rather than silently rerouting keys.
+ pub fn has_scrollback(&self) -> bool {
+ self.metrics.map(|m| m.history_size > 0).unwrap_or(true)
+ }
+
pub fn content_refresh_due(&self, interval: Duration) -> bool {
self.last_content_refresh.elapsed() >= interval
}
@@ -139,25 +149,70 @@ pub fn compute_visible_lines<'a>(
/// Build the footer text for the shell popup
pub fn build_footer_text(scroll_offset: i32, start_line: usize) -> String {
- build_footer_text_for_mode(scroll_offset, start_line, false)
+ build_footer_text_for_mode(scroll_offset, start_line, false, true)
}
-fn build_footer_text_for_mode(scroll_offset: i32, start_line: usize, fullscreen: bool) -> String {
+fn build_footer_text_for_mode(
+ scroll_offset: i32,
+ start_line: usize,
+ fullscreen: bool,
+ has_scrollback: bool,
+) -> String {
let view_action = if fullscreen { "windowed" } else { "fullscreen" };
+ // `C-n/p` and `C-d/u` are both bound and both stay bound; the footer has
+ // room to name one pair, and `C-d/u` is the one advertised. Do not "fix"
+ // the mismatch by unbinding the other β€” see `handle_shell_popup_key`.
+ //
+ // With no tmux scrollback the scroll keys go to the agent, so advertising a
+ // line number agtx cannot move to is worse than saying nothing: that is
+ // exactly what made an empty buffer look like a broken scrollbar.
+ if !has_scrollback {
+ return format!(
+ "[C-d/u] scroll [C-g] bottom Β· [C-f] {view_action} [C-q] close"
+ );
+ }
if scroll_offset < 0 {
format!(
- " Line {} | [C-g] bottom [C-f] {} [C-Space] send next [C-q] close [C-j/k] scroll [C-d/u] page ",
+ "Line {} Β· [C-d/u] scroll [C-g] bottom Β· [C-f] {} [C-q] close",
start_line + 1,
view_action
)
} else {
format!(
- " At bottom | [C-f] {} [C-Space] send next [C-q] close [C-j/k] scroll [C-d/u] page ",
+ "At bottom Β· [C-d/u] scroll Β· [C-f] {} [C-q] close",
view_action
)
}
}
+/// Render popup shortcuts with the same key-first hierarchy as the board
+/// footer: keys carry the accent while labels and separators stay subdued.
+fn styled_footer(text: &str, colors: &ShellPopupColors) -> Line<'static> {
+ let key_style = Style::default().fg(colors.border).bold();
+ let label_style = Style::default().fg(colors.footer_bg);
+ let mut spans = Vec::new();
+ let mut rest = text;
+
+ while let Some(open) = rest.find('[') {
+ if open > 0 {
+ spans.push(Span::styled(rest[..open].to_string(), label_style));
+ }
+ let Some(close) = rest[open..].find(']') else {
+ spans.push(Span::styled(rest[open..].to_string(), label_style));
+ rest = "";
+ break;
+ };
+ let end = open + close + 1;
+ spans.push(Span::styled(rest[open..end].to_string(), key_style));
+ rest = &rest[end..];
+ }
+ if !rest.is_empty() {
+ spans.push(Span::styled(rest.to_string(), label_style));
+ }
+
+ Line::from(spans)
+}
+
/// Maximum number of trailing empty lines to keep after content
pub const MAX_TRAILING_EMPTY_LINES: usize = 3;
@@ -308,8 +363,8 @@ pub fn render_shell_popup(
// Title bar (pad to fill width)
let title = format!(" {} ", popup.task_title);
let padded_title = format!("{:<width$}", title, width = popup_chunks[0].width as usize);
- let title_bar = Paragraph::new(padded_title)
- .style(Style::default().fg(colors.header_bg).bold());
+ let title_bar =
+ Paragraph::new(padded_title).style(Style::default().fg(colors.header_bg).bold());
frame.render_widget(title_bar, popup_chunks[0]);
// Escalation banner (if present)
@@ -347,27 +402,28 @@ pub fn render_shell_popup(
// A captured pane is text-only; explicitly restore tmux's live cursor when
// it falls inside the current (non-scrolled) viewport.
if popup.scroll_offset >= 0 {
- if let Some((cursor_x, cursor_y, pane_height)) = popup.cursor_info {
+ if let Some((cursor_x, cursor_y, pane_height)) = popup.metrics.map(|m| m.cursor()) {
let pane_start = total_lines.saturating_sub(pane_height);
let cursor_line = pane_start.saturating_add(cursor_y);
if cursor_line >= start_line && cursor_line < start_line + visible_height {
- let x = popup_chunks[2]
- .x
- .saturating_add(cursor_x.min(popup_chunks[2].width.saturating_sub(1) as usize) as u16);
- let y = popup_chunks[2].y.saturating_add((cursor_line - start_line) as u16);
+ let x = popup_chunks[2].x.saturating_add(
+ cursor_x.min(popup_chunks[2].width.saturating_sub(1) as usize) as u16,
+ );
+ let y = popup_chunks[2]
+ .y
+ .saturating_add((cursor_line - start_line) as u16);
frame.set_cursor_position((x, y));
}
}
}
- // Footer with scroll indicator (pad to fill width)
- let footer_text = build_footer_text_for_mode(popup.scroll_offset, start_line, popup.fullscreen);
- let padded_footer = format!(
- "{:<width$}",
- footer_text,
- width = popup_chunks[3].width as usize
+ // Footer with scroll indicator and grouped, accented shortcuts.
+ let footer_text = build_footer_text_for_mode(
+ popup.scroll_offset,
+ start_line,
+ popup.fullscreen,
+ popup.has_scrollback(),
);
- let footer = Paragraph::new(padded_footer)
- .style(Style::default().fg(colors.footer_bg));
+ let footer = Paragraph::new(styled_footer(&footer_text, colors)).alignment(Alignment::Center);
frame.render_widget(footer, popup_chunks[3]);
}
diff --git a/tests/shell_popup_tests.rs b/tests/shell_popup_tests.rs
index 46f11f4..641763f 100644
--- a/tests/shell_popup_tests.rs
+++ b/tests/shell_popup_tests.rs
@@ -201,6 +201,47 @@ fn test_build_footer_text_at_bottom() {
let footer = build_footer_text(0, 10);
assert!(footer.contains("At bottom"));
assert!(!footer.contains("Line"));
+ assert!(footer.contains("[C-d/u] scroll Β· [C-f] fullscreen"));
+ assert!(!footer.contains("[C-j/k]"));
+ // Both pairs scroll; only one is advertised.
+ assert!(!footer.contains("[C-n/p]"));
+}
+
+#[test]
+fn agent_managed_history_is_described_by_actions_not_implementation() {
+ let popup = ShellPopup {
+ metrics: Some(agtx::tmux::PaneMetrics {
+ cursor_x: 0,
+ cursor_y: 0,
+ pane_height: 24,
+ history_size: 0,
+ }),
+ ..ShellPopup::new("Task".to_string(), "window".to_string())
+ };
+ let backend = TestBackend::new(100, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ terminal
+ .draw(|frame| {
+ render_shell_popup(
+ &popup,
+ frame,
+ Rect::new(0, 0, 100, 24),
+ vec![],
+ &ShellPopupColors::default(),
+ );
+ })
+ .unwrap();
+ let content: String = terminal
+ .backend()
+ .buffer()
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect();
+ assert!(content.contains("[C-d/u] scroll"));
+ assert!(!content.contains("[C-j/k]"));
+ assert!(!content.contains("[C-n/p]"));
+ assert!(!content.contains("scrollback"));
}
#[test]
@@ -208,6 +249,7 @@ fn test_build_footer_text_scrolled_up() {
let footer = build_footer_text(-5, 10);
assert!(footer.contains("Line 11")); // start_line + 1
assert!(footer.contains("bottom")); // Ctrl+g option visible
+ assert!(footer.contains("[C-d/u] scroll [C-g] bottom"));
}
#[test]
@@ -245,12 +287,6 @@ fn test_fullscreen_footer_offers_windowed_toggle() {
assert!(content.contains("[C-f] windowed"));
}
-#[test]
-fn test_footer_documents_reserved_key_passthrough() {
- let footer = build_footer_text(0, 0);
- assert!(footer.contains("[C-Space] send next"));
-}
-
// === Rendering Tests ===
#[test]
@@ -470,7 +506,7 @@ fn test_trim_trailing_empty_lines_whitespace_only() {
}
#[test]
-fn test_trim_content_to_cursor_no_cursor_info() {
+fn test_trim_content_to_cursor_no_metrics() {
let content = b"line 1\nline 2\n\n\n\n\n\n\n\n\n".to_vec();
let result = trim_content_to_cursor(content, None);
let result_str = String::from_utf8_lossy(&result);
@@ -482,14 +518,14 @@ fn test_trim_content_to_cursor_no_cursor_info() {
}
#[test]
-fn test_trim_content_to_cursor_with_cursor_info() {
+fn test_trim_content_to_cursor_with_metrics() {
// Simulate: 10 lines captured, pane_height=5, cursor at line 2 of visible area
// visible_pane_start = 10 - 5 = 5
// cursor_in_capture = 5 + 2 = 7
// Lines below cursor are empty (unused pane buffer) β†’ trimmed at cursor
let content = b"line 0\nline 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\n\n".to_vec();
- let cursor_info = Some((2, 5)); // cursor_y=2, pane_height=5
- let result = trim_content_to_cursor(content, cursor_info);
+ let metrics = Some((2, 5)); // cursor_y=2, pane_height=5
+ let result = trim_content_to_cursor(content, metrics);
let result_str = String::from_utf8_lossy(&result);
let lines: Vec<&str> = result_str.lines().collect();
@@ -504,8 +540,8 @@ fn test_trim_content_to_cursor_tui_cursor_mid_screen() {
// Should keep all content, not trim at cursor
let content =
b"header\nstatus bar\n\ninput field\n\noutput area\nmore output\nbottom bar".to_vec();
- let cursor_info = Some((3, 8)); // cursor_y=3 (mid-screen), pane_height=8
- let result = trim_content_to_cursor(content, cursor_info);
+ let metrics = Some((3, 8)); // cursor_y=3 (mid-screen), pane_height=8
+ let result = trim_content_to_cursor(content, metrics);
let result_str = String::from_utf8_lossy(&result);
let lines: Vec<&str> = result_str.lines().collect();
@@ -519,8 +555,8 @@ fn test_trim_content_to_cursor_cursor_at_bottom_with_empty() {
// Cursor at bottom of pane, but those lines are empty
// Should trim the empty lines via second pass
let content = b"line 0\nline 1\nline 2\n\n\n\n\n".to_vec();
- let cursor_info = Some((6, 7)); // cursor at line 6 of 7-line pane (bottom)
- let result = trim_content_to_cursor(content, cursor_info);
+ let metrics = Some((6, 7)); // cursor at line 6 of 7-line pane (bottom)
+ let result = trim_content_to_cursor(content, metrics);
let result_str = String::from_utf8_lossy(&result);
// Count newlines + 1 to avoid lines() quirk with trailing newlines
let line_count = result_str.matches('\n').count() + 1;
diff --git a/tests/tmux_control_tests.rs b/tests/tmux_control_tests.rs
new file mode 100644
index 0000000..e6576f4
--- /dev/null
+++ b/tests/tmux_control_tests.rs
@@ -0,0 +1,660 @@
+//! Real-tmux tests for the pane input path.
+//!
+//! The unit tests in `src/tmux/input.rs` and `src/tmux/control.rs` prove the
+//! broker's ordering and the encoder's escaping against recording doubles. They
+//! cannot prove the one thing that matters most here: that **tmux agrees**. Every
+//! bug this path can have is silent β€” a mis-encoded argument is still a valid
+//! command, a control client that joins the size calculation shrinks a pane, and
+//! a key that tmux resolves as a name never arrives as a character.
+//!
+//! So these run against a real `tmux` server on a throwaway socket, assert on
+//! the **bytes a program in the pane received** rather than on rendered output,
+//! and are opt-in:
+//!
+//! ```bash
+//! AGTX_TMUX_IT=1 cargo test --test tmux_control_tests -- --nocapture
+//! ```
+//!
+//! They are opt-in because they start processes, take seconds rather than
+//! milliseconds, and depend on a tmux whose version the machine chooses. When
+//! they are skipped they say so by name rather than passing quietly.
+
+use agtx::tmux::input::{spawn, InputConfig, PaneInput, PaneInputSink};
+use agtx::tmux::TmuxOperations;
+use anyhow::Result;
+use std::process::Command;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+/// Skip guard. Returns the reason, so a skipped test names itself.
+fn skip_reason() -> Option<&'static str> {
+ if std::env::var("AGTX_TMUX_IT").ok().as_deref() != Some("1") {
+ return Some("AGTX_TMUX_IT=1 not set (opt-in: starts real tmux servers)");
+ }
+ if which::which("tmux").is_err() {
+ return Some("tmux is not installed");
+ }
+ None
+}
+
+macro_rules! guard {
+ () => {
+ if let Some(reason) = skip_reason() {
+ eprintln!("SKIP {}: {}", module_path!(), reason);
+ return;
+ }
+ };
+}
+
+/// A tmux server on its own socket, killed when the test ends β€” including when
+/// it panics, which is when a leaked server would be most confusing.
+struct Server {
+ name: String,
+ dir: tempfile::TempDir,
+}
+
+impl Server {
+ fn start(tag: &str) -> Self {
+ let name = format!(
+ "agtx-it-{tag}-{}",
+ std::process::id() as u64 * 1_000 + rand_suffix()
+ );
+ let server = Self {
+ name,
+ dir: tempfile::tempdir().expect("tempdir"),
+ };
+ server
+ .tmux(&["new-session", "-d", "-s", "it", "-x", "200", "-y", "50"])
+ .expect("start a session");
+ server
+ }
+
+ fn tmux(&self, args: &[&str]) -> Result<String> {
+ let out = Command::new("tmux")
+ .args(["-L", &self.name])
+ .args(args)
+ .output()?;
+ if !out.status.success() {
+ anyhow::bail!(
+ "tmux {:?} failed: {}",
+ args,
+ String::from_utf8_lossy(&out.stderr)
+ );
+ }
+ Ok(String::from_utf8_lossy(&out.stdout).to_string())
+ }
+
+ /// A window whose pane writes everything it is sent into `name.txt`, so a
+ /// test can assert on exact bytes instead of on what a terminal drew.
+ fn recording_window(&self, name: &str) -> String {
+ let path = self.dir.path().join(format!("{name}.txt"));
+ self.tmux(&[
+ "new-window",
+ "-d",
+ "-t",
+ "it:",
+ "-n",
+ name,
+ "sh",
+ "-c",
+ &format!("cat > {}", path.display()),
+ ])
+ .expect("create the recording window");
+ // The shell has to be running before anything is typed at it.
+ std::thread::sleep(Duration::from_millis(300));
+ format!("it:{name}")
+ }
+
+ fn recorded(&self, name: &str) -> Vec<u8> {
+ std::fs::read(self.dir.path().join(format!("{name}.txt"))).unwrap_or_default()
+ }
+
+ /// Cheap enough (a stat, tens of microseconds) to poll in a latency loop.
+ fn recorded_len(&self, name: &str) -> u64 {
+ std::fs::metadata(self.dir.path().join(format!("{name}.txt")))
+ .map(|m| m.len())
+ .unwrap_or(0)
+ }
+
+ fn pane_size(&self, target: &str) -> String {
+ self.tmux(&[
+ "display",
+ "-p",
+ "-t",
+ target,
+ "#{pane_width}x#{pane_height}",
+ ])
+ .map(|s| s.trim().to_string())
+ .unwrap_or_default()
+ }
+}
+
+impl Drop for Server {
+ fn drop(&mut self) {
+ let _ = self.tmux(&["kill-server"]);
+ }
+}
+
+fn rand_suffix() -> u64 {
+ use std::time::{SystemTime, UNIX_EPOCH};
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.subsec_nanos() as u64)
+ .unwrap_or(0)
+}
+
+/// `TmuxOperations` bound to a test server.
+///
+/// `RealTmuxOps` hard-codes the `agtx` socket, which is the production server a
+/// developer's own tasks are running on. Only the three send primitives the
+/// broker's fallback uses are implemented; anything else would be a silent way
+/// for a test to reach the wrong server.
+struct TestTmuxOps {
+ server: String,
+}
+
+impl TestTmuxOps {
+ fn run(&self, args: &[&str]) {
+ let _ = Command::new("tmux")
+ .args(["-L", &self.server])
+ .args(args)
+ .output();
+ }
+}
+
+impl TmuxOperations for TestTmuxOps {
+ fn create_window(
+ &self,
+ _session: &str,
+ _window_name: &str,
+ _working_dir: &str,
+ _command: Option<String>,
+ _keep_shell_on_exit: bool,
+ _env: &[(String, String)],
+ ) -> Result<()> {
+ unimplemented!("not used by the input broker")
+ }
+ fn kill_window(&self, _target: &str) -> Result<()> {
+ unimplemented!("not used by the input broker")
+ }
+ fn window_exists(&self, _target: &str) -> Result<bool> {
+ unimplemented!("not used by the input broker")
+ }
+ fn send_keys(&self, target: &str, keys: &str) -> Result<()> {
+ self.run(&["send-keys", "-t", target, keys]);
+ self.run(&["send-keys", "-t", target, "Enter"]);
+ Ok(())
+ }
+ fn send_key(&self, target: &str, keys: &str) -> Result<()> {
+ self.run(&["send-keys", "-t", target, keys]);
+ Ok(())
+ }
+ fn send_text(&self, target: &str, text: &str) -> Result<()> {
+ self.run(&["send-keys", "-t", target, "-l", "--", text]);
+ Ok(())
+ }
+ fn paste_text(&self, target: &str, text: &str) -> Result<()> {
+ use std::io::Write;
+ let mut child = Command::new("tmux")
+ .args(["-L", &self.server, "load-buffer", "-"])
+ .stdin(std::process::Stdio::piped())
+ .spawn()?;
+ if let Some(mut stdin) = child.stdin.take() {
+ stdin.write_all(text.as_bytes())?;
+ }
+ child.wait()?;
+ self.run(&["paste-buffer", "-p", "-t", target]);
+ Ok(())
+ }
+ fn capture_pane(&self, _target: &str) -> Result<String> {
+ unimplemented!("not used by the input broker")
+ }
+ fn capture_pane_with_history(&self, _target: &str, _history_lines: i32) -> Vec<u8> {
+ unimplemented!("not used by the input broker")
+ }
+ fn pane_metrics(&self, _target: &str) -> Option<agtx::tmux::PaneMetrics> {
+ None
+ }
+ fn resize_window(&self, _target: &str, _width: u16, _height: u16) -> Result<()> {
+ unimplemented!("not used by the input broker")
+ }
+ fn pane_current_command(&self, _target: &str) -> Option<String> {
+ None
+ }
+ fn has_session(&self, _session: &str) -> bool {
+ true
+ }
+ fn create_session(&self, _session: &str, _working_dir: &str) -> Result<()> {
+ unimplemented!("not used by the input broker")
+ }
+}
+
+fn sink_for(server: &Server, control_mode: bool) -> Arc<dyn PaneInputSink> {
+ let mut config = InputConfig::new(server.name.clone(), "it");
+ config.control_mode = control_mode;
+ spawn(
+ config,
+ Arc::new(TestTmuxOps {
+ server: server.name.clone(),
+ }),
+ )
+}
+
+/// Wait for the pane's recorded bytes to settle, then return them.
+fn settle(server: &Server, window: &str) -> Vec<u8> {
+ std::thread::sleep(Duration::from_millis(400));
+ server.recorded(window)
+}
+
+// --- ordering and encoding ---
+
+#[test]
+fn a_thousand_characters_and_a_cursor_move_arrive_in_order() {
+ guard!();
+ let server = Server::start("order");
+ let target = server.recording_window("order");
+ let sink = sink_for(&server, true);
+
+ for _ in 0..1000 {
+ sink.text(&target, "a").unwrap();
+ }
+ sink.key(&target, "Left").unwrap();
+ sink.text(&target, "X").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ // The tty is in canonical mode, so an arrow key is not interpreted: it lands
+ // in the line buffer as the escape sequence tmux sent, between the `a`s and
+ // the `X`. That is exactly the ordering claim, in bytes.
+ let mut expected = vec![b'a'; 1000];
+ expected.extend_from_slice(b"\x1b[D");
+ expected.push(b'X');
+ expected.push(b'\n');
+ assert_eq!(settle(&server, "order"), expected);
+}
+
+#[test]
+fn text_that_spells_a_tmux_key_name_stays_text() {
+ guard!();
+ let server = Server::start("keyname");
+ let target = server.recording_window("keyname");
+ let sink = sink_for(&server, true);
+
+ // Without `-l` tmux resolves each of these as a key: `Space` would arrive as
+ // 0x20, `Up` as an escape sequence, and the words themselves would be gone.
+ for word in ["Space", "Enter", "Up", "C-c", "--", "-x"] {
+ sink.text(&target, word).unwrap();
+ sink.text(&target, " ").unwrap();
+ }
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ assert_eq!(
+ settle(&server, "keyname"),
+ b"Space Enter Up C-c -- -x \n".to_vec()
+ );
+}
+
+#[test]
+fn every_character_the_encoder_escapes_survives_the_round_trip() {
+ guard!();
+ let server = Server::start("escape");
+ let target = server.recording_window("escape");
+ let sink = sink_for(&server, true);
+
+ // One string per replacement tmux performs inside double quotes, plus the
+ // punctuation that would end the argument or start a new command.
+ let payload = r##"$HOME #{pane_id} ~root "quoted" back\slash semi;colon 'single' %pct"##;
+ sink.text(&target, payload).unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ assert_eq!(
+ String::from_utf8_lossy(&settle(&server, "escape")),
+ format!("{payload}\n")
+ );
+}
+
+#[test]
+fn unicode_survives_the_control_connection() {
+ guard!();
+ let server = Server::start("unicode");
+ let target = server.recording_window("unicode");
+ let sink = sink_for(&server, true);
+
+ let payload = "ν•œκ΅­μ–΄ naΓ―ve πŸ˜€ ok";
+ for ch in payload.chars() {
+ sink.text(&target, &ch.to_string()).unwrap();
+ }
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ assert_eq!(
+ String::from_utf8_lossy(&settle(&server, "unicode")),
+ format!("{payload}\n")
+ );
+}
+
+#[test]
+fn a_multiline_paste_arrives_as_one_block_in_order() {
+ guard!();
+ let server = Server::start("paste");
+ let target = server.recording_window("paste");
+ let sink = sink_for(&server, true);
+
+ sink.text(&target, "before ").unwrap();
+ sink.paste(&target, "one\ntwo").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ // A paste travels the buffer, not the control connection; the barrier is
+ // what keeps it behind the text typed before it. Both lines arrive as one
+ // block, in order, after the text typed first.
+ //
+ // No `\e[200~` markers here: tmux emits the bracketed-paste wrapper only for
+ // a pane that asked for it (DECSET 2004), and `cat` does not β€” which is the
+ // point of using `paste-buffer -p` rather than writing the markers by hand.
+ assert_eq!(
+ String::from_utf8_lossy(&settle(&server, "paste")),
+ "before one\ntwo\n"
+ );
+}
+
+// --- the properties that made control mode risky ---
+
+#[test]
+fn the_control_client_never_changes_the_pane_size() {
+ guard!();
+ let server = Server::start("size");
+ let target = server.recording_window("size");
+ let before = server.pane_size(&target);
+ assert_eq!(
+ before, "200x50",
+ "the fixture window should start at 200x50"
+ );
+
+ let sink = sink_for(&server, true);
+ sink.text(&target, "x").unwrap();
+ sink.flush().unwrap();
+ std::thread::sleep(Duration::from_millis(300));
+ let during = server.pane_size(&target);
+
+ sink.shutdown();
+ std::thread::sleep(Duration::from_millis(300));
+ let after = server.pane_size(&target);
+
+ // `-f ignore-size` is what guarantees this. A control client that took part
+ // in the size calculation would resize the very pane the popup sized by hand.
+ assert_eq!(
+ (before.as_str(), during.as_str(), after.as_str()),
+ ("200x50", "200x50", "200x50")
+ );
+}
+
+#[test]
+fn a_missing_target_window_does_not_wedge_the_broker() {
+ guard!();
+ let server = Server::start("missing");
+ let target = server.recording_window("live");
+ let sink = sink_for(&server, true);
+
+ // tmux answers with `%error` and keeps the connection: the next request must
+ // still land.
+ sink.text("it:no-such-window", "lost").unwrap();
+ sink.flush().unwrap();
+ sink.text(&target, "found").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ assert_eq!(settle(&server, "live"), b"found\n".to_vec());
+}
+
+#[test]
+fn a_target_naming_another_session_is_delivered_there() {
+ guard!();
+ // The regression guard for the bug this file could not see: every test here
+ // used an `it:`-qualified target while the popup passed a bare window name,
+ // which tmux resolves *inside the attached session*. A second session with a
+ // window the attached one does not have is the shape that failed β€”
+ // `%error can't find pane`, keystroke dropped, `write_command` still `Ok`.
+ let server = Server::start("cross");
+ let target = server.recording_window("here");
+ let sink = sink_for(&server, true);
+
+ let path = server.dir.path().join("there.txt");
+ server
+ .tmux(&[
+ "new-session",
+ "-d",
+ "-s",
+ "other",
+ "-n",
+ "there",
+ "sh",
+ "-c",
+ &format!("cat > {}", path.display()),
+ ])
+ .expect("create the second session");
+ std::thread::sleep(Duration::from_millis(300));
+
+ // The client is attached to `it`; this names `other` and must land there.
+ sink.text("other:there", "elsewhere").unwrap();
+ sink.key("other:there", "Enter").unwrap();
+ // ...without disturbing the session it is attached to.
+ sink.text(&target, "here").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ std::thread::sleep(Duration::from_millis(400));
+ assert_eq!(
+ String::from_utf8_lossy(&std::fs::read(&path).unwrap_or_default()),
+ "elsewhere\n"
+ );
+ assert_eq!(settle(&server, "here"), b"here\n".to_vec());
+}
+
+#[test]
+fn a_restarted_server_is_reconnected_to() {
+ guard!();
+ let server = Server::start("restart");
+ let target = server.recording_window("first");
+ let sink = sink_for(&server, true);
+ sink.text(&target, "before").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ std::thread::sleep(Duration::from_millis(300));
+
+ let _ = server.tmux(&["kill-server"]);
+ std::thread::sleep(Duration::from_millis(300));
+ server
+ .tmux(&["new-session", "-d", "-s", "it", "-x", "200", "-y", "50"])
+ .expect("restart the session");
+ let target = server.recording_window("second");
+ // Past the first reconnect backoff.
+ std::thread::sleep(Duration::from_millis(600));
+
+ sink.text(&target, "after").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ assert_eq!(settle(&server, "second"), b"after\n".to_vec());
+}
+
+#[test]
+fn a_noisy_pane_cannot_stall_the_writer() {
+ guard!();
+ let server = Server::start("noisy");
+ let target = server.recording_window("quiet");
+ server
+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "noise", "yes"])
+ .expect("create the noisy window");
+ let sink = sink_for(&server, true);
+
+ // `-f no-output` is why this is not a deadlock: without it every byte `yes`
+ // prints would be mirrored down our stdout, and a reader that fell behind
+ // would block the server writing to it.
+ let started = Instant::now();
+ for _ in 0..200 {
+ sink.text(&target, "z").unwrap();
+ }
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+ assert!(
+ started.elapsed() < Duration::from_secs(10),
+ "the writer stalled behind pane output"
+ );
+ assert_eq!(
+ settle(&server, "quiet"),
+ [vec![b'z'; 200], vec![b'\n']].concat()
+ );
+}
+
+#[test]
+fn the_subprocess_backend_delivers_the_same_bytes() {
+ guard!();
+ let server = Server::start("subproc");
+ let target = server.recording_window("subproc");
+ // control_mode off: the fallback path, unchanged behaviour, same assertions.
+ let sink = sink_for(&server, false);
+
+ sink.text(&target, "abc").unwrap();
+ sink.key(&target, "Left").unwrap();
+ sink.text(&target, "X").unwrap();
+ sink.key(&target, "Enter").unwrap();
+ sink.shutdown();
+
+ assert_eq!(settle(&server, "subproc"), b"abc\x1b[DX\n".to_vec());
+}
+
+// --- the measurement the whole change exists for ---
+
+#[test]
+fn control_mode_is_faster_than_a_process_per_key() {
+ guard!();
+ let server = Server::start("bench");
+ let samples = 200;
+
+ // (1) The baseline this whole change exists to remove: one `tmux` process
+ // per key, timed the way the TUI thread used to pay for it.
+ let bench_target = server.recording_window("bench");
+ let mut subprocess_spawn = Vec::with_capacity(samples);
+ for _ in 0..samples {
+ let started = Instant::now();
+ let _ = Command::new("tmux")
+ .args([
+ "-L",
+ &server.name,
+ "send-keys",
+ "-t",
+ &bench_target,
+ "-l",
+ "--",
+ "a",
+ ])
+ .output();
+ subprocess_spawn.push(started.elapsed());
+ }
+
+ // (2) What the TUI thread pays now: an enqueue and nothing else.
+ let control = sink_for(&server, true);
+ control.text(&bench_target, "warmup").unwrap();
+ control.flush().unwrap();
+ std::thread::sleep(Duration::from_millis(200));
+ let mut enqueue = Vec::with_capacity(samples);
+ for _ in 0..samples {
+ let started = Instant::now();
+ control.text(&bench_target, "b").unwrap();
+ enqueue.push(started.elapsed());
+ }
+
+ // (3) End to end: enqueue until the byte has reached a program in the pane.
+ // Measured for both backends in the same run, on the same machine, under
+ // whatever load this test suite is putting on it β€” the only comparison
+ // that means anything.
+ let control_target = server.recording_window("ctl");
+ let control_delivery = delivery_samples(&server, "ctl", &control_target, control.as_ref(), 60);
+ control.shutdown();
+
+ let sub_target = server.recording_window("sub");
+ let subprocess = sink_for(&server, false);
+ let subprocess_delivery =
+ delivery_samples(&server, "sub", &sub_target, subprocess.as_ref(), 60);
+ subprocess.shutdown();
+
+ let enqueue_p95 = p95(enqueue);
+ let spawn_p95 = p95(subprocess_spawn);
+ let control_p95 = p95(control_delivery);
+ let subprocess_p95 = p95(subprocess_delivery);
+ eprintln!(
+ "{}: per-key subprocess spawn p95 {spawn_p95:?} | enqueue p95 {enqueue_p95:?} | \
+ delivery p95 control {control_p95:?} vs subprocess {subprocess_p95:?}",
+ agtx_tmux_version()
+ );
+
+ // The plan's success criteria, as assertions rather than as prose.
+ assert!(
+ enqueue_p95 < Duration::from_millis(1),
+ "the TUI thread must not wait: enqueue p95 was {enqueue_p95:?}"
+ );
+ assert!(
+ enqueue_p95 * 10 < spawn_p95,
+ "enqueue {enqueue_p95:?} vs a process spawn {spawn_p95:?}"
+ );
+ assert!(
+ control_p95 < subprocess_p95,
+ "control delivery {control_p95:?} was not faster than subprocess {subprocess_p95:?}"
+ );
+}
+
+/// Time from enqueue until a program in the pane has actually read the byte.
+fn delivery_samples(
+ server: &Server,
+ window: &str,
+ target: &str,
+ sink: &dyn PaneInputSink,
+ samples: usize,
+) -> Vec<Duration> {
+ let mut out = Vec::with_capacity(samples);
+ for _ in 0..samples {
+ let before = server.recorded_len(window);
+ let started = Instant::now();
+ // The Enter is what makes the line discipline hand the line to `cat`;
+ // it is part of what is being measured, for both backends alike.
+ sink.text(target, "a").unwrap();
+ sink.key(target, "Enter").unwrap();
+ while server.recorded_len(window) == before {
+ if started.elapsed() > Duration::from_secs(2) {
+ break;
+ }
+ std::thread::sleep(Duration::from_micros(100));
+ }
+ out.push(started.elapsed());
+ }
+ out
+}
+
+fn p95(mut samples: Vec<Duration>) -> Duration {
+ samples.sort();
+ samples[((samples.len() as f64 * 0.95) as usize).saturating_sub(1)]
+}
+
+fn agtx_tmux_version() -> String {
+ Command::new("tmux")
+ .arg("-V")
+ .output()
+ .ok()
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
+ .unwrap_or_else(|| "tmux ?".to_string())
+}
+
+/// Exists so the file still compiles the imports when every test skips.
+#[test]
+fn a_pane_input_names_its_target() {
+ assert_eq!(
+ PaneInput::Text {
+ target: "s:w".into(),
+ text: "a".into()
+ }
+ .target(),
+ Some("s:w")
+ );
+}