ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
perf: pane capture and event loop (#147)
Fynn Flueggeb8b4c4b0e258
diff --git a/CLAUDE.md b/CLAUDE.mdindex be24baa..0c5e2d5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -279,21 +279,31 @@ waiting on: the keys forwarded from an open task popup.crossterm key eventβ popup_key_input() β Char β Text, everything else β KeyβΌ- PaneInputSink::send β enqueue, ~1 Β΅s, never waits for tmux+ PaneInputSink::send β enqueue only, never waits for tmuxbounded channel (1024)βΌone broker thread β the single ordering authority- ββ coalesces adjacent Text for the same target (2 ms window, 4 KiB cap)+ ββ coalesces adjacent Text for the same target (only while more is queued)ββ 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)++ popup refresh thread βββΊ PaneInputSink::capture βββ same queue, same connection+ β (flushes first, then `capture-pane` + `display -p`)+ βΌ+ ShellPopup.cached_content β drawn on the next frame```-**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).+`SHELL_REFRESH_INTERVAL` bounds how stale the pane on screen is, and it only became a real knob+once the capture stopped costing a pair of `tmux` processes. Its cost is paid per capture rather+than per wake-up, and on the far side: a capture makes the tmux server format the whole pane. The+ANSI parse is done **once per change on the watcher thread**, not once per frame on the UI thread β+`ShellPopup` carries `cached_lines` beside `cached_content`, set together by `set_content` so the+bytes change detection compares and the lines the popup renders cannot drift.++**Every key used to be a process.** `send_key` started a `tmux` client and waited for it, on the+input thread, per keystroke β that is the whole reason this lane exists. Enqueueing is now+effectively free, and delivery rides a persistent control connection.- **`PaneInput` is typed, not a formatted command**, because the broker must be able to tell literaltext from a key name: text goes out with `send-keys -l` (no key-name lookup), a key without it.@@ -302,13 +312,21 @@ p95** against 38 ms for the subprocess path (tmux 3.5a, macOS; the measurement ltmux separates commands.- **Batching never delays a key.** Enter, Escape, arrows, and anything Ctrl/Alt-modified flush thebuffer first and go immediately. A delayed Enter is a visibly broken editor.+- **Nor does it delay ordinary typing.** Buffered text is flushed as soon as the queue is empty, and+ between two keystrokes a human makes it always is: waiting out `DEFAULT_BATCH_WINDOW` would have+ taxed *every* character while coalescing nothing, since there was no successor to merge with. The window survives as the bound on a genuine backlog β a paste arriving as+ keystrokes, a held key β which is the only case it was ever for. That also makes coalescing+ opportunistic by nature, so `input_tests.rs` pre-queues input before starting the broker rather+ than racing it: a test that sends three characters to a running broker is asserting how fast the+ machine is.- **A target change flushes.** Queued characters belong to the pane they were typed into; the popupclose, 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 aconnection 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 brokeralready 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 β+ report needs to bisect the two lanes; `AGTX_TMUX_PUSH=0` does the same for the two *capture*+ lanes, leaving control mode on but forcing the watcher back onto its timer. The non-blocking broker is *not* conditional either way βthe backend choice only decides what the broker thread writes through, so the subprocess path getsthe 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@@ -333,6 +351,34 @@ p95** against 38 ms for the subprocess path (tmux 3.5a, macOS; the measurement lplace, keeping its order.- **A full queue warns rather than reordering.** Sending synchronously would put that key ahead ofeverything already queued, so agtx keeps the prefix and tells the user.+- **The popup's pane capture rides the same connection**, as a `Capture` request in the input queue.+ A *read* in an input queue looks misplaced until you ask what it is ordered against: the capture+ must show the keys typed before it, and the broker is the only thing that knows whether those have+ been flushed. It is also where the popup's lag actually lived: two `tmux` processes+ (`capture-pane` + `display -p`) against the same pair over the control connection. Process+ *startup* was the whole cost, not the work β `display -p`, which reads four variables, cost the+ same as capturing 500 lines.+ - The broker **declines** rather than falling back: with no control connection the caller's own+ `capture-pane` is the same two processes for the same price, and running them on the broker+ thread would park the next keystroke behind that `fork`/`exec`. `capture_pane_for_popup` owns+ that fallback, and a declined capture costs one frame at the old speed.+ - A failed capture **keeps** a healthy connection, unlike a failed write. A write error is+ ambiguous and tears the connection down; a read error is not, and demoting every later keystroke+ to the subprocess path over one failed read would trade the fix for the bug.+ - Both commands go in **one round trip**, which is also what keeps them consistent β the cursor row+ is an index *into* the content, so metrics fetched a frame later can trim off a line the user+ just typed. `PANE_METRICS_FORMAT` and `parse_pane_metrics` are shared with the subprocess path so+ the two cannot drift, and a real-tmux test asserts the captures are **byte-identical**: they+ parse different things (a process's stdout against reassembled `%begin`/`%end` payload lines) and+ the popup would happily draw a subtly wrong frame without failing.+ - The format literal is **single-quoted, not `tmux_quote`d**: tmux performs no replacements inside+ single quotes, so `#{cursor_x}` reaches `display-message` intact instead of being escaped to a+ literal `\#{cursor_x}`. Verified on 3.5a that `-t` is honoured for the expansion, so a client+ attached to one session reports the *target* pane and not its own active one.+ - Because a payload is now a whole pane capture, `FrameParser` closes a block only on an `%end`+ whose command id matches the `%begin`'s. An agent that paints a line starting `%end ` would+ otherwise end the block early, hand back half a capture, and leave `completed` permanently ahead+ of the commands actually run β which every barrier and query counts on.- **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 pastebehind the text typed before it.@@ -758,15 +804,108 @@ Plugin defaults to the project's active plugin (set via `P` on the board).- Migrations via `ALTER TABLE ... ADD COLUMN` (ignores errors if column exists)- DateTime stored as RFC3339 strings+### The Event Loop+`App::run` **blocks** on one `mpsc` channel that two threads feed, and draws only when something+changed. It used to poll: `event::poll(interval)` woke it on a timer whether or not anything had+happened, and every wake-up redrew the whole screen, re-parsed the pane capture, and queried SQLite.++```text+agtx-terminal-input βββ blocking `event::read()`+ ββββΊ mpsc<Wake> βββΊ run(): recv_timeout(HOUSEKEEPING_TICK)+agtx-pane-watch βββββββ β+ captures the open popup's pane, ββ draw, if anything set `dirty`+ sends only when it CHANGED ββ housekeeping, on its own tick+```++That one interval had been standing in for three unrelated things, and tuning it for any one of them+priced the other two wrongly. They are now separate:++- **Echo latency** is the pane watcher's cadence, and the watcher learns a pane painted in one of+ two ways:+ - **push** β a second control client attached **without** `no-output` (`OutputWatch`), open only+ while a popup is, whose `%output` notifications say which pane painted. `SHELL_REFRESH_INTERVAL`+ then stops being a poll period and becomes a **rate limit**: the signal removes the floor, the+ interval keeps the ceiling, since a pane painting flat out notifies far faster than it is worth+ capturing.+ - **The ceiling has two heights, and that is load-bearing.** A capture makes the *tmux server*+ format the whole pane, so capturing every frame is expensive where nobody is watching for one:+ `PANE_OUTPUT_MIN_INTERVAL` paces the agent's output, `SHELL_REFRESH_INTERVAL` paces the user's+ own echo, and `PANE_TYPING_WINDOW` keeps the fast one in force after a keystroke β because the+ echo arrives as a *paint*, indistinguishable from the agent's output, so pacing paints without+ the window would delay every character. Sharing one interval made a pane painting flat out cost+ more than the polling it replaced, which had been protected by its own slowness: one+ `capture-pane` process per capture is a low ceiling of its own.+ - **poll** β the timer, when push is unavailable (`AGTX_TMUX_PUSH=0`, control mode off, or a pane+ whose id cannot be read). Not a degraded copy: it is the whole design in that case.++ Either way the watcher *compares* and wakes the loop only on a difference β far cheaper than the+ capture that feeds it. `docs/planning/pane-output-push.md` has the design notes.+- **Capture depth follows the scroll position.** At the bottom only the visible rows are rendered,+ so `SHELL_POPUP_TAIL_LINES` (100) is asked for and `SHELL_POPUP_CAPTURE_LINES` (500) only once the+ user scrolls up (`popup_capture_depth`); a scroll is not a target change but it does poke the+ watcher, so the deeper capture arrives immediately rather than after the next paint. This is worth+ nothing for the agents that matter β they take the alternate screen, where `history_size` is 0 and+ every depth returns the same bytes β and a lot for a pane that accumulates history, where the+ deeper capture is many times the size of the screen being rendered.+- **Three things about `%output` shape that design.** It is scoped to the **attached session** and+ no other, so the watch client attaches to the popup's own session. `no-output` is fixed at attach+ time β it survives every `refresh-client` form on 3.5a β which is why this is a *second* client+ rather than a flag flip on the input one, and why nothing is mirrored while no popup is open. And+ it means *bytes reached the pty*, not that the rendered pane differs, so `PANE_PUSH_BACKSTOP`+ stays as the net for a signal that never came.+- **Housekeeping** β `maybe_spawn_session_refresh`, expiring warnings, the MCP transition queue β+ runs on `HOUSEKEEPING_TICK`. It used to run once per loop iteration, so its rate rose and fell+ with how fast the user typed β and it contains a SQLite query. That query has since moved to its+ own `TRANSITION_POLL_INTERVAL`: a request to move a task between columns is acted on against a+ phase status that is itself only as fresh as `PHASE_STATUS_CACHE_TTL`, so reading it faster buys+ nothing.+- **Nothing on the board animates.** The `Working` indicator is a static `βΆ`, not a spinner. On an+ otherwise idle board the spinner was the *only* thing forcing a redraw, and the card already said+ the task was running. A future animated indicator brings that cost back, and+ `nothing_on_the_board_animates` fails if one appears.+- **A closing window is pushed, not polled.** tmux sends `%window-close` / `%unlinked-window-close`+ to a `no-output` client β verified on 3.5a β so the connection agtx already holds for keystrokes+ reports an agent exiting. It raises a flag (`InputConfig::window_events`); housekeeping ages out+ the phase-status cache so the next refresh looks immediately. A flag rather than the window id,+ because the id would have to be resolved to a task anyway and "look again" is the whole signal.+ An `Exited` card then appears promptly instead of on the refresh's next tick.+- **Drawing** happens when `dirty` was set: input, a changed capture, or a background result.+ Nothing else asks for a frame, so an idle board and an idle popup both cost only the backstop.++Two details worth keeping:++- **`REDRAW_BACKSTOP` is a safety net, not the mechanism.** A missed `dirty` would leave a stale+ screen until the next keystroke, which is far worse than one wasted frame a second. If it is ever+ what makes the UI look right, something above it is wrong.+- **The poll fallback backs off** to `PANE_IDLE_INTERVAL` after `PANE_IDLE_ROUNDS` still captures,+ and a keystroke pokes it back to the fast cadence. The reset is the half that makes the back-off+ safe: the capture a poke triggers runs *before* the key that caused it has reached the pane and+ been echoed, so it sees nothing new β leaving the count alone made the first keystroke after a+ pause wait out another whole idle interval. `pane_watch_rounds_after_wait` exists so a test can+ pin that.+### Background Operations- PR description generation runs in background thread- PR creation runs in background thread- Phase status polling runs in background thread (`maybe_spawn_session_refresh`)-- Uses `mpsc` channels to communicate results back to main thread via `try_recv()` (non-blocking)+- Results come back over `mpsc` and are collected by `pump_background_results()` on each wake-up+ (non-blocking `try_recv`), which reports whether anything it applied needs a redraw- Loading spinners shown during async operations### Phase Status Polling- `maybe_spawn_session_refresh()` spawns a background thread with 2-second cache TTL per task, covering Planning/Running/Review tasks plus Backlog tasks with an active research session+- **Its tmux work is per pass, not per task.** One `list-windows -a` answers `window_exists` for+ every task (`live_window_targets`), and each task's pane is captured **once**, over the control+ connection (`capture_pane_text` β `CaptureSpec::text()`), shared by the dialog scan and the content+ hash. The old shape ran a `list-windows` process and up to two `capture-pane` processes *per+ task*, every refresh, so its cost grew with the board+- `CaptureSpec::text()` is deliberately **not** the popup's spec: no `-e`, so no SGR escapes land in+ the middle of a dialog's wording, which is what the matcher and the hash have always been fed. A+ real-tmux test asserts it is byte-identical to `TmuxOperations::capture_pane`+- `live_window_targets` returns `Option`, and the `None` must not be flattened to an empty set: one+ listing now answers for the whole board, so "tmux could not be asked" read as "no windows" would+ mark every running task `Exited` on a transient hiccup. The per-task check it replaced failed safe+ (`!window_exists(sn).unwrap_or(true)`), and `window_is_gone` keeps that direction- Overlap guard: only one refresh thread runs at a time (`session_refresh_rx.is_some()`)- Thread does all expensive work: plugin TOML loading, artifact file checks, `tmux capture-pane`, copy-back side effects- `apply_session_refresh()` applies results on main thread (non-blocking `try_recv`)diff --git a/Cargo.lock b/Cargo.lockindex 337ee3c..501f08c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4,7 +4,7 @@ version = 4[[package]]name = "agtx"-version = "1.0.2"+version = "1.0.3"dependencies = ["anyhow","chrono",diff --git a/Cargo.toml b/Cargo.tomlindex 873099d..d5e7e01 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "agtx"-version = "1.0.2"+version = "1.0.3"edition = "2021"description = "Terminal-native kanban board for managing coding agents"authors = ["agtx contributors"]diff --git a/src/tmux/control.rs b/src/tmux/control.rsindex 23f0778..3c6581c 100644--- a/src/tmux/control.rs+++ b/src/tmux/control.rs@@ -1,11 +1,10 @@//! 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.+//! a `tmux` process and waits for it, which is what made typing in a task popup+//! lag behind the keys. A control-mode client is one long-lived process that+//! takes commands as lines on stdin, so the same `send-keys` costs a fraction of+//! that, and nothing at all when no reply is waited for.//!//! ```text//! tmux -L agtx -C attach-session -t <session> -f ignore-size,no-output@@ -21,8 +20,15 @@//! 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.+//! stdout as `%output`. The popup gets its content from `capture-pane` β issued+//! as a command on this same connection, see [`ControlClient::query`] β so for+//! *this* client the mirror is pure cost, and suppressing it does not suppress+//! command replies, which are what a query reads.+//!+//! The cost is not the volume β a busy pane pushes far less than it looks β+//! but that this client has no use for the bytes. That distinction matters+//! because `%output` is the only "this pane changed" push tmux offers, and the+//! pane watcher takes it on a second client of its own ([`OutputWatch`]).//! - **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@@ -34,6 +40,7 @@use anyhow::{Context, Result};use std::io::{Read, Write};use std::process::{Child, ChildStdin, Command, Stdio};+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Condvar, Mutex};use std::time::{Duration, Instant};@@ -118,7 +125,15 @@ pub enum Frame {#[derive(Default)]pub struct FrameParser {buf: Vec<u8>,- in_block: bool,+ /// Command id of the block currently open, if any.+ ///+ /// Not a bool, because a block's payload is arbitrary text and a *pane+ /// capture* is the most arbitrary there is: an agent that prints a line+ /// beginning `%end ` would otherwise close the block early and desync+ /// `completed`, which barriers and queries both count on. tmux pairs every+ /// `%end`/`%error` with its `%begin`'s id, so requiring the match costs+ /// nothing and makes the spoof need today's exact command number.+ open_cmd: Option<u64>,}impl FrameParser {@@ -146,17 +161,17 @@ impl FrameParser {// 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;+ self.open_cmd = Some(cmd);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(open) = self.open_cmd {+ if frame_cmd(&line, "%end") == Some(open) {+ self.open_cmd = None;+ return Frame::End { cmd: open };}- if let Some(cmd) = frame_cmd(&line, "%error") {- self.in_block = false;- return Frame::Error { cmd };+ if frame_cmd(&line, "%error") == Some(open) {+ self.open_cmd = None;+ return Frame::Error { cmd: open };}return Frame::Payload(line);}@@ -164,6 +179,24 @@ impl FrameParser {}}+/// `%output %7 some\015bytes` β `Some("%7")`.+///+/// Only the pane id is taken; the payload is dropped without being decoded.+/// `%output` is used as a **signal** that a pane painted, never as content β the+/// pane is still read with `capture-pane`, which is what renders correctly and is+/// byte-verified against the subprocess path.+pub fn output_pane_id(line: &str) -> Option<&str> {+ let rest = line.strip_prefix("%output ")?;+ let id = rest.split(' ').next()?;+ // A pane id is `%` followed by digits. Anything else is a notification we do+ // not understand, and guessing at it would signal the wrong pane.+ if id.len() >= 2 && id.starts_with('%') && id[1..].bytes().all(|b| b.is_ascii_digit()) {+ Some(id)+ } else {+ None+ }+}+/// `%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> {@@ -193,6 +226,49 @@ struct ClientState {/// name the target, not the keys.last_error: Option<String>,errors: u64,+ /// The one in-flight [`ControlClient::query`], if any. Single-slot because+ /// the client is owned by one thread, which is blocked while it waits.+ query: Option<QueryState>,+}++/// A command whose *output* a caller wants, identified by the completion+/// indices its blocks will carry.+///+/// Commands complete in the order they were issued, so `completed` β the same+/// counter [`ControlClient::barrier`] waits on β is enough to tell which block+/// belongs to the query. Nothing has to parse `%begin`'s command id.+#[derive(Debug)]+struct QueryState {+ first: u64,+ last: u64,+ blocks: Vec<Vec<String>>,+ /// First `%error` payload in the range. A query is reported as failed even+ /// when later commands in the same batch succeed.+ failed: Option<String>,+ done: bool,+}++impl ClientState {+ /// Hand a just-closed block to the waiting query, if it belongs to one.+ ///+ /// Called with `completed` already incremented, so it *is* the index of the+ /// block that closed.+ fn record_block(&mut self, payload: Vec<String>, error: Option<String>) {+ let idx = self.completed;+ let Some(query) = self.query.as_mut() else {+ return;+ };+ if query.done || idx < query.first || idx > query.last {+ return;+ }+ if let Some(err) = error {+ query.failed.get_or_insert(err);+ }+ query.blocks.push(payload);+ if idx >= query.last {+ query.done = true;+ }+ }}#[derive(Debug, Default)]@@ -235,6 +311,24 @@ impl ControlClient {/// 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> {+ Self::connect_with(server, session, generation, None)+ }++ /// As [`connect`](Self::connect), but raising `window_events` whenever tmux+ /// reports a window closing.+ ///+ /// Those notifications arrive on a `no-output` client β verified on 3.5a β+ /// so the connection agtx already holds for keystrokes can tell it an agent+ /// exited, instead of the status refresh noticing up to its poll interval+ /// later. It is a flag rather than the window id because the id would have+ /// to be resolved to a task anyway: "some window closed, look again" is the+ /// whole signal, and the refresh already knows how to look.+ pub fn connect_with(+ server: &str,+ session: &str,+ generation: u64,+ window_events: Option<Arc<AtomicBool>>,+ ) -> 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.@@ -265,7 +359,7 @@ impl ControlClient {let reader_shared = Arc::clone(&shared);std::thread::Builder::new().name(format!("agtx-tmux-control-{generation}"))- .spawn(move || read_loop(stdout, reader_shared))+ .spawn(move || read_loop(stdout, reader_shared, window_events)).context("failed to start the control-mode reader thread")?;let mut client = Self {@@ -329,11 +423,98 @@ impl ControlClient {Ok(())}+ /// Run commands and return the **output** of each, block by block.+ ///+ /// The write path is fire-and-forget by design β ordering, not+ /// acknowledgement, is what pane input needs β so this is the one place that+ /// reads a reply back. It exists for the popup's pane capture, which is far+ /// cheaper here than as one `tmux` process per command.+ ///+ /// All commands are written before waiting, so a batch costs one round trip+ /// rather than one per command. On timeout the query slot is cleared and the+ /// blocks collected so far are discarded: a late reply must not be handed to+ /// whoever asks next.+ ///+ /// An `Err` from the write half is **ambiguous** in exactly the way+ /// [`write_command`](Self::write_command) documents, and callers must treat+ /// it the same way.+ pub fn query(&mut self, cmds: &[String], timeout: Duration) -> Result<Vec<Vec<String>>> {+ if cmds.is_empty() {+ return Ok(Vec::new());+ }+ // Indices the replies will carry. Every block for a command issued+ // earlier has a smaller index, so one closing between here and the write+ // below is ignored rather than mistaken for ours.+ let first = self.issued + self.offset + 1;+ let last = first + cmds.len() as u64 - 1;+ {+ let mut st = self+ .shared+ .state+ .lock()+ .map_err(|_| anyhow::anyhow!("control-mode state poisoned"))?;+ if !st.alive {+ anyhow::bail!("tmux control client is gone");+ }+ st.query = Some(QueryState {+ first,+ last,+ blocks: Vec::new(),+ failed: None,+ done: false,+ });+ }+ for cmd in cmds {+ if let Err(e) = self.write_command(cmd) {+ self.clear_query();+ return Err(e);+ }+ }++ let deadline = Instant::now() + timeout;+ let mut st = self+ .shared+ .state+ .lock()+ .map_err(|_| anyhow::anyhow!("control-mode state poisoned"))?;+ loop {+ let done = st.query.as_ref().map(|q| q.done).unwrap_or(true);+ if done || !st.alive {+ break;+ }+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ st.query = None;+ anyhow::bail!("tmux control query timed out after {timeout:?}");+ }+ match self.shared.cv.wait_timeout(st, remaining) {+ Ok((next, _)) => st = next,+ Err(_) => anyhow::bail!("control-mode state poisoned"),+ }+ }+ let Some(query) = st.query.take() else {+ anyhow::bail!("tmux control query was never registered");+ };+ if let Some(err) = query.failed {+ anyhow::bail!("tmux rejected the command: {err}");+ }+ if !query.done {+ anyhow::bail!("tmux control client exited during the query");+ }+ Ok(query.blocks)+ }++ fn clear_query(&mut self) {+ if let Ok(mut st) = self.shared.state.lock() {+ st.query = None;+ }+ }+/// 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.+ /// here. Costs one round trip, not one per command.pub fn barrier(&mut self, timeout: Duration) -> bool {let want = self.issued + self.offset;let deadline = Instant::now() + timeout;@@ -400,7 +581,128 @@ impl ControlClient {}}-fn read_loop(mut stdout: std::process::ChildStdout, shared: Arc<Shared>) {+/// A control client attached **without** `no-output`, whose only job is to say+/// which panes painted.+///+/// Separate from [`ControlClient`] on purpose, and the separation is forced:+/// `no-output` is fixed at attach time β it survives every `refresh-client`+/// form on 3.5a β so push cannot be switched on for the input connection when a+/// popup opens. A second client also means the mirrored bytes never touch the+/// path a keystroke takes, and that nothing is mirrored at all while no popup is+/// open, because this is connected only for as long as one is.+pub struct OutputWatch {+ child: Child,+ alive: Arc<AtomicBool>,+}++impl OutputWatch {+ /// Attach and call `on_output` with a pane id every time that pane paints.+ ///+ /// The callback runs on the reader thread and must be cheap: a busy pane+ /// produces ~56 frames a second, and every pane in the session is mirrored+ /// here, not just the one being watched.+ pub fn connect(+ server: &str,+ session: &str,+ on_output: impl Fn(&str) + Send + 'static,+ ) -> Result<Self> {+ let mut child = Command::new("tmux")+ .args(["-L", server, "-C", "attach-session", "-t", session])+ // `ignore-size` for the same reason as the input client; `no-output`+ // deliberately absent, since the output is the entire point.+ .args(["-f", "ignore-size"])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .context("failed to start the tmux output-watch client")?;+ let stdout = child+ .stdout+ .take()+ .context("tmux output-watch client has no stdout")?;+ let alive = Arc::new(AtomicBool::new(true));+ let reader_alive = Arc::clone(&alive);+ std::thread::Builder::new()+ .name("agtx-tmux-output".to_string())+ .spawn(move || {+ let mut parser = FrameParser::new();+ let mut buf = [0u8; 8192];+ let mut stdout = stdout;+ 'read: 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() {+ // Only notifications: a `%output`-shaped line *inside* a+ // command's reply is that command's output, not a pane+ // painting. The parser already draws that line.+ if let Frame::Notify(line) = frame {+ if let Some(id) = output_pane_id(&line) {+ on_output(id);+ } else if line.starts_with("%exit") {+ // Labelled: leaving only the frame loop would+ // keep reading a connection tmux has just said+ // it is closing, and leave `alive()` true until+ // the pipe happened to close.+ break 'read;+ }+ }+ }+ }+ reader_alive.store(false, Ordering::Relaxed);+ })+ .context("failed to start the output-watch reader thread")?;+ Ok(Self { child, alive })+ }++ pub fn alive(&self) -> bool {+ self.alive.load(Ordering::Relaxed)+ }+}++impl Drop for OutputWatch {+ fn drop(&mut self) {+ // Closing stdin asks tmux to exit; the kill is for a client that ignores+ // it. Left running, it would mirror the whole session's output forever.+ drop(self.child.stdin.take());+ let deadline = Instant::now() + Duration::from_millis(300);+ loop {+ match self.child.try_wait() {+ Ok(Some(_)) => return,+ Ok(None) if Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(5));+ }+ _ => break,+ }+ }+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++/// Does this notification mean a window went away?+///+/// tmux emits `%window-close` for a window still linked elsewhere and+/// `%unlinked-window-close` for one that is gone entirely; a task's window is+/// the second, but both mean "the set of windows changed, look again".+pub fn is_window_close(line: &str) -> bool {+ for tag in ["%window-close", "%unlinked-window-close"] {+ if let Some(rest) = line.strip_prefix(tag) {+ if rest.is_empty() || rest.starts_with(' ') {+ return true;+ }+ }+ }+ false+}++fn read_loop(+ mut stdout: std::process::ChildStdout,+ shared: Arc<Shared>,+ window_events: Option<Arc<AtomicBool>>,+) {let mut parser = FrameParser::new();let mut buf = [0u8; 8192];let mut block_payload: Vec<String> = Vec::new();@@ -414,29 +716,37 @@ fn read_loop(mut stdout: std::process::ChildStdout, shared: Arc<Shared>) {match frame {Frame::Begin { .. } => block_payload.clear(),Frame::End { .. } => {- let ready = block_payload.iter().any(|l| l == READY_SENTINEL);- shared.signal(|st| {+ // Moved, not copied: a capture block is the whole pane, and+ // this runs on every command the broker issues.+ let payload = std::mem::take(&mut block_payload);+ let ready = payload.iter().any(|l| l == READY_SENTINEL);+ shared.signal(move |st| {st.completed += 1;if ready {st.ready = true;}+ st.record_block(payload, None);});- block_payload.clear();}Frame::Error { cmd } => {- let msg = block_payload.join("; ");+ let payload = std::mem::take(&mut block_payload);+ let msg = payload.join("; ");tracing::debug!(cmd, error = %msg, "tmux control command failed");- shared.signal(|st| {+ shared.signal(move |st| {st.completed += 1;st.errors += 1;- st.last_error = Some(msg);+ st.last_error = Some(msg.clone());+ st.record_block(Vec::new(), 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);+ } else if is_window_close(&line) {+ if let Some(flag) = window_events.as_ref() {+ flag.store(true, Ordering::Relaxed);+ }}}}diff --git a/src/tmux/control_tests.rs b/src/tmux/control_tests.rsindex ca9eb1b..7b94f57 100644--- a/src/tmux/control_tests.rs+++ b/src/tmux/control_tests.rs@@ -168,6 +168,105 @@ fn a_payload_line_starting_with_percent_is_payload() {);}+#[test]+fn a_window_closing_is_recognised_in_either_form() {+ // tmux emits `%window-close` for a window still linked elsewhere and+ // `%unlinked-window-close` for one that is gone; a task's window is the+ // second, but both mean "the set of windows changed, look again".+ assert!(is_window_close("%unlinked-window-close @1"));+ assert!(is_window_close("%window-close @7"));+ assert!(is_window_close("%window-close"));+ // Not a window closing. `%window-closed` does not exist today, but matching+ // it would age out every task's status on a notification we misread.+ for line in [+ "%window-add @2",+ "%window-closed @2",+ "%unlinked-window-add @2",+ "%exit",+ "%output %1 data",+ ] {+ assert!(!is_window_close(line), "{line:?} is not a window closing");+ }+}++#[test]+fn an_output_notification_yields_its_pane_id() {+ assert_eq!(output_pane_id("%output %7 hello"), Some("%7"));+ assert_eq!(output_pane_id("%output %12 "), Some("%12"));+ // The payload is arbitrary bytes, escaped by tmux; only the id is taken.+ assert_eq!(+ output_pane_id("%output %3 \\033[31mred\\033[0m %output %9 not-an-id"),+ Some("%3")+ );+}++#[test]+fn a_notification_that_is_not_an_output_yields_no_pane_id() {+ // Guessing an id from a notification we do not understand would signal the+ // wrong pane, which reads as "some other task painted" and captures for it.+ for line in [+ "%exit",+ "%window-add @2",+ "%output",+ "%output notapane data",+ "%output % data",+ "%output %x1 data",+ "%outputs %1 data",+ ] {+ assert_eq!(+ output_pane_id(line),+ None,+ "{line:?} must not parse as a pane id"+ );+ }+}++#[test]+fn a_payload_line_that_looks_like_an_output_notification_is_payload() {+ // A capture of a pane that is itself showing control-mode output. Inside a+ // block it is that command's reply, not a pane painting β position decides,+ // as it does for every other tag.+ assert_eq!(+ frames(&["%begin 1 4 0\n%output %9 painted\n%end 1 4 0\n"]),+ vec![+ Frame::Begin { cmd: 4 },+ Frame::Payload("%output %9 painted".to_string()),+ Frame::End { cmd: 4 },+ ]+ );+}++#[test]+fn a_payload_line_that_looks_like_an_end_tag_does_not_close_the_block() {+ // A block's payload is now a whole pane capture, so its lines are whatever+ // an agent chose to paint β `%end 1 7 0` included. Closing on the tag alone+ // would end the block early, hand the caller half a capture, and leave+ // `completed` permanently ahead of the commands that were actually run,+ // which every barrier and query counts on. tmux pairs each `%end` with its+ // `%begin`'s id, so the id is what decides.+ assert_eq!(+ frames(&["%begin 1 4 0\n%end 1 7 0\nreal content\n%end 1 4 0\n"]),+ vec![+ Frame::Begin { cmd: 4 },+ Frame::Payload("%end 1 7 0".to_string()),+ Frame::Payload("real content".to_string()),+ Frame::End { cmd: 4 },+ ]+ );+}++#[test]+fn a_payload_line_that_looks_like_an_error_tag_does_not_fail_the_block() {+ assert_eq!(+ frames(&["%begin 1 4 0\n%error 1 9 0\n%end 1 4 0\n"]),+ vec![+ Frame::Begin { cmd: 4 },+ Frame::Payload("%error 1 9 0".to_string()),+ Frame::End { cmd: 4 },+ ]+ );+}+#[test]fn a_malformed_begin_still_frames_the_block() {// Losing the command number costs a log field. Losing the framing woulddiff --git a/src/tmux/input.rs b/src/tmux/input.rsindex 6cf1829..3f82743 100644--- a/src/tmux/input.rs+++ b/src/tmux/input.rs@@ -11,8 +11,8 @@//! βΌ//! 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)+//! βββΊ control-mode client (persistent process, cheap per command)+//! βββΊ subprocess fallback (`tmux send-keys`, one process per command)//! ```//!//! The broker is the **single ordering authority** for popup input. Nothing else@@ -33,6 +33,7 @@ use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use super::control::{tmux_quote, ControlClient};+use super::operations::{CaptureSpec, PaneSnapshot, PANE_METRICS_FORMAT};use super::TmuxOperations;/// One request to put something into a pane.@@ -56,6 +57,21 @@ pub enum PaneInput {/// 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> },+ /// Read a pane's content and geometry back over the same connection.+ ///+ /// A *read* in an input queue looks out of place until you ask what it is+ /// ordered against: the capture must show the keys typed before it, and the+ /// broker is the only thing that knows whether those have been flushed. It+ /// is also far cheaper here than as a pair of `tmux` processes, which is+ /// where the popup's echo lag came from.+ ///+ /// The reply is `None` when there is no control connection β the caller+ /// then falls back to the subprocess capture, which is where it started.+ Capture {+ target: String,+ spec: CaptureSpec,+ ack: std::sync::mpsc::Sender<Option<PaneSnapshot>>,+ },/// Flush, then stop the broker.Shutdown,}@@ -66,7 +82,8 @@ impl PaneInput {match self {PaneInput::Text { target, .. }| PaneInput::Key { target, .. }- | PaneInput::Paste { target, .. } => Some(target),+ | PaneInput::Paste { target, .. }+ | PaneInput::Capture { target, .. } => Some(target),PaneInput::Flush | PaneInput::Barrier { .. } | PaneInput::Shutdown => None,}}@@ -82,6 +99,14 @@ impl PartialEq for PaneInput {(Self::Paste { target: a, text: b }, Self::Paste { target: c, text: d }) => {a == c && b == d}+ (+ Self::Capture {+ target: a, spec: b, ..+ },+ Self::Capture {+ target: c, spec: d, ..+ },+ ) => a == c && b == d,(Self::Flush, Self::Flush)| (Self::Barrier { .. }, Self::Barrier { .. })| (Self::Shutdown, Self::Shutdown) => true,@@ -153,6 +178,16 @@ pub trait PaneInputSink: Send + Sync {let _ = self.flush();}+ /// Capture a pane over the input connection, if there is one.+ ///+ /// `None` means "not available here" β no control connection, a full queue,+ /// a wedged broker β and every caller must have a subprocess capture to fall+ /// back to. It is deliberately not an error type: a missed capture costs one+ /// frame at the old speed, which is not worth a code path of its own.+ fn capture(&self, _target: &str, _spec: CaptureSpec) -> Option<PaneSnapshot> {+ None+ }+/// Point future control-mode connections at a different session.////// agtx switches project in place, and a session that no longer exists is@@ -174,6 +209,13 @@ pub(crate) trait PaneBackend: Send {fn barrier(&mut self) -> bool {true}+ /// Read a pane back. Only the control backend implements this: on the+ /// subprocess path the caller's own `capture-pane` is the same two processes+ /// for the same cost, so routing it through the broker would buy nothing and+ /// block the input thread behind it.+ fn capture(&mut self, _target: &str, _spec: CaptureSpec) -> Result<PaneSnapshot> {+ anyhow::bail!("capture is not supported on the {} backend", self.label())+ }fn healthy(&self) -> bool {true}@@ -243,10 +285,25 @@ impl Drop for ControlBackend {}/// 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.+/// well above a healthy round trip: reaching it means tmux is wedged, and+/// blocking the broker further would not help.const BARRIER_TIMEOUT: Duration = Duration::from_millis(250);+/// How long a pane capture waits for its reply.+///+/// Not a budget but a wedge detector: a healthy round trip is far below it. It+/// is generous because it is paid on a background refresh thread, not on the+/// input path, and because giving up costs one frame at the fallback's speed,+/// not a dropped keystroke.+const CAPTURE_TIMEOUT: Duration = Duration::from_millis(250);++/// How long the *caller* waits for a capture, queue time included.+///+/// Longer than [`CAPTURE_TIMEOUT`] on purpose: that one bounds the tmux round+/// trip, this one also covers whatever is queued ahead of the request. Same+/// distinction as [`FLUSH_SYNC_TIMEOUT`] against [`BARRIER_TIMEOUT`].+const CAPTURE_ACK_TIMEOUT: Duration = Duration::from_millis(750);+impl PaneBackend for ControlBackend {fn text(&mut self, target: &str, text: &str) -> Result<()> {let cmd = format!(@@ -277,6 +334,47 @@ impl PaneBackend for ControlBackend {}Ok(())}+ fn capture(&mut self, target: &str, spec: CaptureSpec) -> Result<PaneSnapshot> {+ // Both commands in one round trip: they are written back to back and only+ // the last reply is waited for. Fetching them together is also what keeps+ // them consistent β the cursor row is an index into the content.+ let mut cmds = vec![format!(+ "capture-pane -t {}{} -p -S -{}",+ tmux_quote(target),+ if spec.escapes { " -e" } else { "" },+ spec.history.max(0)+ )];+ if spec.metrics {+ // Single quotes, not `tmux_quote`: tmux performs no replacements+ // inside them, so `#{cursor_x}` reaches display-message intact+ // instead of being escaped to a literal `\#{cursor_x}`.+ cmds.push(format!(+ "display -p -t {} '{}'",+ tmux_quote(target),+ PANE_METRICS_FORMAT+ ));+ }+ let mut blocks = self.client()?.query(&cmds, CAPTURE_TIMEOUT)?;+ if blocks.len() != cmds.len() {+ anyhow::bail!("expected {} reply blocks, got {}", cmds.len(), blocks.len());+ }+ let metrics = if spec.metrics {+ blocks+ .pop()+ .and_then(|lines| lines.first().and_then(|l| super::parse_pane_metrics(l)))+ } else {+ None+ };+ let lines = blocks.pop().unwrap_or_default();+ // Rebuilt exactly as `capture-pane`'s stdout: one trailing newline per+ // row, so a caller cannot tell the two backends apart.+ let mut content = Vec::new();+ for line in lines {+ content.extend_from_slice(line.as_bytes());+ content.push(b'\n');+ }+ Ok(PaneSnapshot { content, metrics })+ }fn barrier(&mut self) -> bool {if let Some(client) = self.client.as_mut() {let completed = client.barrier(BARRIER_TIMEOUT);@@ -301,6 +399,8 @@ impl PaneBackend for ControlBackend {pub(crate) enum FlushReason {/// The batching window elapsed.Window,+ /// The queue ran dry, so the buffered text had nothing left to join.+ Idle,/// A non-text request came next.BeforeKey,/// The next text is for a different pane.@@ -313,13 +413,15 @@ pub(crate) enum FlushReason {Shutdown,}-/// How long adjacent characters may wait to be combined.+/// How long adjacent characters may wait to be combined **during a burst**.///-/// 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.+/// It is not paid by ordinary typing: text is flushed as soon as the queue is+/// empty, and between two keystrokes a human makes it always is. That is the+/// difference between taxing every character and charging only while characters+/// are genuinely backed up.+///+/// So this bounds how long a *backlog* may keep growing before it goes out, and+/// raising it trades echo latency for fewer commands only in that case.pub const DEFAULT_BATCH_WINDOW: Duration = Duration::from_millis(2);/// Byte cap on one coalesced `send-keys`. Well under any command-length limit,@@ -339,10 +441,9 @@ const RECONNECT_MAX: Duration = Duration::from_secs(5);////// **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+/// on the subprocess backend every queued command is its own 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.+/// not kept.////// 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@@ -368,6 +469,10 @@ pub struct InputConfig {pub control_mode: bool,pub batch_window: Duration,pub capacity: usize,+ /// Raised by the control connection when tmux reports a window closing, so+ /// the status refresh can look immediately instead of on its next tick.+ /// `None` disables the reporting.+ pub window_events: Option<Arc<AtomicBool>>,}impl InputConfig {@@ -378,6 +483,7 @@ impl InputConfig {control_mode: true,batch_window: DEFAULT_BATCH_WINDOW,capacity: DEFAULT_QUEUE_CAPACITY,+ window_events: None,}}}@@ -465,6 +571,20 @@ impl PaneInputSink for BrokerSink {}}+ fn capture(&self, target: &str, spec: CaptureSpec) -> Option<PaneSnapshot> {+ let (ack, done) = std::sync::mpsc::channel();+ self.send(PaneInput::Capture {+ target: target.to_string(),+ spec,+ ack,+ })+ .ok()?;+ // Bounded by the same reasoning as the broker's own timeout, plus the+ // queue ahead of it: this runs on the popup's refresh thread, so waiting+ // costs a frame and never a keystroke.+ done.recv_timeout(CAPTURE_ACK_TIMEOUT).ok().flatten()+ }+fn flush_sync(&self) -> std::result::Result<(), InputError> {let (ack, done) = std::sync::mpsc::channel();self.send(PaneInput::Barrier { ack })?;@@ -511,12 +631,14 @@ pub fn spawn(config: InputConfig, ops: Arc<dyn TmuxOperations>) -> Arc<BrokerSinlet server = config.server.clone();let session = Arc::clone(&session);let ops = Arc::clone(&ops);+ let window_events = config.window_events.clone();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)?;+ let client =+ ControlClient::connect_with(&server, &attach, generation, window_events.clone())?;Ok(Box::new(ControlBackend::new(client, Arc::clone(&ops))) as Box<dyn PaneBackend>)}))} else {@@ -617,6 +739,15 @@ impl Broker {self.dispatch(|b| b.paste(&target, &text), "paste");tracing::debug!(bytes = len, "pane paste delivered");}+ PaneInput::Capture { target, spec, ack } => {+ // Ordered against the keys, not merely concurrent with them:+ // a capture that overtook buffered text would render a frame+ // missing characters the user has already typed, which is+ // the exact illusion this whole path exists to remove.+ self.flush(FlushReason::BeforeKey);+ let snapshot = self.capture(&target, spec);+ let _ = ack.send(snapshot);+ }PaneInput::Flush => self.flush(FlushReason::Explicit),PaneInput::Barrier { ack } => {self.flush(FlushReason::Explicit);@@ -655,6 +786,15 @@ impl Broker {self.deadline = Some(Instant::now() + self.batch_window);}}+ // Nothing else is queued, so there is nothing left to coalesce *with*:+ // waiting out the window would add its full length to the echo latency+ // of every keystroke a human types, since at typing speed the broker is+ // always idle between characters. Batching is for bursts β a paste+ // arriving as keystrokes, a held key β and a burst is exactly the case+ // where this counter is non-zero.+ if self.depth.load(Ordering::Relaxed) == 0 {+ self.flush(FlushReason::Idle);+ }}fn flush(&mut self, reason: FlushReason) {@@ -722,6 +862,43 @@ impl Broker {}}+ /// Capture a pane on the control connection, or `None` if there isn't one.+ ///+ /// Never falls back to the subprocess itself: the caller already owns that+ /// path, and doing it here would block the broker β and therefore the next+ /// keystroke β behind the `tmux` process startup it would cost.+ fn capture(&mut self, target: &str, spec: CaptureSpec) -> Option<PaneSnapshot> {+ self.maybe_connect();+ let started = Instant::now();+ let outcome = match self.control.as_mut() {+ Some(control) if control.healthy() => control.capture(target, spec),+ Some(_) => Err(anyhow::anyhow!("connection closed")),+ None => return None,+ };+ match outcome {+ Ok(snapshot) => {+ tracing::trace!(+ bytes = snapshot.content.len(),+ micros = started.elapsed().as_micros() as u64,+ "pane captured over the control connection"+ );+ Some(snapshot)+ }+ Err(e) => {+ // A read that failed is not the ambiguous write `dispatch`+ // guards against, so a healthy connection is kept: dropping it+ // over a slow capture would demote every subsequent *keystroke*+ // to the subprocess path to fix a read that is far cheaper.+ if self.control.as_ref().map(|c| c.healthy()) != Some(true) {+ self.drop_control(&format!("capture failed: {e}"));+ } else {+ tracing::debug!(error = %e, "pane capture failed; using the subprocess path");+ }+ None+ }+ }+ }+fn drop_control(&mut self, reason: &str) {if self.control.take().is_some() {tracing::info!(diff --git a/src/tmux/input_tests.rs b/src/tmux/input_tests.rsindex 9fe6a90..3d5efa6 100644--- a/src/tmux/input_tests.rs+++ b/src/tmux/input_tests.rs@@ -14,6 +14,7 @@ enum Op {Key(String, String),Paste(String, String),Barrier,+ Capture(String),OutsideTmuxOperation,}@@ -38,6 +39,9 @@ struct RecordingBackend {failing: bool,/// Report itself as dead, as a `%exit`ed connection does.dead: Arc<std::sync::atomic::AtomicBool>,+ /// What a capture returns. `None` leaves the trait default, which is the+ /// subprocess backend's real behaviour: it does not support captures.+ capture: Option<PaneSnapshot>,}impl RecordingBackend {@@ -47,6 +51,7 @@ impl RecordingBackend {recorder,failing: false,dead: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ capture: None,}}}@@ -84,6 +89,14 @@ impl PaneBackend for RecordingBackend {self.recorder.push(Op::Barrier);true}+ fn capture(&mut self, target: &str, _spec: CaptureSpec) -> Result<PaneSnapshot> {+ self.recorder+ .push(Op::Capture(format!("{}:{target}", self.label)));+ match self.capture.clone() {+ Some(snapshot) => Ok(snapshot),+ None => anyhow::bail!("capture is not supported on the {} backend", self.label),+ }+ }fn healthy(&self) -> bool {!self.dead.load(std::sync::atomic::Ordering::Relaxed)}@@ -137,6 +150,53 @@ fn harness(batch_window: Duration) -> Harness {harness_with(batch_window, Recorder::default(), None)}+/// A harness whose queue is **already full of `inputs`** when the broker starts.+///+/// Coalescing is opportunistic by design: buffered text is flushed as soon as+/// the queue runs dry, because between two keystrokes a human types it always+/// does and waiting out the batch window there would tax every character. So a+/// test that sends three characters to a running broker is asserting that it+/// lost the race to the broker's own drain, which is timing, not behaviour.+/// Queueing first makes the backlog real and the outcome deterministic.+fn harness_queued(batch_window: Duration, inputs: Vec<PaneInput>) -> Harness {+ let (tx, rx) = sync_channel(64);+ let depth = Arc::new(AtomicUsize::new(0));+ for input in inputs {+ depth.fetch_add(1, Ordering::Relaxed);+ tx.send(input).expect("queue has room");+ }+ let recorder = Recorder::default();+ let broker = Broker {+ rx,+ depth: Arc::clone(&depth),+ batch_window,+ fallback: Box::new(RecordingBackend::new("sub", recorder.clone())),+ control: None,+ control_factory: None,+ 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,+ }+}++fn text_input(target: &str, text: &str) -> PaneInput {+ PaneInput::Text {+ target: target.to_string(),+ text: text.to_string(),+ }+}+/// 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(@@ -172,11 +232,38 @@ fn harness_with(#[test]fn adjacent_text_for_one_target_is_coalesced() {+ let h = harness_queued(+ NEVER,+ vec![+ text_input("s:w", "a"),+ text_input("s:w", "b"),+ text_input("s:w", "c"),+ ],+ );+ assert_eq!(h.finish(), vec![Op::Text("sub:s:w".into(), "abc".into())]);+}++#[test]+fn text_is_not_held_when_nothing_else_is_queued() {+ // The other half of the policy, and the one a user feels: with an idle+ // queue the character goes out now, not when the batch window expires.+ // NEVER as the window is what makes this an assertion rather than a race β+ // under a timer-only broker nothing could arrive before the shutdown flush.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())]);+ let deadline = Instant::now() + Duration::from_secs(2);+ while h.recorder.ops().is_empty() {+ assert!(+ Instant::now() < deadline,+ "buffered text was never flushed without a key, a flush or a shutdown"+ );+ std::thread::sleep(Duration::from_millis(1));+ }+ assert_eq!(+ h.recorder.ops(),+ vec![Op::Text("sub:s:w".into(), "a".into())]+ );+ h.finish();}#[test]@@ -282,8 +369,8 @@ 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.+ // with a queue of keys still in flight it reported failure, 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));@@ -328,18 +415,27 @@ fn an_acknowledged_flush_waits_out_a_slow_drain() {}#[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");+fn the_batching_window_bounds_how_long_a_backlog_is_held() {+ // The window is the burst case's bound: with a backlog queued and a window+ // that expires, the buffer must go out on the timer even though no key,+ // flush or shutdown followed it.+ let h = harness_queued(+ Duration::from_millis(1),+ vec![text_input("s:w", "a"), text_input("s:w", "b")],+ );+ let deadline = Instant::now() + Duration::from_secs(2);+ while h.recorder.ops().is_empty() {+ assert!(+ Instant::now() < deadline,+ "the batching window never expired"+ );+ std::thread::sleep(Duration::from_millis(1));+ }assert_eq!(- h.finish(),- vec![- Op::Text("sub:s:w".into(), "a".into()),- Op::Text("sub:s:w".into(), "b".into()),- ]+ h.recorder.ops(),+ vec![Op::Text("sub:s:w".into(), "ab".into())]);+ h.finish();}#[test]@@ -387,10 +483,13 @@ fn dropping_every_sender_still_delivers_the_last_word() {#[test]fn unicode_survives_coalescing() {- let h = harness(NEVER);- for ch in "νκ΅μ΄π".chars() {- h.text("s:w", &ch.to_string());- }+ let h = harness_queued(+ NEVER,+ "νκ΅μ΄π"+ .chars()+ .map(|ch| text_input("s:w", &ch.to_string()))+ .collect(),+ );assert_eq!(h.finish(),vec![Op::Text("sub:s:w".into(), "νκ΅μ΄π".into())]@@ -446,6 +545,116 @@ fn a_paste_flushes_first_and_stays_atomic() {);}+// --- pane capture over the input connection ---++fn canned_snapshot() -> PaneSnapshot {+ PaneSnapshot {+ content: b"hello\n".to_vec(),+ metrics: Some(super::super::PaneMetrics {+ cursor_x: 1,+ cursor_y: 2,+ pane_height: 34,+ history_size: 0,+ }),+ }+}++fn capture(h: &Harness, target: &str) -> Option<PaneSnapshot> {+ let (ack, done) = std::sync::mpsc::channel();+ h.send(PaneInput::Capture {+ target: target.to_string(),+ spec: CaptureSpec::popup(500),+ ack,+ });+ done.recv_timeout(Duration::from_secs(2))+ .expect("the broker answered the capture")+}++#[test]+fn a_capture_is_served_by_the_control_connection() {+ let recorder = Recorder::default();+ let rec = recorder.clone();+ let factory: ControlFactory = Box::new(move |_| {+ let mut backend = RecordingBackend::new("ctl", rec.clone());+ backend.capture = Some(canned_snapshot());+ Ok(Box::new(backend))+ });+ let h = harness_with(NEVER, recorder, Some(factory));+ assert_eq!(capture(&h, "s:w"), Some(canned_snapshot()));+ assert_eq!(h.finish(), vec![Op::Capture("ctl:s:w".into())]);+}++#[test]+fn a_capture_shows_the_keys_typed_before_it() {+ // The reason a read belongs in an input queue at all. Buffered text must+ // reach the pane *before* the capture reads it back, or the popup renders a+ // frame that is missing characters the user has already typed β which is+ // precisely the staleness this path exists to remove.+ let recorder = Recorder::default();+ let rec = recorder.clone();+ let factory: ControlFactory = Box::new(move |_| {+ let mut backend = RecordingBackend::new("ctl", rec.clone());+ backend.capture = Some(canned_snapshot());+ Ok(Box::new(backend))+ });+ let h = harness_with(NEVER, recorder, Some(factory));+ h.text("s:w", "typed");+ assert!(capture(&h, "s:w").is_some());+ assert_eq!(+ h.finish(),+ vec![+ Op::Text("ctl:s:w".into(), "typed".into()),+ Op::Capture("ctl:s:w".into()),+ ]+ );+}++#[test]+fn a_capture_without_a_control_connection_is_declined_not_run_on_the_fallback() {+ // The subprocess path costs the caller the same two processes either way,+ // and running them here would block the next keystroke behind that process+ // startup. So the broker says no and the caller captures itself.+ let h = harness(NEVER);+ assert_eq!(capture(&h, "s:w"), None);+ assert_eq!(+ h.finish(),+ vec![],+ "nothing may reach the subprocess backend"+ );+}++#[test]+fn a_failed_capture_keeps_a_healthy_control_connection() {+ // A read that fails is not the ambiguous *write* the broker tears the+ // connection down for. Demoting every later keystroke to the subprocess path+ // over one failed read would trade the fix for the bug.+ let recorder = Recorder::default();+ let rec = recorder.clone();+ let connects = Arc::new(AtomicUsize::new(0));+ let seen = Arc::clone(&connects);+ let factory: ControlFactory = Box::new(move |_| {+ seen.fetch_add(1, Ordering::Relaxed);+ // `capture: None` makes the backend decline, as a query timeout does.+ Ok(Box::new(RecordingBackend::new("ctl", rec.clone())))+ });+ let h = harness_with(NEVER, recorder, Some(factory));+ assert_eq!(capture(&h, "s:w"), None);+ h.key("s:w", "Enter");+ assert_eq!(+ h.finish(),+ vec![+ Op::Capture("ctl:s:w".into()),+ Op::Key("ctl:s:w".into(), "Enter".into()),+ ],+ "the key must still go out on the control backend"+ );+ assert_eq!(+ connects.load(Ordering::Relaxed),+ 1,+ "the connection was torn down and rebuilt over a failed read"+ );+}+// --- backend selection, failure and reconnect ---#[test]@@ -602,8 +811,8 @@ fn changing_project_repoints_the_next_connection() {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.+ // and panicking on the next increment β found only under real load, never+ // by a 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 {diff --git a/src/tmux/mod.rs b/src/tmux/mod.rsindex bb650b8..33b5e95 100644--- a/src/tmux/mod.rs+++ b/src/tmux/mod.rs@@ -2,7 +2,9 @@ pub mod control;pub mod input;mod operations;-pub use control::{tmux_quote, ControlClient, Frame, FrameParser};+pub use control::{+ is_window_close, output_pane_id, tmux_quote, ControlClient, Frame, FrameParser, OutputWatch,+};pub use input::{InputConfig, InputError, PaneInput, PaneInputSink, DEFAULT_BATCH_WINDOW, DEFAULT_QUEUE_CAPACITY,};diff --git a/src/tmux/operations.rs b/src/tmux/operations.rsindex ddbd587..846361b 100644--- a/src/tmux/operations.rs+++ b/src/tmux/operations.rs@@ -30,6 +30,18 @@ pub trait TmuxOperations: Send + Sync {/// Check if a window existsfn window_exists(&self, target: &str) -> Result<bool>;+ /// This window's tmux pane id (`%7`), for matching `%output` notifications.+ fn pane_id(&self, target: &str) -> Option<String>;++ /// Every window on the server as `session:window`.+ ///+ /// One call answers [`window_exists`](Self::window_exists) for every task on+ /// the board. The per-task form is still the right shape for one-off checks;+ /// this exists because the status refresh asks about every task at once, on a+ /// timer, and N processes for one listing is the difference that shows up in+ /// tmux's CPU as a board grows.+ fn list_window_targets(&self) -> Result<Vec<String>>;+/// Send keys to a window (with Enter at the end).////// Like [`send_key`](Self::send_key), this goes through@@ -67,7 +79,7 @@ pub trait TmuxOperations: Send + Sync {/// 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,+ /// One `display -p` for all four: the popup refresh runs this often,/// so a second process to ask about scrollback would cost more than the/// answer is worth.fn pane_metrics(&self, target: &str) -> Option<PaneMetrics>;@@ -103,6 +115,81 @@ pub struct PaneMetrics {pub history_size: usize,}+/// The `display -p` format that yields a [`PaneMetrics`], in field order.+///+/// One constant because two paths send it β the subprocess client and the+/// control connection β and a field added to one spelling but not the other+/// would silently misparse into the wrong struct fields rather than fail.+///+/// Verified against tmux 3.5a: `-t` is honoured for the expansion, so this+/// reports the *target* pane and not the attached client's active one, which is+/// what makes it usable from a control client attached elsewhere.+pub const PANE_METRICS_FORMAT: &str = "#{cursor_x} #{cursor_y} #{pane_height} #{history_size}";++/// Parse what [`PANE_METRICS_FORMAT`] produces. Anything unexpected is `None`:+/// a half-parsed pane geometry would mistrim the popup's content.+pub fn parse_pane_metrics(line: &str) -> Option<PaneMetrics> {+ let parts: Vec<&str> = line.split_whitespace().collect();+ if parts.len() != 4 {+ return None;+ }+ 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()?,+ })+}++/// What a capture should ask tmux for.+///+/// The popup and the status refresh want different things from the same command,+/// and the difference is not cosmetic: `-e` embeds SGR escapes, which is what+/// the popup renders from and what a *text scan* β dialog matching, content+/// hashing β must not have to parse around.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct CaptureSpec {+ /// Scrollback lines (`-S -<n>`). Zero captures only the visible pane.+ pub history: i32,+ /// Include SGR escapes (`-e`).+ pub escapes: bool,+ /// Also fetch cursor and geometry. A second tmux command, so only the popup+ /// β which needs the cursor row to trim β pays for it.+ pub metrics: bool,+}++impl CaptureSpec {+ /// What the popup renders: scrollback, colour, and the geometry to trim by.+ pub fn popup(history: i32) -> Self {+ Self {+ history,+ escapes: true,+ metrics: true,+ }+ }++ /// What a text scan needs: the visible pane, no escapes, no geometry.+ /// Matches `TmuxOperations::capture_pane` byte for byte.+ pub fn text() -> Self {+ Self {+ history: 0,+ escapes: false,+ metrics: false,+ }+ }+}++/// One pane capture: its content and the geometry needed to trim it.+///+/// The two are fetched together because they are only consistent together β the+/// cursor row is an index *into* the content, so pairing a capture with metrics+/// taken a frame later can trim off a line the user just typed.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PaneSnapshot {+ pub content: Vec<u8>,+ pub metrics: Option<PaneMetrics>,+}+impl PaneMetrics {/// Where the cursor is, for rendering it in the popup.pub fn cursor(&self) -> (usize, usize, usize) {@@ -212,6 +299,35 @@ impl TmuxOperations for RealTmuxOps {Ok(())}+ fn pane_id(&self, target: &str) -> Option<String> {+ let out = std::process::Command::new("tmux")+ .args(["-L", super::AGENT_SERVER])+ .args(["display", "-p", "-t", target, "#{pane_id}"])+ .output()+ .ok()?;+ if !out.status.success() {+ return None;+ }+ let id = String::from_utf8_lossy(&out.stdout).trim().to_string();+ (!id.is_empty()).then_some(id)+ }++ fn list_window_targets(&self) -> Result<Vec<String>> {+ let output = std::process::Command::new("tmux")+ .args(["-L", super::AGENT_SERVER])+ .args(["list-windows", "-a", "-F", "#{session_name}:#{window_name}"])+ .output()?;+ if !output.status.success() {+ // No server at all is "no windows", not an error: it is the normal+ // state before the first task is started.+ return Ok(Vec::new());+ }+ Ok(String::from_utf8_lossy(&output.stdout)+ .lines()+ .map(str::to_string)+ .collect())+ }+fn window_exists(&self, target: &str) -> Result<bool> {let output = std::process::Command::new("tmux").args(["-L", super::AGENT_SERVER])@@ -291,29 +407,14 @@ impl TmuxOperations for RealTmuxOps {fn pane_metrics(&self, target: &str) -> Option<PaneMetrics> {let output = std::process::Command::new("tmux").args(["-L", super::AGENT_SERVER])- .args([- "display",- "-p",- "-t",- target,- "#{cursor_x} #{cursor_y} #{pane_height} #{history_size}",- ])+ .args(["display", "-p", "-t", target, PANE_METRICS_FORMAT]).output().ok()?;- if output.status.success() {- let output_str = String::from_utf8_lossy(&output.stdout);- 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()?,- });- }+ if !output.status.success() {+ return None;}- None+ parse_pane_metrics(&String::from_utf8_lossy(&output.stdout))}fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()> {diff --git a/src/tui/app.rs b/src/tui/app.rsindex f2e711e..2e03d9c 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -1,6 +1,6 @@use anyhow::Result;use crossterm::{- event::{self, DisableBracketedPaste, EnableBracketedPaste, Event, KeyCode, KeyEventKind},+ event::{DisableBracketedPaste, EnableBracketedPaste, Event, KeyCode, KeyEventKind},execute,terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},};@@ -11,7 +11,7 @@ use std::io::{self, Stdout};use std::path::{Path, PathBuf};use std::sync::{atomic::{AtomicBool, Ordering},- mpsc, Arc,+ mpsc, Arc, Condvar, Mutex,};use std::time::Instant;@@ -115,7 +115,13 @@ fn styled_footer(text: &str, styles: TuiStyles) -> Line<'static> {}fn visible_column_range(selected: usize, width: u16) -> std::ops::Range<usize> {- let visible = if width >= 140 { 5 } else if width >= 96 { 3 } else { 2 };+ let visible = if width >= 140 {+ 5+ } else if width >= 96 {+ 3+ } else {+ 2+ };let start = selected.saturating_sub(visible / 2).min(5usize.saturating_sub(visible));@@ -318,9 +324,6 @@ struct AppState {show_project_list: bool,// Task shell popupshell_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<crate::tmux::PaneMetrics>)>>,// File search dropdownfile_search: Option<FileSearchState>,// Skill search dropdown@@ -359,7 +362,10 @@ struct AppState {setup_rx: Option<mpsc::Receiver<SetupResult>>,// Phase detectionphase_status_cache: HashMap<String, (PhaseStatus, Instant)>,- spinner_frame: usize,+ /// Paces the MCP transition-queue read, which is a SQLite query.+ last_transition_poll: Instant,+ /// Raised by the control connection when tmux reports a window closing.+ window_events: Arc<AtomicBool>,// Idle detection: (content_hash, last_change_time) per taskpane_content_hashes: HashMap<String, (u64, Instant)>,/// Why a task is Blocked, as reported by its agent's hook payload.@@ -753,6 +759,11 @@ impl App {// control connection at all.let mut input_config = InputConfig::new(tmux::AGENT_SERVER, &tmux_project_name);input_config.control_mode = control_mode_enabled();+ // tmux reports a window closing on this same connection, even with+ // `no-output`. That is how an exited agent becomes an `Exited` card+ // promptly instead of on the status refresh's next tick.+ let window_events = Arc::new(AtomicBool::new(false));+ input_config.window_events = Some(Arc::clone(&window_events));let input_sink = tmux::input::spawn(input_config, Arc::clone(&tmux_ops));// If the project is untrusted, also suppress plugin init_scripts@@ -795,7 +806,6 @@ impl App {selected_project: 0,show_project_list: false,shell_popup: None,- shell_refresh_rx: None,file_search: None,skill_search: None,task_ref_search: None,@@ -815,7 +825,8 @@ impl App {review_confirm_popup: None,trust_confirm_popup: None,phase_status_cache: HashMap::new(),- spinner_frame: 0,+ last_transition_poll: Instant::now(),+ window_events,pane_content_hashes: HashMap::new(),blocked_reasons: HashMap::new(),trust_blocked: HashSet::new(),@@ -1023,7 +1034,6 @@ impl App {selected_project: 0,show_project_list: false,shell_popup: None,- shell_refresh_rx: None,file_search: None,skill_search: None,task_ref_search: None,@@ -1043,7 +1053,8 @@ impl App {review_confirm_popup: None,trust_confirm_popup: None,phase_status_cache: HashMap::new(),- spinner_frame: 0,+ last_transition_poll: Instant::now(),+ window_events: Arc::new(AtomicBool::new(false)),pane_content_hashes: HashMap::new(),blocked_reasons: HashMap::new(),trust_blocked: HashSet::new(),@@ -1077,199 +1088,339 @@ impl App {self.state.input_sink = sink;}+ /// The event loop.+ ///+ /// It **blocks** on a channel that two threads feed β terminal input and+ /// pane captures β and draws only when something actually changed. The+ /// previous shape polled: `event::poll(interval)` woke the loop on a timer+ /// whether or not anything had happened, and every wake-up redrew the whole+ /// screen and re-parsed the pane capture through `parse_ansi_to_lines`. That+ /// made the poll interval a three-way trade between echo latency, DB+ /// polling rate and idle CPU, so tuning it for the first made the other two+ /// expensive.+ ///+ /// Splitting them makes each one answer to what it is actually for:+ ///+ /// - **latency** is the pane watcher's cadence, and it wakes the loop only+ /// when the pane it captured differs from the last one it sent;+ /// - **housekeeping** β the DB queue, the session refresh, the spinner β runs+ /// on its own tick, no faster than it needs to and no longer coupled to+ /// how fast the user types;+ /// - **drawing** happens when state changed, so an idle board with an idle+ /// popup costs one backstop frame a second.pub async fn run(&mut self) -> Result<()> {+ let (tx, rx) = mpsc::channel::<Wake>();+ spawn_terminal_reader(tx.clone());+ let watch = Arc::new(PaneWatch::default());+ spawn_pane_watcher(+ Arc::clone(&watch),+ tx,+ Arc::clone(&self.state.input_sink),+ Arc::clone(&self.state.tmux_ops),+ );++ // The first frame has nothing to be a change from.+ let mut dirty = true;+ let mut last_draw = Instant::now();+ let mut last_housekeeping = Instant::now() - HOUSEKEEPING_TICK;+while !self.state.should_quit {- self.draw()?;-- // Check for PR generation completion- if let Some(ref rx) = self.state.pr_generation_rx {- if let Ok((pr_title, pr_body)) = rx.try_recv() {- if let Some(ref mut popup) = self.state.pr_confirm_popup {- popup.pr_title = pr_title;- popup.pr_body = pr_body;- popup.generating = false;+ // A missed `dirty` would leave a stale screen until the next+ // keystroke, which is a far worse failure than a wasted frame β so+ // the loop repaints once a second regardless. A backstop, not the+ // mechanism: one frame a second is nothing, and if it is ever what+ // makes the UI look right, something above it is wrong.+ if dirty || last_draw.elapsed() >= REDRAW_BACKSTOP {+ self.draw()?;+ dirty = false;+ last_draw = Instant::now();+ }++ // Point the watcher at whatever popup is open now. Done here rather+ // than at the three sites that open one and the several that close+ // one: this cannot be forgotten by a new call site.+ let (watch_target, watch_depth) = match self.state.shell_popup.as_ref() {+ Some(popup) => (+ Some(popup.window_name.as_str()),+ popup_capture_depth(popup.scroll_offset),+ ),+ None => (None, SHELL_POPUP_TAIL_LINES),+ };+ watch.follow(watch_target, watch_depth);++ match rx.recv_timeout(HOUSEKEEPING_TICK) {+ Ok(wake) => {+ // Typing is the case the fast cadence exists for, so a key+ // ends the watcher's wait rather than landing in the middle+ // of a backed-off one.+ if matches!(wake, Wake::Input(_)) {+ watch.poke();}- self.state.pr_generation_rx = None;- }- }-- // Check for PR creation completion- if let Some(ref rx) = self.state.pr_creation_rx {- if let Ok(result) = rx.try_recv() {- match result {- Ok((_, pr_url)) => {- self.state.pr_status_popup = Some(PrStatusPopup {- status: PrCreationStatus::Success,- pr_url: Some(pr_url),- error_message: None,- });- }- Err(err) => {- self.state.pr_status_popup = Some(PrStatusPopup {- status: PrCreationStatus::Error,- pr_url: None,- error_message: Some(err),- });+ dirty |= self.handle_wake(wake)?;+ // Drain what is already queued: a burst of keystrokes, or a+ // key and the capture it caused, are one redraw, not four.+ loop {+ match rx.try_recv() {+ Ok(wake) => dirty |= self.handle_wake(wake)?,+ Err(mpsc::TryRecvError::Empty) => break,+ Err(mpsc::TryRecvError::Disconnected) => {+ self.state.should_quit = true;+ break;+ }}}- self.state.pr_creation_rx = None;- self.refresh_tasks()?;}+ Err(mpsc::RecvTimeoutError::Timeout) => {}+ // Both feeder threads are gone; without terminal input there is+ // no way left to quit.+ Err(mpsc::RecvTimeoutError::Disconnected) => self.state.should_quit = true,}- // Check for worktree setup completion- if let Some(ref rx) = self.state.setup_rx {- if let Ok(result) = rx.try_recv() {- self.state.setup_rx = None;- if let Some(err) = result.error {- self.state.warning_message = Some((err, Instant::now()));- } else {- // Update task with worktree info from background setup- if let Some(db) = &self.state.db {- if let Ok(Some(mut task)) = db.get_task(&result.task_id) {- task.session_name = Some(result.session_name);- task.worktree_path = Some(result.worktree_path);- task.branch_name = Some(result.branch_name);- task.agent = result.agent;- task.plugin = result.plugin;- if let Some(status) = result.new_status {- task.status = status;- }- task.updated_at = chrono::Utc::now();- let _ = db.update_task(&task);- }- }- self.refresh_tasks()?;- }- // This setup finished; start the next queued batch task (if any).- self.try_start_next_queued_setup()?;- }+ dirty |= self.pump_background_results()?;++ if last_housekeeping.elapsed() >= HOUSEKEEPING_TICK {+ last_housekeeping = Instant::now();+ dirty |= self.run_housekeeping();}+ }- // Process MCP transition requests from the command queue- self.process_transition_requests()?;+ watch.stop();+ Ok(())+ }- if event::poll(main_event_poll_timeout(self.state.shell_popup.is_some()))? {- match event::read()? {- Event::Key(key) if key.kind == KeyEventKind::Press => {- self.handle_key(key)?;+ /// Apply one wake-up. Returns whether the screen needs redrawing.+ fn handle_wake(&mut self, wake: Wake) -> Result<bool> {+ match wake {+ Wake::Input(Event::Key(key)) if key.kind == KeyEventKind::Press => {+ self.handle_key(key)?;+ Ok(true)+ }+ Wake::Input(Event::Paste(text)) => {+ self.handle_paste(text)?;+ Ok(true)+ }+ Wake::Input(Event::Resize(..)) => Ok(true),+ Wake::Input(_) => Ok(false),+ Wake::Pane {+ window,+ content,+ lines,+ metrics,+ } => {+ let Some(popup) = self.state.shell_popup.as_mut() else {+ return Ok(false);+ };+ // A capture for a popup that has since closed or switched panes+ // is not this popup's content.+ if popup.window_name != window {+ return Ok(false);+ }+ // The watcher already suppresses unchanged captures; this also+ // covers the first one after a popup seeded its own content+ // synchronously at open time.+ if popup.cached_content == content && popup.metrics == metrics {+ return Ok(false);+ }+ popup.set_content(content, lines);+ popup.metrics = metrics;+ Ok(true)+ }+ }+ }++ /// Collect anything the background threads have finished. Returns whether+ /// any of it changed what is on screen.+ fn pump_background_results(&mut self) -> Result<bool> {+ let mut changed = false;++ // Check for PR generation completion+ if let Some(ref rx) = self.state.pr_generation_rx {+ if let Ok((pr_title, pr_body)) = rx.try_recv() {+ if let Some(ref mut popup) = self.state.pr_confirm_popup {+ popup.pr_title = pr_title;+ popup.pr_body = pr_body;+ popup.generating = false;+ }+ self.state.pr_generation_rx = None;+ changed = true;+ }+ }++ // Check for PR creation completion+ if let Some(ref rx) = self.state.pr_creation_rx {+ if let Ok(result) = rx.try_recv() {+ match result {+ Ok((_, pr_url)) => {+ self.state.pr_status_popup = Some(PrStatusPopup {+ status: PrCreationStatus::Success,+ pr_url: Some(pr_url),+ error_message: None,+ });}- Event::Paste(text) => {- self.handle_paste(text)?;+ Err(err) => {+ self.state.pr_status_popup = Some(PrStatusPopup {+ status: PrCreationStatus::Error,+ pr_url: None,+ error_message: Some(err),+ });}- _ => {}}+ self.state.pr_creation_rx = None;+ self.refresh_tasks()?;+ changed = true;}+ }- // Apply a completed pane capture without ever waiting for tmux on- // the input thread.- if let Some(ref rx) = self.state.shell_refresh_rx {- match rx.try_recv() {- 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.metrics = metrics;+ // Check for worktree setup completion+ if let Some(ref rx) = self.state.setup_rx {+ if let Ok(result) = rx.try_recv() {+ self.state.setup_rx = None;+ if let Some(err) = result.error {+ self.state.warning_message = Some((err, Instant::now()));+ } else {+ // Update task with worktree info from background setup+ if let Some(db) = &self.state.db {+ if let Ok(Some(mut task)) = db.get_task(&result.task_id) {+ task.session_name = Some(result.session_name);+ task.worktree_path = Some(result.worktree_path);+ task.branch_name = Some(result.branch_name);+ task.agent = result.agent;+ task.plugin = result.plugin;+ if let Some(status) = result.new_status {+ task.status = status;}+ task.updated_at = chrono::Utc::now();+ let _ = db.update_task(&task);}}- Err(std::sync::mpsc::TryRecvError::Disconnected) => {- self.state.shell_refresh_rx = None;- }- Err(std::sync::mpsc::TryRecvError::Empty) => {}+ self.refresh_tasks()?;}+ // This setup finished; start the next queued batch task (if any).+ self.try_start_next_queued_setup()?;+ changed = true;}+ }- // Capturing history invokes tmux twice (content + cursor metadata),- // so run it in a single background worker at a responsive 20 FPS.- if self.state.shell_refresh_rx.is_none() {- if let Some(popup) = self.state.shell_popup.as_mut() {- if popup.content_refresh_due(SHELL_REFRESH_INTERVAL) {- let window_name = popup.window_name.clone();- let tmux_ops = Arc::clone(&self.state.tmux_ops);- let (tx, rx) = mpsc::channel();- popup.mark_content_refreshed();- self.state.shell_refresh_rx = Some(rx);- std::thread::spawn(move || {- let (content, metrics) = capture_tmux_pane_snapshot(- &window_name,- 500,- tmux_ops.as_ref(),- );- let _ = tx.send((window_name, content, metrics));- });- }+ // Apply results from background session refresh (non-blocking)+ if let Some(ref rx) = self.state.session_refresh_rx {+ match rx.try_recv() {+ Ok(result) => {+ self.state.session_refresh_rx = None;+ self.apply_session_refresh(result);+ changed = true;}+ Err(mpsc::TryRecvError::Disconnected) => {+ // Thread panicked or dropped sender β clear to allow future spawns+ self.state.session_refresh_rx = None;+ }+ Err(mpsc::TryRecvError::Empty) => {}}+ }- // Apply results from background session refresh (non-blocking)- if let Some(ref rx) = self.state.session_refresh_rx {- match rx.try_recv() {- Ok(result) => {- self.state.session_refresh_rx = None;- self.apply_session_refresh(result);- }- Err(std::sync::mpsc::TryRecvError::Disconnected) => {- // Thread panicked or dropped sender β clear to allow future spawns- self.state.session_refresh_rx = None;- }- Err(std::sync::mpsc::TryRecvError::Empty) => {}+ // Release check result (arrives once, then the channel is dropped)+ if let Some(ref rx) = self.state.update_rx {+ match rx.try_recv() {+ Ok(info) => {+ self.state.update_rx = None;+ self.state.update_available = info;+ changed = true;}- }- // Release check result (arrives once, then the channel is dropped)- if let Some(ref rx) = self.state.update_rx {- match rx.try_recv() {- Ok(info) => {- self.state.update_rx = None;- self.state.update_available = info;- }- Err(std::sync::mpsc::TryRecvError::Disconnected) => {- self.state.update_rx = None;- }- Err(std::sync::mpsc::TryRecvError::Empty) => {}+ Err(mpsc::TryRecvError::Disconnected) => {+ self.state.update_rx = None;}+ Err(mpsc::TryRecvError::Empty) => {}}+ }- // Result of an install started from the update popup- if let Some(ref rx) = self.state.update_install_rx {- match rx.try_recv() {- Ok(result) => {- self.state.update_install_rx = None;- if let Some(popup) = self.state.update_popup.as_mut() {- popup.installing = false;- popup.status = Some(match result {- Ok(msg) => msg,- Err(e) => format!("failed: {e}"),- });- }+ // Result of an install started from the update popup+ if let Some(ref rx) = self.state.update_install_rx {+ match rx.try_recv() {+ Ok(result) => {+ self.state.update_install_rx = None;+ if let Some(popup) = self.state.update_popup.as_mut() {+ popup.installing = false;+ popup.status = Some(match result {+ Ok(msg) => msg,+ Err(e) => format!("failed: {e}"),+ });}- Err(std::sync::mpsc::TryRecvError::Disconnected) => {- self.state.update_install_rx = None;- if let Some(popup) = self.state.update_popup.as_mut() {- popup.installing = false;- popup.status = Some("failed: the update thread stopped".to_string());- }+ changed = true;+ }+ Err(mpsc::TryRecvError::Disconnected) => {+ self.state.update_install_rx = None;+ if let Some(popup) = self.state.update_popup.as_mut() {+ popup.installing = false;+ popup.status = Some("failed: the update thread stopped".to_string());}- Err(std::sync::mpsc::TryRecvError::Empty) => {}+ changed = true;}+ Err(mpsc::TryRecvError::Empty) => {}}+ }- // Spawn background refresh if not already running and cache expired- self.maybe_spawn_session_refresh();+ Ok(changed)+ }- // Deliver queued notifications to orchestrator when idle- self.deliver_orchestrator_notifications();+ /// Periodic work, on its own tick rather than once per wake-up.+ ///+ /// Every item here used to run on every loop iteration β including+ /// `process_transition_requests`, which queries SQLite β so its rate rose and+ /// fell with how fast the user happened to be typing. Returns whether+ /// anything on screen moved.+ fn run_housekeeping(&mut self) -> bool {+ let mut changed = false;+ let now = Instant::now();- // Clear expired warning messages- if let Some((_, created)) = &self.state.warning_message {- if created.elapsed() >= std::time::Duration::from_secs(5) {- self.state.warning_message = None;- }+ // Process MCP transition requests from the command queue, on their own+ // interval β this is a SQLite query, and it used to run on every tick.+ if now.duration_since(self.state.last_transition_poll) >= TRANSITION_POLL_INTERVAL {+ self.state.last_transition_poll = now;+ if let Err(e) = self.process_transition_requests() {+ tracing::warn!(error = %e, "failed to process transition requests");}}- Ok(())+ // tmux said a window closed. The refresh is what turns that into an+ // `Exited` card, and its per-task cache would otherwise hold the old+ // status for up to `PHASE_STATUS_CACHE_TTL` β so age the cache out and+ // let the refresh below run now.+ if self.state.window_events.swap(false, Ordering::Relaxed) {+ self.expire_phase_status_cache();+ }++ // Spawn background refresh if not already running and cache expired.+ self.maybe_spawn_session_refresh();++ // Nothing on the board animates any more: every indicator is static, so+ // an idle board asks for no frame at all between real changes.++ // Deliver queued notifications to orchestrator when idle+ self.deliver_orchestrator_notifications();++ // Clear expired warning messages+ if let Some((_, created)) = &self.state.warning_message {+ if created.elapsed() >= WARNING_MESSAGE_TTL {+ self.state.warning_message = None;+ changed = true;+ }+ }++ changed+ }++ /// Make every cached phase status look stale, so the next refresh re-checks+ /// every task rather than waiting out its per-task TTL.+ ///+ /// The timestamps are aged rather than the entries dropped: the previous+ /// status is what decides `was_ready`, and losing it would suppress the+ /// "newly ready" notification for a task that had just finished.+ fn expire_phase_status_cache(&mut self) {+ let Some(stale) = Instant::now().checked_sub(PHASE_STATUS_CACHE_TTL) else {+ return;+ };+ for (_, ts) in self.state.phase_status_cache.values_mut() {+ *ts = stale;+ }}pub fn draw(&mut self) -> Result<()> {@@ -1329,7 +1480,10 @@ impl App {// Headerlet plugin_label = state.config.workflow_plugin.as_deref().unwrap_or("agtx");- let left = Span::styled(format!(" {}", state.project_name), Style::default().fg(styles.text).bold());+ let left = Span::styled(+ format!(" {}", state.project_name),+ Style::default().fg(styles.text).bold(),+ );let mut right_spans: Vec<Span> = Vec::new();if state.flags.experimental {let orch_active = state.orchestrator_session.is_some();@@ -1375,10 +1529,20 @@ impl App {let padding = (chunks[0].width as usize).saturating_sub(left_len + right_len + 2);let mut spans = vec![left, Span::raw(" ".repeat(padding))];spans.extend(right_spans);- frame.render_widget(Paragraph::new(Line::from(spans)), Rect { height: 1, ..chunks[0] });+ frame.render_widget(+ Paragraph::new(Line::from(spans)),+ Rect {+ height: 1,+ ..chunks[0]+ },+ );frame.render_widget(Paragraph::new("β".repeat(chunks[0].width as usize)).style(styles.muted()),- Rect { y: chunks[0].y + 1, height: 1, ..chunks[0] },+ Rect {+ y: chunks[0].y + 1,+ height: 1,+ ..chunks[0]+ },);// Keep cards usable on narrow terminals by showing a window around the@@ -1412,7 +1576,10 @@ impl App {Style::default().fg(styles.column_header).bold()};- let header_area = Rect { height: 2, ..column_area };+ let header_area = Rect {+ height: 2,+ ..column_area+ };let count = Span::styled(format!(" {}", tasks.len()), styles.muted());frame.render_widget(Paragraph::new(Line::from(vec![@@ -1422,13 +1589,24 @@ impl App {),count,])),- Rect { height: 1, ..header_area },+ Rect {+ height: 1,+ ..header_area+ },);- let rule_color = if is_selected_column { styles.selected } else { styles.dimmed };+ let rule_color = if is_selected_column {+ styles.selected+ } else {+ styles.dimmed+ };frame.render_widget(Paragraph::new("β".repeat(header_area.width as usize)).style(Style::default().fg(rule_color)),- Rect { y: header_area.y + 1, height: 1, ..header_area },+ Rect {+ y: header_area.y + 1,+ height: 1,+ ..header_area+ },);let inner_area = Rect {@@ -1490,13 +1668,16 @@ impl App {is_selected,&state.config.theme,state.phase_status_cache.get(&task.id),- state.spinner_frame,deps_blocked,);}if tasks.is_empty() {- let empty = if is_selected_column { " No tasks Β· [o] new" } else { " No tasks" };+ let empty = if is_selected_column {+ " No tasks Β· [o] new"+ } else {+ " No tasks"+ };frame.render_widget(Paragraph::new(empty).style(styles.muted()), inner_area);}@@ -1574,16 +1755,26 @@ impl App {frame.render_widget(Paragraph::new("β".repeat(chunks[2].width as usize)).style(styles.muted()),- Rect { height: 1, ..chunks[2] },+ Rect {+ height: 1,+ ..chunks[2]+ },);let footer_line = if footer_style.fg == Some(Color::Yellow) {- Line::from(Span::styled(format!(" {}", footer_text.trim()), footer_style))+ Line::from(Span::styled(+ format!(" {}", footer_text.trim()),+ footer_style,+ ))} else {styled_footer(&footer_text, styles)};frame.render_widget(Paragraph::new(footer_line).alignment(Alignment::Center),- Rect { y: chunks[2].y + 1, height: 1, ..chunks[2] },+ Rect {+ y: chunks[2].y + 1,+ height: 1,+ ..chunks[2]+ },);// Input overlay if in input mode@@ -2840,7 +3031,9 @@ impl App {};// Parse ANSI escape sequences for colors- let styled_lines = parse_ansi_to_lines(&popup.cached_content);+ // Parsed by the watcher, and borrowed rather than cloned: only the rows+ // that fit on screen are copied, not the whole cached pane.+ let styled_lines = popup.cached_lines.as_slice();// Build colors from themelet colors = shell_popup::ShellPopupColors {@@ -2863,7 +3056,6 @@ impl App {is_selected: bool,theme: &ThemeConfig,phase_status: Option<&(PhaseStatus, Instant)>,- spinner_frame: usize,deps_blocked: bool,) {let styles = TuiStyles::from_theme(theme);@@ -2897,7 +3089,11 @@ impl App {let card_block = Block::default().borders(Borders::ALL).border_style(border_style)- .border_type(if is_selected { BorderType::Rounded } else { BorderType::Plain });+ .border_type(if is_selected {+ BorderType::Rounded+ } else {+ BorderType::Plain+ });let block_inner = card_block.inner(area);frame.render_widget(card_block, area);let inner = Rect {@@ -2914,17 +3110,17 @@ impl App {&& task.session_name.is_some());if show_indicator {- const SPINNER_FRAMES: &[&str] = &[- "\u{280b}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283c}", "\u{2834}", "\u{2826}",- "\u{2827}", "\u{2807}", "\u{280f}",- ];let indicator = match phase_status {Some((PhaseStatus::Ready, _)) => {Span::styled("\u{2713} ", Style::default().fg(Color::Green))}+ // Static, not a spinner. An animated frame is a redraw of the+ // whole board, and on an otherwise idle board it was the *only*+ // thing forcing one β ten a second, forever, to rotate a glyph.+ // The card already says a task is running; the motion added+ // nothing that the icon does not.Some((PhaseStatus::Working, _)) => {- let spinner = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];- Span::styled(format!("{} ", spinner), Style::default().fg(Color::Yellow))+ Span::styled("\u{25b6} ", Style::default().fg(Color::Yellow))}Some((PhaseStatus::Blocked, _)) => Span::styled("? ",@@ -3120,7 +3316,11 @@ impl App {);frame.render_widget(Paragraph::new("β".repeat(area.width.saturating_sub(1) as usize)).style(styles.muted()),- Rect { y: area.y + 1, height: 1, ..area },+ Rect {+ y: area.y + 1,+ height: 1,+ ..area+ },);frame.render_widget(List::new(items),@@ -4065,10 +4265,10 @@ impl App {.unwrap_or(24);(SHELL_POPUP_CONTENT_WIDTH, height.saturating_sub(4))};- let _ = self- .state- .tmux_ops- .resize_window(&window_name, pane_width, pane_height);+ let _ =+ self.state+ .tmux_ops+ .resize_window(&window_name, pane_width, pane_height);popup.last_pane_size = Some((pane_width, pane_height));return Ok(());}@@ -7031,7 +7231,8 @@ impl App {}let (content, metrics) =capture_tmux_pane_snapshot(&orch_target, 500, self.state.tmux_ops.as_ref());- popup.cached_content = content;+ let lines = parse_ansi_to_lines(&content);+ popup.set_content(content, lines);popup.metrics = metrics;let _ = self.state.input_sink.flush();self.state.shell_popup = Some(popup);@@ -7115,7 +7316,8 @@ impl App {}let (content, metrics) =capture_tmux_pane_snapshot(&orch_target, 500, self.state.tmux_ops.as_ref());- popup.cached_content = content;+ let lines = parse_ansi_to_lines(&content);+ popup.set_content(content, lines);popup.metrics = metrics;let _ = self.state.input_sink.flush();self.state.shell_popup = Some(popup);@@ -7207,12 +7409,13 @@ impl App {// 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+ // Leaving them to the first 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;+ let lines = parse_ansi_to_lines(&content);+ popup.set_content(content, lines);popup.metrics = metrics;// A popup opening changes the target; nothing queued for the@@ -7230,11 +7433,10 @@ impl App {popup.fullscreen = true;if let Ok((width, height)) = crossterm::terminal::size() {let pane_size = (width.saturating_sub(2), height.saturating_sub(4));- let _ = self.state.tmux_ops.resize_window(- &popup.window_name,- pane_size.0,- pane_size.1,- );+ let _ =+ self.state+ .tmux_ops+ .resize_window(&popup.window_name, pane_size.0, pane_size.1);popup.last_pane_size = Some(pane_size);}}@@ -7383,12 +7585,11 @@ impl App {fn maybe_spawn_session_refresh(&mut self) {// Don't spawn if a refresh is already in flightif self.state.session_refresh_rx.is_some() {- self.state.spinner_frame = self.state.spinner_frame.wrapping_add(1);return;}let now = Instant::now();- const CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);+ const CACHE_TTL: std::time::Duration = PHASE_STATUS_CACHE_TTL;// Collect tasks that need checking (cache expired or never checked)let tasks_to_check: Vec<_> = self@@ -7431,18 +7632,24 @@ impl App {.collect();if tasks_to_check.is_empty() {- self.state.spinner_frame = self.state.spinner_frame.wrapping_add(1);return;}let project_path = self.state.project_path.clone();let tmux_ops = Arc::clone(&self.state.tmux_ops);+ let input_sink = Arc::clone(&self.state.input_sink);let auto_trust = self.state.config.auto_trust;let (tx, rx) = mpsc::channel();self.state.session_refresh_rx = Some(rx);std::thread::spawn(move || {+ // Every window on the server, once, rather than a `list-windows`+ // process per task. `window_exists` is a membership test, and asking+ // tmux N times for the same answer was the largest remaining+ // per-task subprocess cost on the board.+ let live_windows = live_window_targets(tmux_ops.as_ref());+let mut plugin_cache: HashMap<Option<String>, Option<WorkflowPlugin>> = HashMap::new();let mut statuses = Vec::new();let now_secs = chrono::Utc::now().timestamp();@@ -7528,9 +7735,10 @@ impl App {// Check if tmux window still exists β if not, mark as Exited// (unless phase artifact was found, in which case it completed before the crash)- let window_gone = session_name- .as_ref()- .map_or(false, |sn| !tmux_ops.window_exists(sn).unwrap_or(true));+ //+ // Answered from one listing taken for the whole pass: this used to+ // be a `list-windows` **process per task**, on a 2-second timer.+ let window_gone = window_is_gone(session_name.as_deref(), live_windows.as_ref());let phase_status = if window_gone && phase_status == PhaseStatus::Working {PhaseStatus::Exited} else {@@ -7565,15 +7773,30 @@ impl App {Some(hook_status::HookState::Working));let mut awaiting_trust: Option<String> = None;+ // One capture for this pass, shared by the dialog scan below and+ // the content hash further down. They ask different questions of+ // the same bytes, and reading the pane twice was a second `tmux`+ // process per task for every agent that reports no hook status β+ // which is the case the hash exists for in the first place.+ // `hook_says_working` implies a hook status exists, so this one+ // condition is exactly the union of the two below.+ let pane_text: Option<String> =+ if phase_status == PhaseStatus::Working && !window_gone && !hook_says_working {+ session_name.as_ref().and_then(|sn| {+ capture_pane_text(sn, input_sink.as_ref(), tmux_ops.as_ref())+ })+ } else {+ None+ };if phase_status == PhaseStatus::Working && !window_gone && !hook_says_working {if let Some(sn) = session_name.as_ref() {- if let Ok(content) = tmux_ops.capture_pane(sn) {+ if let Some(content) = pane_text.as_deref() {// Detected whether or not it is answered: with// `auto_trust` off this is what turns the card// `Blocked`, so the user knows a decision is theirs to// make rather than watching a task sit at "working".if !auto_trust {- awaiting_trust = visible_security_dialog(Some(&agent), &content)+ awaiting_trust = visible_security_dialog(Some(&agent), content).map(str::to_string);}// A fresh state each poll: the attempt cap guards a@@ -7584,7 +7807,7 @@ impl App {&tmux_ops,sn,Some(&agent),- &content,+ content,&mut st,auto_trust,);@@ -7595,7 +7818,7 @@ impl App {// Matched against this agent's own dialogs only: the// refresh loop knows what runs in the pane, unlike// `wait_for_agent_ready`.- answer_session_dialogs(&tmux_ops, sn, &agent, &content);+ answer_session_dialogs(&tmux_ops, sn, &agent, content);}}}@@ -7607,13 +7830,11 @@ impl App {&& !window_gone&& hook_status.is_none(){- session_name.as_ref().and_then(|sn| {- tmux_ops.capture_pane(sn).ok().map(|content| {- use std::hash::{Hash, Hasher};- let mut hasher = std::collections::hash_map::DefaultHasher::new();- content.hash(&mut hasher);- hasher.finish()- })+ pane_text.as_ref().map(|content| {+ use std::hash::{Hash, Hasher};+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ content.hash(&mut hasher);+ hasher.finish()})} else {None@@ -7909,8 +8130,6 @@ impl App {.remove(&task_status.task_id);}}-- self.state.spinner_frame = self.state.spinner_frame.wrapping_add(1);}fn switch_to_project(&mut self, project: &ProjectInfo) -> Result<()> {@@ -8699,14 +8918,95 @@ fn capture_tmux_pane_snapshot(// Lines below the cursor are unused pane buffer spacelet metrics = tmux_ops.pane_metrics(window_name);- // Trim content to only include lines up to cursor position- let trim_info = metrics.map(|m| m.trim_bounds());+ trim_pane_snapshot(crate::tmux::PaneSnapshot { content, metrics })+}++/// Cut the unused pane buffer below the cursor off a capture.+///+/// Shared by both capture paths so they cannot disagree about what the popup is+/// shown β the whole point of the control-mode path is to be indistinguishable+/// from the subprocess one apart from its cost.+fn trim_pane_snapshot(+ snapshot: crate::tmux::PaneSnapshot,+) -> (Vec<u8>, Option<crate::tmux::PaneMetrics>) {+ let trim_info = snapshot.metrics.map(|m| m.trim_bounds());(- shell_popup::trim_content_to_cursor(content, trim_info),- metrics,+ shell_popup::trim_content_to_cursor(snapshot.content, trim_info),+ snapshot.metrics,)}+/// Capture a pane for the popup: over the input broker's control connection when+/// there is one, otherwise the two `tmux` processes this has always cost.+///+/// The broker is asked first because it already holds a live `tmux -C` client+/// for keystrokes, and reusing it avoids the process startup that dominated the+/// delay between typing into a task pane and seeing the character appear. It+/// also flushes buffered keystrokes ahead of the capture, so a frame can never+/// be missing text the user has already typed.+fn capture_pane_for_popup(+ window_name: &str,+ history_lines: i32,+ input_sink: &dyn PaneInputSink,+ tmux_ops: &dyn TmuxOperations,+) -> (Vec<u8>, Option<crate::tmux::PaneMetrics>) {+ match input_sink.capture(window_name, crate::tmux::CaptureSpec::popup(history_lines)) {+ Some(snapshot) => trim_pane_snapshot(snapshot),+ None => capture_tmux_pane_snapshot(window_name, history_lines, tmux_ops),+ }+}++/// Windows that currently exist, as a set of `session:window` targets, or `None`+/// when tmux could not be asked.+///+/// The `Option` is the whole point and must not be flattened to an empty set.+/// The per-task check this replaces failed *safe* β+/// `!window_exists(sn).unwrap_or(true)` leaves a task alone when the check+/// errors β whereas an empty set reads as "every window is gone" and would mark+/// every running task `Exited` on one transient tmux hiccup. That is a visible,+/// wrong status change on the whole board, so a failed listing must mean+/// "unknown", not "none".+fn live_window_targets(tmux_ops: &dyn TmuxOperations) -> Option<std::collections::HashSet<String>> {+ tmux_ops+ .list_window_targets()+ .ok()+ .map(|targets| targets.into_iter().collect())+}++/// Has this task's tmux window gone away?+///+/// Split out because its **failure direction** is the whole subtlety: `None` for+/// the listing means tmux could not be asked, and must read as "leave the task+/// alone", never as "every window is gone". Getting that backwards marks a whole+/// board `Exited` on one transient tmux hiccup.+fn window_is_gone(session: Option<&str>, live: Option<&std::collections::HashSet<String>>) -> bool {+ match (session, live) {+ (Some(sn), Some(live)) => !live.contains(sn),+ _ => false,+ }+}++/// Read a pane as **plain text**, over the input connection when there is one.+///+/// The status refresh's counterpart to [`capture_pane_for_popup`]: no escapes,+/// no scrollback, no geometry β byte-identical to+/// [`TmuxOperations::capture_pane`], which is what the dialog matcher and the+/// content hash have always been fed.+///+/// Worth routing because this is the last per-task subprocess left on the status+/// refresh's timer: the fallback is a `tmux` process *per task*, and it scales+/// with the size of the board.+fn capture_pane_text(+ target: &str,+ input_sink: &dyn PaneInputSink,+ tmux_ops: &dyn TmuxOperations,+) -> Option<String> {+ if let Some(snapshot) = input_sink.capture(target, crate::tmux::CaptureSpec::text()) {+ return Some(String::from_utf8_lossy(&snapshot.content).into_owned());+ }+ tmux_ops.capture_pane(target).ok()+}+/// Generate PR title and description using the configured agentpub(crate) fn generate_pr_description(task_title: &str,@@ -9028,21 +9328,695 @@ fn pane_target(session: &str, window: &str) -> String {/// 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")- )+ control_mode_from_env(std::env::var("AGTX_TMUX_CONTROL").ok().as_deref())}-const SHELL_REFRESH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);-const DEFAULT_EVENT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);+/// The policy half, split from the read so it can be tested without touching+/// the process environment. `setenv` is not thread-safe against a concurrent+/// `getenv`, and `cargo test` runs hundreds of tests in parallel threads β a+/// test that mutates a global to check a `match` is a race for no reason.+fn control_mode_from_env(value: Option<&str>) -> bool {+ !matches!(value, Some("0") | Some("false") | Some("no"))+}-fn main_event_poll_timeout(shell_popup_open: bool) -> std::time::Duration {- if shell_popup_open {- SHELL_REFRESH_INTERVAL+/// How fresh the popup's view of its pane is while the **user is typing**.+///+/// It means two different things depending on how the watcher is being driven:+/// under push it is a *rate limit* β the ceiling on how often a paint may cause+/// a capture β and on the poll fallback it is the sampling period itself.+///+/// Either way it is the term a keystroke's echo latency is made of, which is+/// only true because a capture over the control connection is cheap where two+/// `tmux` processes were not. Its cost is paid on the far side β a capture makes+/// the tmux server format the whole pane β so this is not free to lower. [`PANE_OUTPUT_MIN_INTERVAL`] is the same ceiling for the agent's own+/// output, where nobody is waiting on a single frame.+const SHELL_REFRESH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);++/// Scrollback lines a popup capture asks for **when the user has scrolled up**.+///+/// A pane in the alternate screen β where full-screen agent UIs live β has none,+/// and returns just the visible rows regardless of this.+const SHELL_POPUP_CAPTURE_LINES: i32 = 500;++/// Scrollback lines to ask for while the popup sits **at the bottom**.+///+/// Only the visible rows are rendered there, so the rest is fetched, formatted+/// by the tmux server, compared and parsed for nothing. Not zero, because the+/// first `C-u` needs somewhere to scroll to: 100 lines is ~3 pages, and by the+/// time the user scrolls past that the deeper capture has arrived.+///+/// Worth nothing for the agents that matter today β they take the alternate+/// screen, where `history_size` is 0 and every depth returns the same bytes. It+/// is for a pane that *does* accumulate history, where the deeper capture is+/// many times the size of the screen being rendered.+const SHELL_POPUP_TAIL_LINES: i32 = 100;++/// How deep the watcher should capture, given where the popup is scrolled.+fn popup_capture_depth(scroll_offset: i32) -> i32 {+ if scroll_offset < 0 {+ SHELL_POPUP_CAPTURE_LINES+ } else {+ SHELL_POPUP_TAIL_LINES+ }+}++/// What the **poll fallback** slows to once a pane has stopped changing.+///+/// Only reached when push is unavailable ([`attach_pane_push`]); with an output+/// watch attached, a still pane produces no captures at all and this never+/// applies. Once a pane has been unchanged for [`PANE_IDLE_ROUNDS`] nobody is+/// waiting on a millisecond, and this much staleness is invisible. A keystroke+/// pokes the watcher back+/// to [`SHELL_REFRESH_INTERVAL`] before the character is even delivered, so the+/// first character after a pause is as prompt as the tenth.+const PANE_IDLE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);++/// How long the watcher waits for a paint that never comes.+///+/// Under push this replaces the poll interval entirely, so it is a **safety+/// net**, not a cadence: `%output` says bytes reached the pty, not that the+/// rendered pane differs, and the converse happens too β a repaint with no new+/// bytes still changes what `capture-pane` returns. A missed signal is otherwise+/// invisible, because the popup simply stops updating. Same reasoning as+/// [`REDRAW_BACKSTOP`], and if it is ever what makes the popup look right,+/// something above it is wrong.+const PANE_PUSH_BACKSTOP: std::time::Duration = std::time::Duration::from_millis(500);++/// Slowest a capture may be driven by the **agent painting**, as opposed to by+/// the user typing.+///+/// The two deserve different answers and used to share one. Nobody reads text+/// scrolling past frame by frame, but everybody notices their own keystroke+/// arriving late β so the agent's output is sampled at a readable rate while+/// typing keeps [`SHELL_REFRESH_INTERVAL`].+///+/// Not a micro-optimisation: sharing one ceiling made a pane painting flat out+/// cost more than the polling it replaced. Every frame is a `capture-pane`, and+/// a capture makes the tmux server format the whole pane.+const PANE_OUTPUT_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);++/// How long after a keystroke captures stay on the fast cadence.+///+/// A keystroke's echo does not arrive with the keystroke: the key reaches the+/// pane almost immediately, the agent repaints a little later, and *that* is+/// what the watcher sees β as a paint, indistinguishable from the agent's own+/// output.+/// Rate-limiting paints to [`PANE_OUTPUT_MIN_INTERVAL`] without this window would+/// therefore delay the echo of every character by that much, which is the one+/// thing this whole lane exists to avoid.+const PANE_TYPING_WINDOW: std::time::Duration = std::time::Duration::from_millis(250);++/// How long to wait before trying to attach an output watch again.+///+/// Attaching costs two `tmux` processes (the pane id, then the client), and the+/// attempt sits in a loop that runs every [`SHELL_REFRESH_INTERVAL`]. A popup+/// left open on a window that has since closed would otherwise spawn a hundred+/// processes a second β the exact cost this whole change removes, reintroduced+/// through the failure path.+const PANE_PUSH_RETRY: std::time::Duration = std::time::Duration::from_secs(2);++/// Unchanged captures before the poll fallback backs off.+///+/// Counted in rounds, so the wall-clock settling time is this times+/// [`SHELL_REFRESH_INTERVAL`] β change one and the other moves with it. It only+/// has to outlast the gap between two keystrokes.+const PANE_IDLE_ROUNDS: u32 = 40;++/// How often periodic work runs: the MCP transition queue, the session refresh,+/// the spinner, expiring warnings.+///+/// What matters is that it is *decoupled* from input, so none of it speeds up+/// because the user is typing. Anything wanting a slower rate keeps its own+/// interval β see [`TRANSITION_POLL_INTERVAL`].+const HOUSEKEEPING_TICK: std::time::Duration = std::time::Duration::from_millis(100);++/// How long the screen may go unpainted while nothing reports a change.+const REDRAW_BACKSTOP: std::time::Duration = std::time::Duration::from_secs(1);++/// How often the MCP transition queue is read.+///+/// A SQLite query, previously run on every housekeeping tick β ten times a+/// second, forever, whether or not anything is connected. A queued transition is+/// not latency-critical: it is a request to move a task between columns, and the+/// phase status it acts on is itself refreshed on a 2-second cache.+const TRANSITION_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);++/// How long a phase status is trusted before the refresh looks again.+const PHASE_STATUS_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);++/// How long a warning banner stays up.+const WARNING_MESSAGE_TTL: std::time::Duration = std::time::Duration::from_secs(5);++/// Why the event loop woke up.+///+/// Terminal input and pane content arrive on separate threads and are merged+/// into one channel, so the loop can block on both at once instead of polling+/// each on a timer.+enum Wake {+ Input(Event),+ Pane {+ window: String,+ content: Vec<u8>,+ /// Parsed on the watcher thread β see `ShellPopup::cached_lines`.+ lines: Vec<Line<'static>>,+ metrics: Option<crate::tmux::PaneMetrics>,+ },+}++/// Which pane the watcher should be capturing, if any.+///+/// A condvar rather than a channel because the watcher spends most of its life+/// waiting on exactly one of two things β a target to appear, or its next+/// capture β and both are this same wait. With no popup open it blocks+/// indefinitely and costs nothing.+#[derive(Default)]+struct PaneWatch {+ inner: Mutex<PaneWatchState>,+ cv: Condvar,+}++#[derive(Default)]+struct PaneWatchState {+ target: Option<String>,+ /// tmux pane id of `target` (`%7`), matched against `%output` notifications.+ /// `None` means push is unavailable for this pane and the timer runs.+ pane_id: Option<String>,+ /// Scrollback depth to capture β see [`popup_capture_depth`].+ history_lines: i32,+ /// Bumped to make the watcher capture now, at the fast cadence.+ poke: u64,+ /// Bumped by the output watch every time *this* pane paints.+ signal: u64,+ stopped: bool,+}++impl PaneWatch {+ /// Point the watcher at `target` (or nothing). Cheap enough to call every+ /// iteration, which is the point: no popup call site has to remember to.+ fn follow(&self, target: Option<&str>, history_lines: i32) {+ let Ok(mut state) = self.inner.lock() else {+ return;+ };+ if state.target.as_deref() == target {+ if state.history_lines != history_lines {+ // The user scrolled: re-capture at the new depth now, rather+ // than leaving them looking at a buffer with nothing above it.+ state.history_lines = history_lines;+ state.poke = state.poke.wrapping_add(1);+ drop(state);+ self.cv.notify_all();+ }+ return;+ }+ state.history_lines = history_lines;+ state.target = target.map(str::to_string);+ // The id belongs to the old pane; the watcher resolves the new one.+ state.pane_id = None;+ state.poke = state.poke.wrapping_add(1);+ drop(state);+ self.cv.notify_all();+ }++ /// Record that `pane_id` painted. Called from the output-watch reader+ /// thread, for **every** pane in the session, so it filters before waking.+ fn mark_output(&self, pane_id: &str) {+ let Ok(mut state) = self.inner.lock() else {+ return;+ };+ if state.pane_id.as_deref() != Some(pane_id) {+ return;+ }+ state.signal = state.signal.wrapping_add(1);+ drop(state);+ self.cv.notify_all();+ }++ /// Wait for a poke, a paint, a target change or `wait` to elapse, and report+ /// whether a **poke** was what ended it. `None` means stop.+ ///+ /// A method, not an inline block, because the lock must not outlive the+ /// wait: the watcher takes it again immediately afterwards for the rate+ /// limit, and `Mutex` is not reentrant. Inline, the arm that does not hand+ /// its guard to `wait_timeout` kept the guard alive for the rest of the+ /// iteration and the watcher deadlocked against itself β holding the very+ /// lock the UI thread calls [`follow`](Self::follow) on every iteration, so+ /// the whole TUI froze. Here the guard cannot escape the call.+ fn wait_for_change(+ &self,+ poke: u64,+ signal: u64,+ wait: std::time::Duration,+ ) -> Option<WaitOutcome> {+ let Ok(state) = self.inner.lock() else {+ return None;+ };+ if state.stopped {+ return None;+ }+ if state.poke != poke || state.signal != signal {+ // Something landed while the capture was in flight; no reason to wait.+ return Some(WaitOutcome {+ poked: state.poke != poke,+ skipped: true,+ });+ }+ let Ok((state, _)) = self.cv.wait_timeout(state, wait) else {+ return None;+ };+ if state.stopped {+ return None;+ }+ Some(WaitOutcome {+ poked: state.poke != poke,+ skipped: false,+ })+ }++ /// Hold off for `wait`, unless a poke arrives first. `None` means stop.+ ///+ /// Same reasoning as [`wait_for_change`](Self::wait_for_change): the guard+ /// stays inside the call. A plain sleep would be simpler and wrong β it would+ /// hold the ceiling meant for the agent's paints against the user's own echo.+ fn wait_out_rate_limit(&self, wait: std::time::Duration) -> Option<bool> {+ let Ok(state) = self.inner.lock() else {+ return None;+ };+ let before = state.poke;+ let Ok((state, _)) = self.cv.wait_timeout(state, wait) else {+ return None;+ };+ if state.stopped {+ return None;+ }+ Some(state.poke != before)+ }++ fn set_pane_id(&self, pane_id: Option<String>) {+ if let Ok(mut state) = self.inner.lock() {+ state.pane_id = pane_id;+ }+ }++ /// Capture now and go back to the fast cadence: the user just typed.+ fn poke(&self) {+ if let Ok(mut state) = self.inner.lock() {+ state.poke = state.poke.wrapping_add(1);+ }+ self.cv.notify_all();+ }++ fn stop(&self) {+ if let Ok(mut state) = self.inner.lock() {+ state.stopped = true;+ }+ self.cv.notify_all();+ }++ fn target(&self) -> Option<String> {+ self.inner.lock().ok().and_then(|s| s.target.clone())+ }++ /// Pokes issued so far. The watcher compares it across its wait to notice a+ /// poke that arrived *while* it was capturing; tests read it to assert that+ /// following the same target twice is not one.+ fn poke_count(&self) -> u64 {+ self.inner.lock().map(|s| s.poke).unwrap_or(0)+ }++ /// Paint signals accepted so far. Tests read it to assert the filtering.+ #[cfg(test)]+ fn signal_count(&self) -> u64 {+ self.inner.lock().map(|s| s.signal).unwrap_or(0)+ }+}++/// How a [`PaneWatch::wait_for_change`] ended.+struct WaitOutcome {+ /// The user typed. Puts the watcher back on the fast cadence.+ poked: bool,+ /// There was no wait at all: a poke or a paint had already landed while the+ /// capture was in flight, so the pane is known to be moving.+ skipped: bool,+}++/// Is this capture different from the last one the watcher sent?+///+/// Geometry counts as much as content: a cursor that moved without the text+/// changing still has to be repainted, and a capture whose target has changed is+/// not this pane's content at all.+fn pane_capture_changed(+ last: &Option<(String, Vec<u8>, Option<crate::tmux::PaneMetrics>)>,+ target: &str,+ content: &[u8],+ metrics: &Option<crate::tmux::PaneMetrics>,+) -> bool {+ match last {+ Some((window, seen, seen_metrics)) => {+ window != target || seen != content || seen_metrics != metrics+ }+ None => true,+ }+}++/// Still rounds to carry into the next wait.+///+/// A poke resets the count, and that is not bookkeeping β it is the half of the+/// back-off that makes it safe. The capture a poke triggers runs *before* the+/// keystroke that caused it has reached the pane and been echoed, so it sees+/// nothing new; without the reset the watcher would then wait out another idle+/// interval and the character would appear a whole one late.+fn pane_watch_rounds_after_wait(unchanged_rounds: u32, poked: bool) -> u32 {+ if poked {+ 0} else {- DEFAULT_EVENT_POLL_INTERVAL+ unchanged_rounds+ }+}++/// How long to wait before the next capture, given how long the pane has been+/// still. See [`PANE_IDLE_INTERVAL`] for why this has two speeds.+fn pane_watch_interval(unchanged_rounds: u32) -> std::time::Duration {+ if unchanged_rounds >= PANE_IDLE_ROUNDS {+ PANE_IDLE_INTERVAL+ } else {+ SHELL_REFRESH_INTERVAL+ }+}++/// Read terminal events on their own thread.+///+/// `event::read()` blocks, which is exactly what is wanted now: the loop learns+/// about a keystroke when there is one instead of asking every few milliseconds.+fn spawn_terminal_reader(tx: mpsc::Sender<Wake>) {+ let _ = std::thread::Builder::new()+ .name("agtx-terminal-input".to_string())+ .spawn(move || loop {+ match crossterm::event::read() {+ Ok(event) => {+ if tx.send(Wake::Input(event)).is_err() {+ break;+ }+ }+ // The terminal is gone; the loop's channel will disconnect and+ // it will quit on its own.+ Err(e) => {+ tracing::debug!(error = %e, "terminal input reader stopped");+ break;+ }+ }+ });+}++/// Capture the open popup's pane, and wake the loop **only when it changed**.+///+/// Comparing here rather than in the loop is what makes an idle popup free: an+/// agent that is painting nothing produces no wake-ups at all, so no frame is+/// drawn and no capture is re-parsed.+///+/// **How it learns the pane painted** has two modes, and the second is not a+/// degraded copy of the first β it is the whole design when control mode is off:+///+/// - **push**, when an [`OutputWatch`](crate::tmux::OutputWatch) is attached:+/// the thread sleeps until tmux says *this* pane produced output. Typing at+/// human speed changes the pane 5β8 times a second where the timer sampled it+/// 100 times, so most of those captures found nothing new; push removes+/// exactly that waste.+/// - **poll**, otherwise: the historical timer, fast while the pane changes and+/// backing off once it settles.+///+/// Under push, `SHELL_REFRESH_INTERVAL` stops being a poll period and becomes a+/// **rate limit**. The signal removes the floor β no capture when nothing+/// happened β while the interval keeps the ceiling, because a pane painting flat+/// out notifies far faster than it is worth capturing.+fn spawn_pane_watcher(+ watch: Arc<PaneWatch>,+ tx: mpsc::Sender<Wake>,+ input_sink: Arc<dyn PaneInputSink>,+ tmux_ops: Arc<dyn TmuxOperations>,+) {+ let _ = std::thread::Builder::new()+ .name("agtx-pane-watch".to_string())+ .spawn(move || {+ let mut last: Option<(String, Vec<u8>, Option<crate::tmux::PaneMetrics>)> = None;+ let mut unchanged: u32 = 0;+ let mut push: Option<PanePush> = None;+ let mut push_retry_at: Option<Instant> = None;+ let mut watched_target = String::new();+ // When the user last typed, which decides how fast paints are+ // sampled β see `PANE_TYPING_WINDOW`.+ let mut last_keystroke: Option<Instant> = None;+ loop {+ // With no popup open, release the output watch so tmux mirrors+ // nothing for a session nobody is looking at.+ //+ // Outside the lock, never under it: dropping the watch closes a+ // tmux client and reaps the child, and the UI thread calls+ // `follow()` on this same mutex every iteration β so holding it+ // here stalls the whole TUI until that client exits.+ if watch+ .inner+ .lock()+ .map(|state| state.target.is_none())+ .unwrap_or(true)+ {+ push = None;+ }+ // Then wait for something to watch. No popup open is the common+ // case, and costs one blocked thread and nothing else.+ let (target, poke, signal, history_lines) = {+ let Ok(mut state) = watch.inner.lock() else {+ return;+ };+ while state.target.is_none() && !state.stopped {+ let Ok(next) = watch.cv.wait(state) else {+ return;+ };+ state = next;+ }+ if state.stopped {+ return;+ }+ (+ state.target.clone(),+ state.poke,+ state.signal,+ state.history_lines,+ )+ };+ let Some(target) = target else { continue };++ if target != watched_target {+ // A new pane deserves an immediate attempt rather than+ // whatever backoff the previous one had accumulated.+ push_retry_at = None;+ watched_target = target.clone();+ }+ push =+ attach_pane_push(push, &target, &watch, tmux_ops.as_ref(), &mut push_retry_at);++ let captured_at = Instant::now();+ let (content, metrics) = capture_pane_for_popup(+ &target,+ history_lines,+ input_sink.as_ref(),+ tmux_ops.as_ref(),+ );+ if pane_capture_changed(&last, &target, &content, &metrics) {+ unchanged = 0;+ last = Some((target.clone(), content.clone(), metrics));+ // Parsed here, off the thread that handles keystrokes, and+ // once per *change* rather than once per frame.+ let lines = parse_ansi_to_lines(&content);+ if tx+ .send(Wake::Pane {+ window: target,+ content,+ lines,+ metrics,+ })+ .is_err()+ {+ return;+ }+ } else {+ unchanged = unchanged.saturating_add(1);+ }++ let pushing = push.is_some();+ // Under push there is nothing to poll for: the next capture is+ // caused by the pane painting, and this is only the net for a+ // signal that never came.+ let wait = if pushing {+ PANE_PUSH_BACKSTOP+ } else {+ pane_watch_interval(unchanged)+ };+ // A poke, a paint, or a target change ends the wait early, so+ // backing off never costs the first keystroke after a pause.+ //+ // A poke also puts the watcher back on the fast cadence, and+ // that half is not optional: the capture a poke triggers runs+ // *before* the key it announced has reached the pane and been+ // echoed, so it sees no change. Without the reset the next wait+ // would be the slow one again and the echo would arrive a whole+ // idle interval late β the back-off charging exactly what it+ // was built not to.+ let Some(outcome) = watch.wait_for_change(poke, signal, wait) else {+ return;+ };+ if outcome.skipped {+ // The pane is moving; do not let a back-off accumulate.+ unchanged = 0;+ }+ let poked = outcome.poked;+ if poked {+ last_keystroke = Some(Instant::now());+ }+ unchanged = pane_watch_rounds_after_wait(unchanged, poked);++ // The rate limit, under push only β polling already paces itself.+ //+ // Waited on the condvar rather than slept, so a keystroke still+ // gets through: a plain sleep here would hold the ceiling meant+ // for the *agent's* paints against the user's own echo, adding up+ // to `PANE_OUTPUT_MIN_INTERVAL` to the first character typed+ // after a pause.+ if let Some(remaining) = push_rate_limit_wait(+ pushing,+ captured_at.elapsed(),+ last_keystroke.map(|at| at.elapsed()),+ ) {+ let Some(poked_during_limit) = watch.wait_out_rate_limit(remaining) else {+ return;+ };+ if poked_during_limit {+ last_keystroke = Some(Instant::now());+ }+ }+ }+ });+}++/// How long to hold off the next capture, given how long ago the last one+/// started. `None` means capture now.+///+/// Only meaningful under push: it turns `SHELL_REFRESH_INTERVAL` from "how often+/// to look" into "no more often than this", which is what stops a pane painting+/// flat out from driving one capture per notification.+fn push_rate_limit_wait(+ pushing: bool,+ since_last_capture: std::time::Duration,+ since_last_keystroke: Option<std::time::Duration>,+) -> Option<std::time::Duration> {+ if !pushing {+ return None;+ }+ let floor = match since_last_keystroke {+ // The user is typing: their own echo is what is being waited on.+ Some(since) if since < PANE_TYPING_WINDOW => SHELL_REFRESH_INTERVAL,+ // Nobody is waiting on a single frame of the agent's output.+ _ => PANE_OUTPUT_MIN_INTERVAL,+ };+ if since_last_capture >= floor {+ return None;+ }+ Some(floor - since_last_capture)+}++/// The output-watch connection for the pane currently being followed.+struct PanePush {+ /// Session the watch is attached to. `%output` never crosses sessions, so a+ /// popup in another session needs a different client.+ session: String,+ watch: crate::tmux::OutputWatch,+}++/// Keep the output watch pointed at `target`'s session, reconnecting when the+/// popup moves and giving up β to the timer β when tmux will not cooperate.+///+/// `None` is a supported state, not a failure: `AGTX_TMUX_CONTROL=0`, a tmux+/// that refuses the attach, and a pane whose id cannot be read all land here and+/// get the poll path instead.+fn attach_pane_push(+ current: Option<PanePush>,+ target: &str,+ watch: &Arc<PaneWatch>,+ tmux_ops: &dyn TmuxOperations,+ retry_at: &mut Option<Instant>,+) -> Option<PanePush> {+ if !control_mode_enabled() || !output_push_enabled() {+ return None;+ }+ let session = pane_push_session(target);+ if let Some(push) = current {+ if push.session == session && push.watch.alive() {+ return Some(push);+ }+ // Dropping it closes the client, so nothing stays mirrored for a session+ // nobody is looking at.+ // Also outside any lock, for the same reason: this runs on the watcher+ // thread with nothing held, and closing the client can take a moment.+ drop(push);+ // A watch that died is retried like a first attempt, not immediately.+ *retry_at = Some(Instant::now() + PANE_PUSH_RETRY);+ return None;}+ // Both steps below spawn a `tmux` process, and this runs once per watcher+ // iteration. Without a backoff, a popup left open on a window that has since+ // closed would spawn them continuously β far worse than the polling this+ // replaces.+ if let Some(at) = retry_at {+ if Instant::now() < *at {+ return None;+ }+ }+ *retry_at = Some(Instant::now() + PANE_PUSH_RETRY);+ // The id is what every `%output` line is matched against; without it the+ // watch could only say "some pane in this session painted", which is not a+ // signal β it would fire on every other task's output.+ let pane_id = tmux_ops.pane_id(target)?;+ watch.set_pane_id(Some(pane_id));++ let signal_watch = Arc::clone(watch);+ match crate::tmux::OutputWatch::connect(crate::tmux::AGENT_SERVER, &session, move |id| {+ signal_watch.mark_output(id);+ }) {+ Ok(client) => {+ tracing::debug!(session, "pane output watch attached");+ *retry_at = None;+ Some(PanePush {+ session,+ watch: client,+ })+ }+ Err(e) => {+ tracing::debug!(error = %e, "pane output watch unavailable; polling instead");+ watch.set_pane_id(None);+ None+ }+ }+}++/// Is `%output` push on for this run?+///+/// On unless `AGTX_TMUX_PUSH` says otherwise, and there is no config field for+/// the same reason [`control_mode_enabled`] has none: an attach that fails falls+/// back to polling on its own, so a persisted setting could only hold a staler+/// copy of a decision made at runtime. The escape hatch exists because a bug+/// report needs to bisect the two capture lanes β push against poll β the way+/// `AGTX_TMUX_CONTROL` bisects the two input lanes.+fn output_push_enabled() -> bool {+ control_mode_from_env(std::env::var("AGTX_TMUX_PUSH").ok().as_deref())+}++/// The session half of a `session:window` target β the only thing `%output` is+/// scoped to, so it is what decides whether an existing watch can be reused.+fn pane_push_session(target: &str) -> String {+ target+ .split_once(':')+ .map(|(session, _)| session)+ .unwrap_or(target)+ .to_string()}/// Parse ANSI escape sequences to ratatui Lines with colors@@ -9295,9 +10269,7 @@ fn wizard_plugin_option_lines(let marker_width = Span::raw(marker.to_string()).width();let prefix_width = marker_width + LABEL_WIDTH + CHECK_WIDTH;- let description_width = width- .saturating_sub(prefix_width + RIGHT_PADDING)- .max(1);+ let description_width = width.saturating_sub(prefix_width + RIGHT_PADDING).max(1);let mut description_lines = wrap_spans(vec![Span::styled(description.to_string(), description_style)],description_width,@@ -11333,10 +12305,7 @@ fn claude_shaped_hooks(if let (Some(m), Some(obj)) = (matcher, group.as_object_mut()) {obj.insert("matcher".to_string(), serde_json::json!(m));}- out.insert(- (*event).to_string(),- serde_json::Value::Array(vec![group]),- );+ out.insert((*event).to_string(), serde_json::Value::Array(vec![group]));}serde_json::Value::Object(out)}@@ -11504,7 +12473,12 @@ fn merge_hook_events(let mut defs: Vec<serde_json::Value> = existing.get(event).and_then(|d| d.as_array())- .map(|a| a.iter().filter(|d| !is_agtx_hook_entry(d)).cloned().collect())+ .map(|a| {+ a.iter()+ .filter(|d| !is_agtx_hook_entry(d))+ .cloned()+ .collect()+ }).unwrap_or_default();if let Some(arr) = our_defs.as_array() {defs.extend(arr.iter().cloned());@@ -11640,12 +12614,7 @@ fn write_skills_to_worktree(////// The writers whose file is shared with an MCP config, or may be committed,/// merge; the rest own their file and are written outright.-fn write_hook_config(- spec: &agent::AgentSpec,- worktree_path: &str,- agtx_bin: &str,- enabled: bool,-) {+fn write_hook_config(spec: &agent::AgentSpec, worktree_path: &str, agtx_bin: &str, enabled: bool) {let Some(kind) = spec.hook_config else {return;};@@ -11738,7 +12707,10 @@ fn write_hook_config(agent::HookConfigKind::GrokHooksJson => {let dir = wt.join(".grok").join("hooks");let _ = std::fs::create_dir_all(&dir);- write_json(&dir.join("agtx.json"), &serde_json::json!({ "hooks": ours }));+ write_json(+ &dir.join("agtx.json"),+ &serde_json::json!({ "hooks": ours }),+ );}// Keyed by hook *name* first, event second; every handler carries its own// `--event` because the payload has no event name. `.agents/` is@@ -11819,7 +12791,10 @@ fn read_json_object(path: &Path) -> serde_json::Map<String, serde_json::Value> {}fn write_json(path: &Path, value: &serde_json::Value) {- let _ = std::fs::write(path, serde_json::to_string_pretty(value).unwrap_or_default());+ let _ = std::fs::write(+ path,+ serde_json::to_string_pretty(value).unwrap_or_default(),+ );}/// Merge agtx's hooks into a settings file it shares with other keys.@@ -11979,10 +12954,7 @@ fn write_mcp_config("trust": true}),);- settings.insert(- "mcpServers".to_string(),- serde_json::Value::Object(servers),- );+ settings.insert("mcpServers".to_string(), serde_json::Value::Object(servers));write_json(&path, &serde_json::Value::Object(settings));}agent::McpConfigKind::CursorJson => {diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex ebf4557..d2e1cf9 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -56,7 +56,11 @@ fn board_scrollbar_is_hidden_without_overflow_or_height() {fn styled_footer_emphasizes_shortcuts_without_changing_text() {let styles = TuiStyles::from_theme(&ThemeConfig::default());let line = styled_footer(" [o] new [Enter] open ", styles);- let rendered: String = line.spans.iter().map(|span| span.content.as_ref()).collect();+ let rendered: String = line+ .spans+ .iter()+ .map(|span| span.content.as_ref())+ .collect();assert_eq!(rendered, "[o] new [Enter] open");assert_eq!(line.spans[0].style.fg, Some(styles.selected));assert_eq!(line.spans[1].style.fg, Some(styles.dimmed));@@ -83,7 +87,11 @@ fn wizard_plugin_descriptions_wrap_and_align() {assert!(lines.len() > 1);for line in &lines {- assert!(line.width() <= 40, "line reached the right margin: {:?}", line);+ assert!(+ line.width() <= 40,+ "line reached the right margin: {:?}",+ line+ );}let continuation: String = lines[1].spans@@ -863,9 +871,383 @@ fn control_modifiers_reach_the_pane() {}#[test]-fn shell_popup_uses_twenty_fps_poll_interval() {- assert_eq!(main_event_poll_timeout(true), std::time::Duration::from_millis(50));- assert_eq!(main_event_poll_timeout(false), std::time::Duration::from_millis(100));+fn an_unreadable_window_listing_never_marks_a_task_exited() {+ use std::collections::HashSet;+ let live: HashSet<String> = ["pj:t1".to_string()].into_iter().collect();++ assert!(!window_is_gone(Some("pj:t1"), Some(&live)));+ assert!(window_is_gone(Some("pj:gone"), Some(&live)));++ // The direction that matters. One listing now answers for every task, so a+ // failed listing read as "no windows" would mark the whole board `Exited` β+ // a visible, wrong status change β where the per-task check it replaced+ // failed safe (`!window_exists(sn).unwrap_or(true)`).+ assert!(+ !window_is_gone(Some("pj:t1"), None),+ "an unreadable listing must mean unknown, not gone"+ );+ // An empty-but-readable listing is real information: the windows are gone.+ assert!(window_is_gone(Some("pj:t1"), Some(&HashSet::new())));+ // A task with no session was never running in the first place.+ assert!(!window_is_gone(None, Some(&HashSet::new())));+}++#[test]+fn the_pane_watcher_only_wakes_the_loop_when_the_pane_changed() {+ // The property the whole event-driven loop rests on: an agent painting+ // nothing produces no wake-ups, so no frame is drawn and no capture is+ // re-parsed. Asserted on the comparison itself, which is what the watcher+ // thread decides with.+ let a = (+ "task-x".to_string(),+ b"same".to_vec(),+ Some(crate::tmux::PaneMetrics {+ cursor_x: 1,+ cursor_y: 2,+ pane_height: 30,+ history_size: 0,+ }),+ );+ assert!(!pane_capture_changed(&Some(a.clone()), &a.0, &a.1, &a.2));++ // Content, geometry and target each count as a change on their own: a+ // cursor that moved without the text changing is still a redraw, and a+ // capture for a different pane is never this pane's content.+ let mut moved = a.clone();+ moved.2.as_mut().unwrap().cursor_x = 9;+ assert!(pane_capture_changed(+ &Some(a.clone()),+ &moved.0,+ &moved.1,+ &moved.2+ ));+ assert!(pane_capture_changed(&Some(a.clone()), &a.0, b"other", &a.2));+ assert!(pane_capture_changed(&Some(a.clone()), "task-y", &a.1, &a.2));+ // Nothing seen yet always sends, so a popup that seeded its own content+ // still gets a first real capture.+ assert!(pane_capture_changed(&None, &a.0, &a.1, &a.2));+}++#[test]+fn the_watcher_backs_off_only_after_the_pane_has_settled() {+ // Fast while the pane is moving β that is the cadence a keystroke's echo+ // rides on β and slow once it has not moved for a while, because then+ // nobody is waiting on a millisecond.+ assert_eq!(pane_watch_interval(0), SHELL_REFRESH_INTERVAL);+ assert_eq!(+ pane_watch_interval(PANE_IDLE_ROUNDS - 1),+ SHELL_REFRESH_INTERVAL+ );+ assert_eq!(pane_watch_interval(PANE_IDLE_ROUNDS), PANE_IDLE_INTERVAL);+ assert!(PANE_IDLE_INTERVAL > SHELL_REFRESH_INTERVAL);+ // The back-off must not be reachable between two keystrokes at any human+ // typing speed, or the first character after a pause would lag.+ assert!(SHELL_REFRESH_INTERVAL * PANE_IDLE_ROUNDS >= std::time::Duration::from_millis(150));+}++#[test]+fn a_poke_puts_the_watcher_back_on_the_fast_cadence() {+ // The regression this exists for: a poke's own capture runs before the key+ // it announced has reached the pane, so it sees nothing new. If that left+ // the count alone, the echo would wait out another idle interval β which is+ // the back-off charging exactly what it was built not to.+ let settled = PANE_IDLE_ROUNDS + 10;+ assert_eq!(pane_watch_interval(settled), PANE_IDLE_INTERVAL);+ assert_eq!(+ pane_watch_interval(pane_watch_rounds_after_wait(settled, true)),+ SHELL_REFRESH_INTERVAL,+ "a keystroke must return the watcher to the fast cadence"+ );+ // A wait that simply expired changes nothing: an idle pane stays idle.+ assert_eq!(pane_watch_rounds_after_wait(settled, false), settled);+}++#[test]+fn a_paint_signal_only_wakes_the_pane_being_watched() {+ // The output watch mirrors *every* pane in the session, so filtering is what+ // keeps another task's output from driving captures of this one.+ let watch = PaneWatch::default();+ watch.follow(Some("pj:mine"), SHELL_POPUP_TAIL_LINES);+ watch.set_pane_id(Some("%7".to_string()));+ let before = watch.signal_count();++ watch.mark_output("%9");+ assert_eq!(watch.signal_count(), before, "another pane must not signal");+ watch.mark_output("%7");+ assert_ne!(watch.signal_count(), before, "the watched pane must signal");++ // With no id resolved, push is not active and nothing may signal β the+ // watcher is on the timer, and a stray wake would defeat its back-off.+ watch.set_pane_id(None);+ let idle = watch.signal_count();+ watch.mark_output("%7");+ assert_eq!(watch.signal_count(), idle);+}++#[test]+fn following_a_new_pane_drops_the_previous_pane_id() {+ // Otherwise the old pane's output would keep signalling after the popup+ // moved, and the new pane's would not.+ let watch = PaneWatch::default();+ watch.follow(Some("pj:one"), SHELL_POPUP_TAIL_LINES);+ watch.set_pane_id(Some("%1".to_string()));+ watch.follow(Some("pj:two"), SHELL_POPUP_TAIL_LINES);+ let before = watch.signal_count();+ watch.mark_output("%1");+ assert_eq!(+ watch.signal_count(),+ before,+ "the old pane must stop signalling the moment the popup moves"+ );+}++#[test]+fn the_interval_becomes_a_rate_limit_under_push() {+ use std::time::Duration;+ let typing = Some(Duration::ZERO);+ // Push removes the floor: with a signal driving captures, the interval's+ // only job is to stop a pane painting flat out from driving one capture per+ // notification.+ assert_eq!(+ push_rate_limit_wait(true, Duration::ZERO, typing),+ Some(SHELL_REFRESH_INTERVAL)+ );+ assert_eq!(+ push_rate_limit_wait(true, SHELL_REFRESH_INTERVAL, typing),+ None+ );+ // Polling paces itself through its own wait, so it must never sleep twice.+ assert_eq!(push_rate_limit_wait(false, Duration::ZERO, typing), None);+}++#[test]+fn output_is_sampled_slower_than_a_keystroke_echo() {+ use std::time::Duration;+ // The two reasons to capture deserve different answers. Sharing one made a+ // pane painting flat out cost more than the polling it replaced: a capture+ // makes the tmux server format the whole pane, so capturing every frame is+ // expensive where nobody is watching for one. The polling had been protected+ // by its own slowness β one `capture-pane` process per capture.+ assert!(PANE_OUTPUT_MIN_INTERVAL > SHELL_REFRESH_INTERVAL);++ // Nobody is waiting on one frame of an agent's output.+ let idle_hands = Some(PANE_TYPING_WINDOW * 2);+ assert_eq!(+ push_rate_limit_wait(true, Duration::ZERO, idle_hands),+ Some(PANE_OUTPUT_MIN_INTERVAL)+ );+ assert_eq!(+ push_rate_limit_wait(true, Duration::ZERO, None),+ Some(PANE_OUTPUT_MIN_INTERVAL)+ );++ // But a keystroke's echo arrives as a *paint*, indistinguishable from the+ // agent's own output β so for a window after typing, paints stay fast or+ // every character would echo up to `PANE_OUTPUT_MIN_INTERVAL` late.+ assert_eq!(+ push_rate_limit_wait(true, Duration::ZERO, Some(PANE_TYPING_WINDOW / 2)),+ Some(SHELL_REFRESH_INTERVAL)+ );+ assert!(PANE_TYPING_WINDOW > SHELL_REFRESH_INTERVAL * 4);+}++#[test]+#[cfg(feature = "test-mocks")]+fn a_failing_output_watch_is_not_retried_every_iteration() {+ // The failure path runs inside a loop that ticks every+ // `SHELL_REFRESH_INTERVAL`, and each attempt is two `tmux` processes. A+ // popup left open on a window that has since closed would otherwise spawn a+ // hundred processes a second β the very cost this change removes.+ let mut mock = MockTmuxOperations::new();+ // The point of the assertion: asked once, not once per call.+ mock.expect_pane_id().times(1).returning(|_| None);+ let watch = Arc::new(PaneWatch::default());+ let mut retry_at: Option<std::time::Instant> = None;++ for _ in 0..50 {+ let push = attach_pane_push(None, "pj:t1", &watch, &mock, &mut retry_at);+ assert!(push.is_none(), "a pane with no id cannot be watched");+ }+ assert!(retry_at.is_some(), "a failed attach must schedule a retry");+}++#[test]+fn the_output_watch_is_reused_only_within_one_session() {+ // `%output` never crosses sessions, so the session decides whether an open+ // watch still covers the pane being followed.+ assert_eq!(pane_push_session("pj:task-one"), "pj");+ assert_eq!(+ pane_push_session("pj:task-one"),+ pane_push_session("pj:task-two")+ );+ assert_ne!(pane_push_session("pj:t"), pane_push_session("other:t"));+ // A bare target names no session; treating it as one is better than+ // panicking, and `pane_target` guarantees it does not happen.+ assert_eq!(pane_push_session("bare"), "bare");+}++#[test]+fn the_transition_queue_paces_itself() {+ // A SQLite query that used to run on every housekeeping tick β ten times a+ // second, forever, whether or not anything was connected. A transition is a+ // request to move a task between columns, acted on against a phase status+ // that is itself only as fresh as its cache, so polling the queue faster+ // than that cache buys nothing.+ assert!(TRANSITION_POLL_INTERVAL > HOUSEKEEPING_TICK);+ assert!(TRANSITION_POLL_INTERVAL >= PHASE_STATUS_CACHE_TTL);+}++#[test]+fn nothing_on_the_board_animates() {+ // The `Working` indicator used to be a spinner, and on an otherwise idle+ // board it was the *only* thing forcing a redraw β ten a second, forever, to+ // rotate a glyph. Every indicator is now static, so a board with running+ // tasks asks for no frame at all between real changes. If a future indicator+ // animates, `run_housekeeping` has to start reporting a change again, and+ // the idle cost comes back with it.+ let src = include_str!("app.rs");+ assert!(+ !src.contains("SPINNER_FRAMES"),+ "an animated indicator is back; idle redraws return with it"+ );+}++#[test]+fn the_capture_depth_follows_the_scroll_position() {+ // At the bottom only the visible rows are rendered, so a deeper capture is+ // fetched, formatted by tmux, compared and parsed for nothing. Scrolled up,+ // the history is the whole point.+ assert_eq!(popup_capture_depth(0), SHELL_POPUP_TAIL_LINES);+ assert_eq!(popup_capture_depth(-1), SHELL_POPUP_CAPTURE_LINES);+ assert_eq!(popup_capture_depth(-40), SHELL_POPUP_CAPTURE_LINES);+ assert!(SHELL_POPUP_TAIL_LINES < SHELL_POPUP_CAPTURE_LINES);+ // Not zero: the first `C-u` has to have somewhere to scroll to, and a page+ // is the pane's height.+ assert!(+ SHELL_POPUP_TAIL_LINES >= 60,+ "the tail must cover a few pages, or the first scroll-up hits the end"+ );+}++#[test]+fn scrolling_repoints_the_watcher_without_changing_target() {+ // A scroll is not a target change, but it *is* a reason to capture again β+ // otherwise the user scrolls into a buffer that has nothing above it and+ // waits for the next paint to fill it in.+ let watch = PaneWatch::default();+ watch.follow(Some("pj:t"), SHELL_POPUP_TAIL_LINES);+ let before = watch.poke_count();++ watch.follow(Some("pj:t"), SHELL_POPUP_TAIL_LINES);+ assert_eq!(+ watch.poke_count(),+ before,+ "an unchanged depth must not poke"+ );++ watch.follow(Some("pj:t"), SHELL_POPUP_CAPTURE_LINES);+ assert_ne!(+ watch.poke_count(),+ before,+ "scrolling up must trigger a deeper capture immediately"+ );+}++#[test]+fn the_popup_renders_the_lines_the_watcher_parsed() {+ // The parse moved off the UI thread, so the bytes and the styled lines are+ // now two fields that must be set together: rendering from lines that do+ // not match the bytes change detection compares would leave a wrong frame+ // on screen forever, because the next capture would compare equal.+ let mut popup = ShellPopup::new("t".to_string(), "pj:t".to_string());+ let content = b"\x1b[31mred\x1b[0m\nplain\n".to_vec();+ let lines = parse_ansi_to_lines(&content);+ assert_eq!(lines.len(), 2);+ popup.set_content(content.clone(), lines);+ assert_eq!(popup.cached_content, content);+ assert_eq!(popup.cached_lines.len(), 2);+ // Scrolling still reads the byte side, so the two must describe one pane.+ assert_eq!(+ popup.cached_lines.len(),+ String::from_utf8_lossy(&popup.cached_content)+ .lines()+ .count()+ );+}++/// Both waits must release `PaneWatch`'s lock before returning, because the+/// watcher takes it again straight afterwards and `Mutex` is not reentrant.+///+/// This is the invariant that broke: written inline, the arm that did not hand+/// its guard to `wait_timeout` kept the guard for the rest of the iteration, the+/// rate limit below re-locked, and the watcher deadlocked *holding the lock the+/// UI thread calls `follow()` on every iteration* β so the whole TUI froze. The+/// waits are methods now so the guard cannot escape them; this pins that.+#[test]+fn the_waits_release_the_lock_before_returning() {+ let watch = PaneWatch::default();+ watch.follow(Some("pj:t1"), SHELL_POPUP_TAIL_LINES);++ // The arm that used to keep its guard: a poke already landed, so the wait is+ // skipped entirely rather than handed to `wait_timeout`.+ watch.poke();+ let outcome = watch+ .wait_for_change(0, 0, std::time::Duration::from_millis(50))+ .expect("not stopped");+ assert!(+ outcome.skipped,+ "a poke that already landed must skip the wait"+ );+ assert!(outcome.poked);+ assert!(+ watch.inner.try_lock().is_ok(),+ "wait_for_change returned still holding the lock"+ );++ // And the arm that does wait.+ let (poke, signal) = {+ let state = watch.inner.lock().expect("lock");+ (state.poke, state.signal)+ };+ let outcome = watch+ .wait_for_change(poke, signal, std::time::Duration::from_millis(1))+ .expect("not stopped");+ assert!(!outcome.skipped);+ assert!(+ watch.inner.try_lock().is_ok(),+ "wait_for_change returned still holding the lock after waiting"+ );++ assert!(watch+ .wait_out_rate_limit(std::time::Duration::from_millis(1))+ .is_some());+ assert!(+ watch.inner.try_lock().is_ok(),+ "wait_out_rate_limit returned still holding the lock"+ );+}++#[test]+fn a_pane_watch_follows_the_open_popup() {+ let watch = PaneWatch::default();+ assert_eq!(watch.target(), None);++ watch.follow(Some("task-one"), SHELL_POPUP_TAIL_LINES);+ assert_eq!(watch.target().as_deref(), Some("task-one"));+ let after_first = watch.poke_count();++ // Following the same target again must not poke: this is called every loop+ // iteration, and a poke means "capture now at the fast cadence".+ watch.follow(Some("task-one"), SHELL_POPUP_TAIL_LINES);+ assert_eq!(watch.poke_count(), after_first);++ // A switch and a close both have to reach the watcher, or it would keep+ // capturing a pane nobody is looking at.+ watch.follow(Some("task-two"), SHELL_POPUP_TAIL_LINES);+ assert_eq!(watch.target().as_deref(), Some("task-two"));+ assert_ne!(watch.poke_count(), after_first);+ watch.follow(None, SHELL_POPUP_TAIL_LINES);+ assert_eq!(watch.target(), None);}// =============================================================================@@ -907,6 +1289,81 @@ fn test_capture_tmux_pane_snapshot() {assert_eq!(metrics.map(|m| m.history_size), Some(0));}+/// A sink that answers captures from a canned snapshot, standing in for a live+/// control connection.+#[cfg(feature = "test-mocks")]+struct CapturingSink(Option<crate::tmux::PaneSnapshot>);++#[cfg(feature = "test-mocks")]+impl PaneInputSink for CapturingSink {+ fn send(+ &self,+ _input: crate::tmux::PaneInput,+ ) -> std::result::Result<(), crate::tmux::InputError> {+ Ok(())+ }+ fn capture(+ &self,+ _target: &str,+ _spec: crate::tmux::CaptureSpec,+ ) -> Option<crate::tmux::PaneSnapshot> {+ self.0.clone()+ }+}++/// The popup's capture goes to the broker's control connection when there is+/// one: the `tmux` process startup it replaces was most of the delay between+/// typing into a task pane and seeing the character.+#[test]+#[cfg(feature = "test-mocks")]+fn the_popup_capture_prefers_the_input_connection() {+ let mut mock_tmux = MockTmuxOperations::new();+ // Not `times(0)` on a permissive mock: an unexpected call panics, which is+ // the assertion. Neither subprocess may run when the sink answers.+ mock_tmux.expect_capture_pane_with_history().never();+ mock_tmux.expect_pane_metrics().never();++ let sink = CapturingSink(Some(crate::tmux::PaneSnapshot {+ content: b"from control\n".to_vec(),+ metrics: Some(crate::tmux::PaneMetrics {+ cursor_x: 0,+ cursor_y: 0,+ pane_height: 1,+ history_size: 7,+ }),+ }));++ let (content, metrics) = capture_pane_for_popup("test-window", 500, &sink, &mock_tmux);+ // Trimmed to the cursor, exactly as the subprocess path is.+ assert_eq!(content, b"from control".to_vec());+ assert_eq!(metrics.map(|m| m.history_size), Some(7));+}++/// And falls back untouched when it does not: control mode is off, the+/// connection is down, or the queue is full. A missed capture costs one frame at+/// the old speed, never a blank popup.+#[test]+#[cfg(feature = "test-mocks")]+fn the_popup_capture_falls_back_to_the_subprocess_path() {+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux+ .expect_capture_pane_with_history()+ .returning(|_, _| b"from subprocess\n".to_vec());+ mock_tmux.expect_pane_metrics().returning(|_| {+ Some(crate::tmux::PaneMetrics {+ cursor_x: 0,+ cursor_y: 0,+ pane_height: 1,+ history_size: 3,+ })+ });++ let (content, metrics) =+ capture_pane_for_popup("test-window", 500, &CapturingSink(None), &mock_tmux);+ assert_eq!(content, b"from subprocess".to_vec());+ assert_eq!(metrics.map(|m| m.history_size), Some(3));+}+// =============================================================================// Tests for centered_rect helpers (pure functions, no mocks needed)// =============================================================================@@ -11498,12 +11955,19 @@ fn test_gemini_hooks_merge_with_existing_settings() {).unwrap();- assert_eq!(v["theme"], serde_json::json!("Dracula"), "user key survived");+ assert_eq!(+ v["theme"],+ serde_json::json!("Dracula"),+ "user key survived"+ );assert_eq!(v["mcpServers"]["agtx"]["command"].is_string(), true);let before_tool = v["hooks"]["BeforeTool"].as_array().unwrap();assert_eq!(before_tool.len(), 2, "user hook kept, agtx hook appended");assert_eq!(before_tool[0]["hooks"][0]["command"], "mine.sh");- assert_eq!(v["hooks"]["AfterAgent"][0]["hooks"][0]["command"].is_string(), true);+ assert_eq!(+ v["hooks"]["AfterAgent"][0]["hooks"][0]["command"].is_string(),+ true+ );}/// Redeploying must replace agtx's entries rather than accumulate them β@@ -11566,7 +12030,10 @@ fn test_antigravity_hooks_preserve_a_projects_own_hooks() {).unwrap();- assert_eq!(v["lint-checker"]["PostToolUse"][0]["hooks"][0]["command"], "./lint.sh");+ assert_eq!(+ v["lint-checker"]["PostToolUse"][0]["hooks"][0]["command"],+ "./lint.sh"+ );// Its payload carries no event name, so every handler must name its own.assert!(v["agtx"]["Stop"][0]["command"].as_str()@@ -11590,9 +12057,10 @@ fn test_cursor_hooks_carry_the_version_envelope() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], true);- let v: serde_json::Value =- serde_json::from_str(&std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap())- .unwrap();+ let v: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap(),+ )+ .unwrap();assert_eq!(v["version"], serde_json::json!(1));// Flat `{command}`, not the Claude `{hooks:[{type,command}]}` wrapper β// cursor loads the wrapped form without complaint and never fires it.@@ -11659,7 +12127,10 @@ fn test_cursor_hooks_preserve_a_projects_own_hooks() {let stop = v["hooks"]["stop"].as_array().unwrap();assert_eq!(stop.len(), 2);assert_eq!(stop[0]["command"], "./mine.sh");- assert!(stop[1]["command"].as_str().unwrap().contains("hook --env cursor"));+ assert!(stop[1]["command"]+ .as_str()+ .unwrap()+ .contains("hook --env cursor"));}/// Redeploying must replace agtx's own flat `{command}` entries, not stack them.@@ -13558,9 +14029,7 @@ fn scroll_keys_go_to_the_agent_when_tmux_has_no_history() {// `handle_popup_scroll`.assert_eq!(keys,- vec![- "PageUp", "PageDown", "PageUp", "PageDown", "PageUp", "PageDown", "End"- ]+ vec!["PageUp", "PageDown", "PageUp", "PageDown", "PageUp", "PageDown", "End"]);assert_eq!(app.state.shell_popup.as_ref().unwrap().scroll_offset,@@ -13672,33 +14141,17 @@ 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");-+ assert!(control_mode_from_env(None), "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");+ assert!(!control_mode_from_env(Some(off)), "{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");+ assert!(control_mode_from_env(Some(on)), "{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"),- }+ assert!(control_mode_from_env(Some("maybe")));+ assert!(control_mode_from_env(Some("")));}#[test]diff --git a/src/tui/shell_popup.rs b/src/tui/shell_popup.rsindex 8888b80..189bebd 100644--- a/src/tui/shell_popup.rs+++ b/src/tui/shell_popup.rs@@ -10,6 +10,12 @@ pub struct ShellPopup {pub scroll_offset: i32, // Negative means scroll up (see more history)/// Cached pane content - updated periodically, not on every framepub cached_content: Vec<u8>,+ /// [`cached_content`](Self::cached_content) already parsed into styled lines.+ ///+ /// Parsed once, on the watcher thread, rather than on every frame in `draw()`.+ /// Kept beside the bytes because the bytes are what change detection+ /// compares, and comparing them is far cheaper than parsing them.+ pub cached_lines: Vec<Line<'static>>,/// Last known pane dimensions for resize detectionpub last_pane_size: Option<(u16, u16)>,/// Escalation note from the orchestrator, shown as a banner@@ -32,6 +38,7 @@ impl ShellPopup {window_name,scroll_offset: 0,cached_content: Vec::new(),+ cached_lines: Vec::new(),last_pane_size: None,escalation_note: None,task_id: None,@@ -41,6 +48,16 @@ impl ShellPopup {}}+ /// Replace the cached pane, bytes and parsed lines together.+ ///+ /// One setter so the two cannot drift: rendering from lines that do not match+ /// the bytes change detection compares would show a frame that is never+ /// corrected, because the next capture would compare equal.+ pub fn set_content(&mut self, content: Vec<u8>, lines: Vec<Line<'static>>) {+ self.cached_content = content;+ self.cached_lines = lines;+ }+/// Scroll up into history, clamped to content bounds.pub fn scroll_up(&mut self, lines: i32) {// Derive the total line count from text lines rather than raw '\n' bytes,@@ -100,8 +117,14 @@ pub struct ShellPopupView<'a> {/// Compute the visible lines for the shell popup/// This is the core testable logic, separated from rendering+/// Takes a **slice**, not a `Vec`, and clones only the rows it returns.+///+/// The caller's lines are cached and reused across frames, so taking them by+/// value meant cloning every cached row β 100 of them, or 500 once scrolled β to+/// render the ~30 that fit. Each `Span` owns its text, so those clones are+/// allocations, on every frame a streaming pane produces.pub fn compute_visible_lines<'a>(- styled_lines: Vec<Line<'a>>,+ styled_lines: &[Line<'a>],visible_height: usize,scroll_offset: i32,) -> (Vec<Line<'a>>, usize, usize) {@@ -138,10 +161,11 @@ pub fn compute_visible_lines<'a>(};let visible_lines: Vec<Line<'a>> = styled_lines- .into_iter()+ .iter().take(effective_line_count).skip(start_line).take(visible_height)+ .cloned().collect();(visible_lines, start_line, total_lines)@@ -167,9 +191,7 @@ fn build_footer_text_for_mode(// 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"- );+ return format!("[C-d/u] scroll [C-g] bottom Β· [C-f] {view_action} [C-q] close");}if scroll_offset < 0 {format!(@@ -333,7 +355,7 @@ pub fn render_shell_popup(popup: &ShellPopup,frame: &mut Frame,popup_area: Rect,- styled_lines: Vec<Line<'_>>,+ styled_lines: &[Line<'_>],colors: &ShellPopupColors,) {frame.render_widget(Clear, popup_area);diff --git a/tests/shell_popup_tests.rs b/tests/shell_popup_tests.rsindex 641763f..492ab03 100644--- a/tests/shell_popup_tests.rs+++ b/tests/shell_popup_tests.rs@@ -3,9 +3,9 @@ use agtx::tui::shell_popup::{trim_trailing_empty_lines, ShellPopup, ShellPopupColors, MAX_TRAILING_EMPTY_LINES,};use ratatui::backend::TestBackend;-use std::time::{Duration, Instant};use ratatui::prelude::*;use ratatui::Terminal;+use std::time::{Duration, Instant};#[test]fn test_shell_popup_new() {@@ -101,7 +101,7 @@ fn test_shell_popup_is_at_bottom() {#[test]fn test_compute_visible_lines_empty() {let lines: Vec<Line> = vec![];- let (visible, start, total) = compute_visible_lines(lines, 10, 0);+ let (visible, start, total) = compute_visible_lines(&lines, 10, 0);assert!(visible.is_empty());assert_eq!(start, 0);@@ -115,7 +115,7 @@ fn test_compute_visible_lines_fewer_than_height() {Line::from("line 2"),Line::from("line 3"),];- let (visible, start, total) = compute_visible_lines(lines, 10, 0);+ let (visible, start, total) = compute_visible_lines(&lines, 10, 0);assert_eq!(visible.len(), 3);assert_eq!(start, 0);@@ -126,7 +126,7 @@ fn test_compute_visible_lines_fewer_than_height() {fn test_compute_visible_lines_exact_height() {let lines: Vec<Line> = (0..10).map(|i| Line::from(format!("line {}", i))).collect();- let (visible, start, total) = compute_visible_lines(lines, 10, 0);+ let (visible, start, total) = compute_visible_lines(&lines, 10, 0);assert_eq!(visible.len(), 10);assert_eq!(start, 0);@@ -138,7 +138,7 @@ fn test_compute_visible_lines_scrolled_up() {let lines: Vec<Line> = (0..20).map(|i| Line::from(format!("line {}", i))).collect();// Visible height 10, scrolled up by 5 lines- let (visible, start, total) = compute_visible_lines(lines, 10, -5);+ let (visible, start, total) = compute_visible_lines(&lines, 10, -5);assert_eq!(visible.len(), 10);assert_eq!(start, 5); // 20 - 10 - 5 = 5@@ -149,7 +149,7 @@ fn test_compute_visible_lines_scrolled_up() {fn test_compute_visible_lines_at_bottom() {let lines: Vec<Line> = (0..20).map(|i| Line::from(format!("line {}", i))).collect();- let (visible, start, total) = compute_visible_lines(lines, 10, 0);+ let (visible, start, total) = compute_visible_lines(&lines, 10, 0);assert_eq!(visible.len(), 10);assert_eq!(start, 10); // Shows last 10 lines@@ -165,7 +165,7 @@ fn test_compute_visible_lines_keeps_trailing_empty_at_bottom() {lines.push(Line::from(""));// At bottom (scroll_offset = 0) - should keep trailing empty lines- let (_visible, _start, total) = compute_visible_lines(lines, 20, 0);+ let (_visible, _start, total) = compute_visible_lines(&lines, 20, 0);assert_eq!(total, 13); // Keeps all lines including trailing empty}@@ -179,7 +179,7 @@ fn test_compute_visible_lines_strips_trailing_empty_when_scrolled() {lines.push(Line::from(""));// Scrolled up (scroll_offset < 0) - should trim trailing empty for cleaner history- let (_visible, _start, total) = compute_visible_lines(lines, 20, -5);+ let (_visible, _start, total) = compute_visible_lines(&lines, 20, -5);assert_eq!(total, 10); // Trims trailing empty when scrolled up}@@ -189,7 +189,7 @@ fn test_compute_visible_lines_scrolled_to_top() {let lines: Vec<Line> = (0..30).map(|i| Line::from(format!("line {}", i))).collect();// Scroll up enough to be at top- let (visible, start, total) = compute_visible_lines(lines, 10, -20);+ let (visible, start, total) = compute_visible_lines(&lines, 10, -20);assert_eq!(visible.len(), 10);assert_eq!(start, 0); // At the very top@@ -226,7 +226,7 @@ fn agent_managed_history_is_described_by_actions_not_implementation() {&popup,frame,Rect::new(0, 0, 100, 24),- vec![],+ &[],&ShellPopupColors::default(),);})@@ -272,7 +272,7 @@ fn test_fullscreen_footer_offers_windowed_toggle() {&popup,frame,Rect::new(0, 0, 80, 24),- vec![],+ &[],&ShellPopupColors::default(),);})@@ -307,7 +307,7 @@ fn test_render_shell_popup_basic() {terminal.draw(|frame| {let area = Rect::new(0, 0, 80, 24);- render_shell_popup(&popup, frame, area, lines, &colors);+ render_shell_popup(&popup, frame, area, &lines, &colors);}).unwrap();@@ -338,7 +338,7 @@ fn test_render_shell_popup_with_content() {terminal.draw(|frame| {let area = Rect::new(0, 0, 80, 24);- render_shell_popup(&popup, frame, area, lines, &colors);+ render_shell_popup(&popup, frame, area, &lines, &colors);}).unwrap();@@ -365,7 +365,7 @@ fn test_render_shell_popup_scrolled_up() {terminal.draw(|frame| {let area = Rect::new(0, 0, 80, 24);- render_shell_popup(&popup, frame, area, lines, &colors);+ render_shell_popup(&popup, frame, area, &lines, &colors);}).unwrap();@@ -390,7 +390,7 @@ fn test_render_shell_popup_empty_content() {terminal.draw(|frame| {let area = Rect::new(0, 0, 80, 24);- render_shell_popup(&popup, frame, area, lines, &colors);+ render_shell_popup(&popup, frame, area, &lines, &colors);}).unwrap();@@ -424,7 +424,7 @@ fn test_render_shell_popup_custom_colors() {terminal.draw(|frame| {let area = Rect::new(0, 0, 80, 24);- render_shell_popup(&popup, frame, area, lines, &colors);+ render_shell_popup(&popup, frame, area, &lines, &colors);}).unwrap();@@ -446,7 +446,7 @@ fn test_render_shell_popup_small_area() {terminal.draw(|frame| {let area = Rect::new(0, 0, 40, 10);- render_shell_popup(&popup, frame, area, lines, &colors);+ render_shell_popup(&popup, frame, area, &lines, &colors);}).unwrap();diff --git a/tests/tmux_control_tests.rs b/tests/tmux_control_tests.rsindex e6576f4..4aab293 100644--- a/tests/tmux_control_tests.rs+++ b/tests/tmux_control_tests.rs@@ -20,10 +20,11 @@//! 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 agtx::tmux::{CaptureSpec, TmuxOperations};use anyhow::Result;use std::process::Command;-use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};/// Skip guard. Returns the reason, so a skipped test names itself.@@ -116,6 +117,12 @@ impl Server {.unwrap_or(0)}+ fn client_count(&self) -> usize {+ self.tmux(&["list-clients", "-F", "#{client_name}"])+ .map(|s| s.lines().filter(|l| !l.trim().is_empty()).count())+ .unwrap_or(0)+ }+fn pane_size(&self, target: &str) -> String {self.tmux(&["display",@@ -177,8 +184,32 @@ impl TmuxOperations for TestTmuxOps {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 pane_id(&self, target: &str) -> Option<String> {+ let out = Command::new("tmux")+ .args(["-L", &self.server])+ .args(["display", "-p", "-t", target, "#{pane_id}"])+ .output()+ .ok()?;+ let id = String::from_utf8_lossy(&out.stdout).trim().to_string();+ (!id.is_empty()).then_some(id)+ }+ fn list_window_targets(&self) -> Result<Vec<String>> {+ let out = Command::new("tmux")+ .args(["-L", &self.server])+ .args(["list-windows", "-a", "-F", "#{session_name}:#{window_name}"])+ .output()?;+ Ok(String::from_utf8_lossy(&out.stdout)+ .lines()+ .map(str::to_string)+ .collect())+ }+ fn window_exists(&self, target: &str) -> Result<bool> {+ Ok(Command::new("tmux")+ .args(["-L", &self.server])+ .args(["list-windows", "-t", target])+ .output()?+ .status+ .success())}fn send_keys(&self, target: &str, keys: &str) -> Result<()> {self.run(&["send-keys", "-t", target, keys]);@@ -206,14 +237,41 @@ impl TmuxOperations for TestTmuxOps {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(&self, target: &str) -> Result<String> {+ let out = Command::new("tmux")+ .args(["-L", &self.server])+ .args(["capture-pane", "-t", target, "-p"])+ .output()?;+ Ok(String::from_utf8_lossy(&out.stdout).to_string())}- fn capture_pane_with_history(&self, _target: &str, _history_lines: i32) -> Vec<u8> {- unimplemented!("not used by the input broker")+ /// The subprocess capture path, verbatim from `RealTmuxOps` but on the+ /// test server's socket. It is the reference the control capture is+ /// compared against, so it must not be a simplification of it.+ fn capture_pane_with_history(&self, target: &str, history_lines: i32) -> Vec<u8> {+ Command::new("tmux")+ .args(["-L", &self.server])+ .args(["capture-pane", "-t", target, "-p", "-e"])+ .args(["-S", &format!("-{history_lines}")])+ .output()+ .map(|o| o.stdout)+ .unwrap_or_default()}- fn pane_metrics(&self, _target: &str) -> Option<agtx::tmux::PaneMetrics> {- None+ fn pane_metrics(&self, target: &str) -> Option<agtx::tmux::PaneMetrics> {+ let out = Command::new("tmux")+ .args(["-L", &self.server])+ .args([+ "display",+ "-p",+ "-t",+ target,+ agtx::tmux::PANE_METRICS_FORMAT,+ ])+ .output()+ .ok()?;+ if !out.status.success() {+ return None;+ }+ agtx::tmux::parse_pane_metrics(&String::from_utf8_lossy(&out.stdout))}fn resize_window(&self, _target: &str, _width: u16, _height: u16) -> Result<()> {unimplemented!("not used by the input broker")@@ -525,6 +583,406 @@ fn the_subprocess_backend_delivers_the_same_bytes() {assert_eq!(settle(&server, "subproc"), b"abc\x1b[DX\n".to_vec());}+// --- reading the pane back over the same connection ---++/// A pane painted with known text, captured both ways, must come back+/// **byte-identical**.+///+/// The two paths parse different things β one reads a process's stdout, the+/// other reassembles `%begin`/`%end` payload lines β and the popup renders the+/// result through an ANSI parser that will happily draw a subtly wrong frame+/// without failing. Only a byte comparison catches a dropped trailing newline,+/// a mangled escape or a lost blank row.+#[test]+fn a_control_capture_is_byte_identical_to_the_subprocess_one() {+ guard!();+ let server = Server::start("capture");+ // A plain shell, not a recording window: this test needs a pane with+ // *content on screen*, which is what a capture reads.+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "cap", "cat"])+ .expect("create the capture window");+ std::thread::sleep(Duration::from_millis(300));+ let target = "it:cap";+ // Colour, a blank line, a trailing space and a line that looks like a+ // control-mode tag β the payload shapes that could each break framing.+ server+ .tmux(&[+ "send-keys",+ "-t",+ target,+ "-l",+ "plain\n\x1b[31mred\x1b[0m\n\n%end 1 7 0\ntrailing \n",+ ])+ .expect("paint the pane");+ std::thread::sleep(Duration::from_millis(300));++ let ops = TestTmuxOps {+ server: server.name.clone(),+ };+ let expected_content = ops.capture_pane_with_history(target, 500);+ let expected_metrics = ops.pane_metrics(target);++ let sink = sink_for(&server, true);+ let snapshot = sink+ .capture(target, CaptureSpec::popup(500))+ .expect("the control connection served the capture");+ sink.shutdown();++ assert_eq!(+ String::from_utf8_lossy(&snapshot.content),+ String::from_utf8_lossy(&expected_content),+ "the two capture paths disagree about the pane"+ );+ assert_eq!(+ snapshot.metrics, expected_metrics,+ "the two metrics paths disagree about the pane geometry"+ );+ assert!(+ snapshot.content.windows(10).any(|w| w == b"%end 1 7 0"),+ "the tag-shaped line was lost, so framing closed the block early"+ );+}++/// A `CaptureSpec::text()` capture must be **byte-identical** to+/// `TmuxOperations::capture_pane`.+///+/// The status refresh matches trust dialogs and hashes pane content against+/// these bytes. An `-e` left on would embed SGR escapes through the middle of a+/// dialog's wording, so the match would fail and the task would sit at "working"+/// forever with nobody told a decision was waiting β silent, and exactly the+/// class of bug the popup's byte-identity test was written for.+#[test]+fn a_text_capture_matches_the_subprocess_capture_pane() {+ guard!();+ let server = Server::start("captext");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "cap", "cat"])+ .expect("create the capture window");+ std::thread::sleep(Duration::from_millis(300));+ let target = "it:cap";+ server+ .tmux(&[+ "send-keys",+ "-t",+ target,+ "-l",+ "plain\n\x1b[31mDo you trust the files in this folder?\x1b[0m\n",+ ])+ .expect("paint the pane");+ std::thread::sleep(Duration::from_millis(300));++ let ops = TestTmuxOps {+ server: server.name.clone(),+ };+ let expected = ops.capture_pane(target).expect("subprocess capture");++ let sink = sink_for(&server, true);+ let snapshot = sink+ .capture(target, CaptureSpec::text())+ .expect("the control connection served the capture");+ sink.shutdown();++ let got = String::from_utf8_lossy(&snapshot.content).into_owned();+ assert_eq!(got, expected, "the two text-capture paths disagree");+ assert!(+ !got.contains('\u{1b}'),+ "a text capture must carry no escapes: {got:?}"+ );+ assert!(+ got.contains("Do you trust the files in this folder?"),+ "the dialog wording must survive intact for the matcher"+ );+ assert_eq!(+ snapshot.metrics, None,+ "a text capture skips the second command"+ );+}++/// One listing answers `window_exists` for every task on the board.+#[test]+fn the_window_listing_names_every_window_as_session_colon_window() {+ guard!();+ let server = Server::start("winlist");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "alpha", "cat"])+ .expect("create a window");+ std::thread::sleep(Duration::from_millis(200));+ let ops = TestTmuxOps {+ server: server.name.clone(),+ };+ let targets = ops.list_window_targets().expect("listing");+ assert!(+ targets.iter().any(|t| t == "it:alpha"),+ "the listing must use the same `session:window` form task.session_name holds: {targets:?}"+ );+ // What the refresh actually asks of it.+ assert!(ops.window_exists("it:alpha").unwrap_or(false));+ assert!(!targets.iter().any(|t| t == "it:missing"));+}++/// With control mode off there is no connection to serve a capture, and the+/// broker must say so rather than running the subprocess itself β the caller+/// owns that path, and paying for it here would block the next keystroke.+#[test]+fn a_capture_is_declined_when_control_mode_is_off() {+ guard!();+ let server = Server::start("nocapture");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "cap", "cat"])+ .expect("create the capture window");+ std::thread::sleep(Duration::from_millis(300));+ let sink = sink_for(&server, false);+ assert!(sink.capture("it:cap", CaptureSpec::popup(500)).is_none());+ sink.shutdown();+}++/// The number this change was made for: a capture over the input connection+/// against the two `tmux` processes it replaces.+#[test]+fn a_control_capture_beats_two_tmux_processes() {+ guard!();+ let server = Server::start("capbench");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "cap", "cat"])+ .expect("create the capture window");+ std::thread::sleep(Duration::from_millis(300));+ let target = "it:cap";+ let samples = 50;++ let ops = TestTmuxOps {+ server: server.name.clone(),+ };+ let mut subprocess = Vec::with_capacity(samples);+ for _ in 0..samples {+ let started = Instant::now();+ let _ = ops.capture_pane_with_history(target, 500);+ let _ = ops.pane_metrics(target);+ subprocess.push(started.elapsed());+ }++ let sink = sink_for(&server, true);+ // One warm-up: the first capture may pay for the connect.+ let _ = sink.capture(target, CaptureSpec::popup(500));+ let mut control = Vec::with_capacity(samples);+ for _ in 0..samples {+ let started = Instant::now();+ let snapshot = sink.capture(target, CaptureSpec::popup(500));+ control.push(started.elapsed());+ assert!(snapshot.is_some(), "the control capture stopped working");+ }+ sink.shutdown();++ let (sub_p95, ctl_p95) = (p95(subprocess), p95(control));+ eprintln!(+ "capture p95 β two tmux processes {:?}, control connection {:?} ({})",+ sub_p95,+ ctl_p95,+ agtx_tmux_version()+ );+ // Deliberately loose: this asserts the order of magnitude the popup's+ // refresh rate depends on, not a number a loaded CI box has to hit.+ assert!(+ ctl_p95 * 5 < sub_p95,+ "a control capture ({ctl_p95:?}) should be far cheaper than two processes ({sub_p95:?})"+ );+}++/// tmux must tell the **input** connection that a window closed, even though it+/// is attached with `no-output`.+///+/// This is what turns an exited agent into an `Exited` card promptly rather than+/// on the status refresh's next tick, and it costs nothing: the notification+/// arrives on a connection agtx already holds open for keystrokes.+#[test]+fn a_closing_window_is_reported_on_the_input_connection() {+ guard!();+ let server = Server::start("winclose");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "doomed", "cat"])+ .expect("create the window");+ std::thread::sleep(Duration::from_millis(300));++ let flag = Arc::new(AtomicBool::new(false));+ let client =+ agtx::tmux::ControlClient::connect_with(&server.name, "it", 1, Some(Arc::clone(&flag)))+ .expect("attach the control client");+ std::thread::sleep(Duration::from_millis(400));+ // The attach itself must not look like a window closing.+ assert!(!flag.load(Ordering::Relaxed), "attaching raised the flag");++ server+ .tmux(&["kill-window", "-t", "it:doomed"])+ .expect("kill the window");+ let deadline = Instant::now() + Duration::from_secs(3);+ while !flag.load(Ordering::Relaxed) {+ assert!(+ Instant::now() < deadline,+ "a closing window was never reported on the input connection"+ );+ std::thread::sleep(Duration::from_millis(10));+ }+ client.shutdown();+}++// --- %output push: does tmux actually tell us a pane painted? ---++/// The scope assumption the push design rests on, pinned so a tmux upgrade+/// cannot change it in silence: `%output` covers every pane in the **attached**+/// session and no pane outside it.+#[test]+fn output_notifications_cover_the_attached_session_only() {+ guard!();+ let server = Server::start("outscope");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "mine", "cat"])+ .expect("window in the attached session");+ server+ .tmux(&["new-session", "-d", "-s", "other", "-n", "theirs", "cat"])+ .expect("window in another session");+ std::thread::sleep(Duration::from_millis(300));++ let ops = TestTmuxOps {+ server: server.name.clone(),+ };+ let mine = ops.pane_id("it:mine").expect("pane id");+ let theirs = ops.pane_id("other:theirs").expect("pane id");+ assert_ne!(mine, theirs);++ let seen = Arc::new(Mutex::new(Vec::<String>::new()));+ let sink = Arc::clone(&seen);+ let watch = agtx::tmux::OutputWatch::connect(&server.name, "it", move |id| {+ sink.lock().unwrap().push(id.to_string());+ })+ .expect("attach the output watch");+ std::thread::sleep(Duration::from_millis(400));++ server+ .tmux(&["send-keys", "-t", "it:mine", "-l", "painted\n"])+ .expect("paint the watched pane");+ server+ .tmux(&["send-keys", "-t", "other:theirs", "-l", "painted\n"])+ .expect("paint the other session's pane");+ std::thread::sleep(Duration::from_millis(600));++ let ids = seen.lock().unwrap().clone();+ drop(watch);+ assert!(+ ids.iter().any(|id| *id == mine),+ "the attached session's pane must notify: {ids:?}"+ );+ assert!(+ !ids.iter().any(|id| *id == theirs),+ "a pane outside the attached session must not: {ids:?}"+ );+}++/// A pane that paints notifies **promptly** β this is what replaces the timer,+/// so it has to beat one.+#[test]+fn a_paint_notifies_faster_than_the_poll_interval() {+ guard!();+ let server = Server::start("outlat");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "p", "cat"])+ .expect("create the window");+ std::thread::sleep(Duration::from_millis(300));+ let ops = TestTmuxOps {+ server: server.name.clone(),+ };+ let pane = ops.pane_id("it:p").expect("pane id");++ let (tx, rx) = std::sync::mpsc::channel();+ let want = pane.clone();+ let watch = agtx::tmux::OutputWatch::connect(&server.name, "it", move |id| {+ if id == want {+ let _ = tx.send(Instant::now());+ }+ })+ .expect("attach the output watch");+ std::thread::sleep(Duration::from_millis(400));+ while rx.try_recv().is_ok() {}++ let mut samples = Vec::new();+ for i in 0..10 {+ // Drain *per iteration*: one paint produces several `%output` frames, and+ // reading a leftover from the previous round would time an event that+ // happened before the send β which saturates to zero and makes the whole+ // measurement look perfect.+ while rx.try_recv().is_ok() {}+ let started = Instant::now();+ server+ .tmux(&["send-keys", "-t", "it:p", "-l", &format!("x{i}\n")])+ .expect("paint");+ let at = rx+ .recv_timeout(Duration::from_secs(2))+ .expect("a paint must notify");+ samples.push(at.duration_since(started));+ std::thread::sleep(Duration::from_millis(60));+ }+ drop(watch);+ let p95 = p95(samples);+ eprintln!("paint -> %output p95 {p95:?} ({})", agtx_tmux_version());+ // Loose on purpose: the `send-keys` process in front of it costs more than+ // the notification does. It only has to be in a different class from a poll.+ assert!(+ p95 < Duration::from_millis(100),+ "a paint notification should be prompt, got {p95:?}"+ );+}++/// An idle pane must produce **nothing**. This is the property that makes an+/// open popup free, and the one a timer can never have.+#[test]+fn an_idle_pane_notifies_nothing() {+ guard!();+ let server = Server::start("outidle");+ server+ .tmux(&["new-window", "-d", "-t", "it:", "-n", "quiet", "cat"])+ .expect("create the window");+ std::thread::sleep(Duration::from_millis(400));++ let count = Arc::new(AtomicUsize::new(0));+ let seen = Arc::clone(&count);+ let watch = agtx::tmux::OutputWatch::connect(&server.name, "it", move |_| {+ seen.fetch_add(1, Ordering::Relaxed);+ })+ .expect("attach the output watch");+ // Let the attach settle: a client attaching makes tmux repaint.+ std::thread::sleep(Duration::from_millis(700));+ count.store(0, Ordering::Relaxed);+ std::thread::sleep(Duration::from_secs(2));+ let n = count.load(Ordering::Relaxed);+ drop(watch);+ assert_eq!(n, 0, "an idle pane produced {n} notifications");+}++/// Dropping the watch must close the tmux client. Left running it would mirror+/// the whole session's output for the life of the server, which is the cost the+/// dedicated-client design exists to avoid paying while no popup is open.+#[test]+fn dropping_the_watch_closes_its_client() {+ guard!();+ let server = Server::start("outdrop");+ std::thread::sleep(Duration::from_millis(200));+ let before = server.client_count();+ let watch = agtx::tmux::OutputWatch::connect(&server.name, "it", |_| {})+ .expect("attach the output watch");+ std::thread::sleep(Duration::from_millis(400));+ assert_eq!(+ server.client_count(),+ before + 1,+ "the watch did not attach"+ );+ drop(watch);+ std::thread::sleep(Duration::from_millis(600));+ assert_eq!(+ server.client_count(),+ before,+ "the watch client outlived the watch"+ );+}+// --- the measurement the whole change exists for ---#[test]