agentmux_srv_core/backend/blockcontroller/shell/lifecycle.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The `impl Controller for ShellController` block: start/stop/send_input/
5//! get_runtime_status. Kept whole in one file (a trait impl cannot be split
6//! across modules); it orchestrates the helpers extracted into the sibling
7//! `pty`, `file_ops`, and `translation` modules.
8
9use std::sync::Arc;
10
11#[cfg(unix)]
12use libc;
13
14use portable_pty::CommandBuilder;
15use tokio::sync::mpsc;
16
17use super::super::{
18 BlockControllerRuntimeStatus, BlockInputUnion, Controller, META_KEY_CMD_ENV, STATUS_DONE,
19};
20#[cfg(unix)]
21use super::controller::KILL_GRACE_SECS;
22use super::controller::{ShellController, SHELL_INPUT_CH_SIZE};
23use super::file_ops::handle_append_block_file;
24use super::pty::{PTY_CHANNEL_CAPACITY, PTY_COALESCE_MAX_BYTES};
25use super::spawn_command::SpawnPlan;
26use super::start_steps::{is_agent_pane, program_name, RemotePlan};
27use super::wait_task::ExitParts;
28use super::translation::accumulate_and_translate;
29use crate::backend::obj::{self, MetaMapType};
30use crate::backend::mps;
31
32/// One PTY read's worth of already-OSC-cleaned output, on its way from the
33/// blocking read loop to the coalescing flusher (`start()`, below). See
34/// docs/reports/REPORT_RENDERER_CPU_UNBATCHED_PTY_OUTPUT_2026_09_11.md.
35pub(super) struct PtyReadChunk {
36 pub(super) data: Vec<u8>,
37 pub(super) osc_events: Vec<crate::backend::osc_extractor::OscEvent>,
38 /// Flush barrier. When set, the flusher signals it AFTER committing the
39 /// batch this chunk lands in — so a sender that enqueues a barrier and
40 /// awaits it knows everything queued before it has reached the FileStore
41 /// and the broker.
42 ///
43 /// Exists because "the flusher task ended" is NOT a usable completion
44 /// signal on Windows: ConPTY's console host outlives the direct child, so
45 /// the read loop never sees EOF, never drops its sender, and the channel
46 /// never closes. Waiting on the task therefore always burned the full
47 /// `FLUSHER_DRAIN_TIMEOUT` (see its doc comment) even though the flusher
48 /// itself had been idle for most of that second. A barrier asks the
49 /// question actually being asked — "is prior output committed yet?" —
50 /// and is answered as soon as the batch it lands in commits.
51 pub(super) ack: Option<tokio::sync::oneshot::Sender<()>>,
52}
53
54/// Do the actual per-batch work the read loop used to do per-read: write
55/// through to the FileStore, broadcast the raw bytes, publish any OSC
56/// activity, and (for agent panes) feed the JSON-stream translator. Called
57/// once per coalesced batch instead of once per (up to 4KB) PTY read.
58#[allow(clippy::too_many_arguments)]
59fn flush_pty_batch(
60 broker: &mps::Broker,
61 block_id: &str,
62 data: &[u8],
63 osc_events: &[crate::backend::osc_extractor::OscEvent],
64 filestore: Option<&Arc<crate::backend::storage::filestore::FileStore>>,
65 line_buf: &mut Vec<u8>,
66 translator: Option<&mut crate::agents::translator::claude::ClaudeTranslator>,
67) {
68 if data.is_empty() && osc_events.is_empty() {
69 return;
70 }
71
72 handle_append_block_file(
73 broker,
74 block_id,
75 "term",
76 data,
77 // Write-through so scrollback survives a reconnect
78 // (SPEC_TERMINAL_SCROLLBACK_PERSISTENCE_2026_07_23.md
79 // §2.1) — was `None` (raw PTY bytes discarded after
80 // the live broadcast), which meant every `view:"term"`
81 // pane (standalone Terminal panes and the agent-shell
82 // drawer alike) lost all output on remount.
83 filestore,
84 None, // not an agent output stream; no global mirror
85 );
86
87 for ev in osc_events {
88 mps::publish_block_activity(broker, block_id, &ev.payload);
89 }
90
91 if let Some(t) = translator {
92 accumulate_and_translate(broker, block_id, line_buf, data, t);
93 }
94}
95
96/// Drain `rx`, coalescing into batches whatever is already queued at the
97/// moment each batch is assembled — never waiting on output that has not
98/// arrived, and bounded by `PTY_COALESCE_MAX_BYTES` — then flushing each
99/// batch through [`flush_pty_batch`]. Runs until `rx` closes
100/// (the PTY read loop's sender dropped, i.e. the PTY hit EOF or an error),
101/// flushing any final partial batch before returning.
102///
103/// A standalone fn rather than inlined into its `tokio::spawn` call site so
104/// it can be driven directly in a test with a synthetic channel and no real
105/// PTY — see `pty_output_flusher_tests` below.
106pub(super) async fn run_pty_output_flusher(
107 mut rx: mpsc::Receiver<PtyReadChunk>,
108 broker: Option<Arc<mps::Broker>>,
109 block_id: String,
110 filestore: Option<Arc<crate::backend::storage::filestore::FileStore>>,
111 is_agent: bool,
112) {
113 let Some(broker) = broker else {
114 // No broker means the read loop's sender never had anything worth
115 // sending (see its own `broker_read.is_some()` gate) — nothing to
116 // drain or flush.
117 return;
118 };
119 // Phase 1.5 PR 1 (additive): if this is an agent pane, also try to
120 // interpret stdout as Claude Code stream-json line-by-line, feeding
121 // successful parses through ClaudeTranslator and emitting AgentEvents
122 // on a new MPS scope `agent_event:<block_id>`. The existing raw-chunk
123 // path stays byte-equal — interactive panes (which don't emit JSON) see
124 // no behavior change because every line fails the JSON parse and is
125 // silently dropped. The future stream-json-mode pane and the drone
126 // inspector (issue #830 / Phase 1.5 PR 3) will be the first real
127 // consumers.
128 let mut translator: Option<crate::agents::translator::claude::ClaudeTranslator> = if is_agent
129 {
130 Some(crate::agents::translator::claude::ClaudeTranslator::new())
131 } else {
132 None
133 };
134 // Per-block line-buffer (raw bytes — see `extract_agent_events`). Capped
135 // to AGENT_LINE_BUFFER_CAP so a producer that never emits a newline
136 // can't grow the buffer unboundedly.
137 let mut line_buf: Vec<u8> = Vec::new();
138
139 loop {
140 let Some(first) = rx.recv().await else {
141 break; // channel closed, nothing pending
142 };
143 let mut batch = first.data;
144 let mut batch_osc = first.osc_events;
145 // Barriers collected into THIS batch. A barrier ends accumulation as
146 // soon as it is seen (below): everything already in `batch` is about
147 // to be flushed, and holding the batch open for the rest of the
148 // coalescing window would delay the ack for no benefit.
149 let mut batch_acks: Vec<tokio::sync::oneshot::Sender<()>> = Vec::new();
150 if let Some(ack) = first.ack {
151 batch_acks.push(ack);
152 }
153 // Drain what is ALREADY queued into this batch, and nothing more —
154 // never wait for output that has not arrived yet.
155 //
156 // This previously waited up to a fixed 20ms window for more chunks.
157 // That is application-layer Nagle, and it sat directly on the
158 // keystroke echo path: typing one character into an otherwise idle
159 // pane produces exactly one chunk, so the window could never be
160 // satisfied early and the echo paid the full 20ms — longer than a
161 // 60Hz frame — before it was ever broadcast. It is the same mistake
162 // SPEC_TERM_DOUBLE_RAF_TEAROUT_2026_05_30 removed from the frontend
163 // (a second frame gate on the echo path, symptom: "not silky"
164 // hiccups); that spec's own prescription for a backend version was a
165 // ~2-4ms merge of consecutive reads, not a 20ms wait.
166 //
167 // Dropping the wait costs no batching, because batching here is
168 // self-tuning without it: a flush takes real time (SQLite write +
169 // broadcast, on spawn_blocking), and everything the producer writes
170 // while that flush is in flight queues up behind it. So the busier
171 // the pane the bigger the next batch — which is exactly the burst
172 // case REPORT_RENDERER_CPU_UNBATCHED_PTY_OUTPUT_2026_09_11.md
173 // measured — while an idle pane, where there is nothing to coalesce
174 // in the first place, now pays nothing to find that out.
175 let closed_mid_batch = loop {
176 if batch.len() >= PTY_COALESCE_MAX_BYTES {
177 break false;
178 }
179 match rx.try_recv() {
180 Ok(next) => {
181 batch.extend_from_slice(&next.data);
182 batch_osc.extend(next.osc_events);
183 if let Some(ack) = next.ack {
184 batch_acks.push(ack);
185 break false; // flush now; someone is waiting on it
186 }
187 }
188 // Nothing more queued — flush immediately rather than
189 // waiting to see whether something shows up.
190 Err(mpsc::error::TryRecvError::Empty) => break false,
191 Err(mpsc::error::TryRecvError::Disconnected) => break true,
192 }
193 };
194
195 // spawn_blocking, not block_in_place (reagentx P2 on PR #3206,
196 // correcting the round before it): flush_pty_batch does blocking
197 // SQLite I/O and takes std::sync::Mutex locks, so it must not run
198 // on a Tokio async worker directly — this closure is inside a
199 // plain `tokio::spawn`, not `spawn_blocking`. The first fix for
200 // that reached for `block_in_place` specifically to avoid moving
201 // `&mut line_buf`/`translator.as_mut()` across a 'static+Send
202 // boundary — but `block_in_place` gets its own replacement worker
203 // via THE SAME shared `spawn_blocking` pool internally (verified
204 // directly against the vendored tokio 1.52.3 source,
205 // `runtime/scheduler/multi_thread/worker.rs`'s `block_in_place`: (comment-hygiene: allow)
206 // `runtime::spawn_blocking(move || run(worker))`), so per flush it
207 // draws on that shared pool TWICE — once for the replacement
208 // worker, once implicitly for the original thread's own blocking
209 // — for work `spawn_blocking` alone would cover with one. Tokio's
210 // own docs single out `block_in_place`'s one real advantage
211 // (protecting OTHER concurrent work in the SAME task, e.g. across
212 // a `join!`) as the reason to prefer it over `spawn_blocking` —
213 // this task does nothing else concurrently, so that advantage
214 // never applies here, and `spawn_blocking` is strictly the better
215 // fit. The ownership problem is solved properly instead: `batch`/
216 // `batch_osc` are freshly built each iteration (cheap to move),
217 // and `line_buf`/`translator` — the only state the flush actually
218 // MUTATES — are moved into the closure and handed back out via the
219 // `JoinHandle`'s return value, rather than trying to keep them
220 // borrowed across the call.
221 let broker_owned = broker.clone();
222 let block_id_owned = block_id.clone();
223 let filestore_owned = filestore.clone();
224 let (new_line_buf, new_translator) = tokio::task::spawn_blocking(move || {
225 flush_pty_batch(
226 &broker_owned,
227 &block_id_owned,
228 &batch,
229 &batch_osc,
230 filestore_owned.as_ref(),
231 &mut line_buf,
232 translator.as_mut(),
233 );
234 (line_buf, translator)
235 })
236 .await
237 .expect("PTY output flush task panicked");
238
239 // Everything enqueued up to and including the barrier is now
240 // committed. A dropped receiver (the waiter timed out and moved on)
241 // is fine — that is the bounded-wait path doing its job.
242 for ack in batch_acks {
243 let _ = ack.send(());
244 }
245 line_buf = new_line_buf;
246 translator = new_translator;
247
248 if closed_mid_batch {
249 break;
250 }
251 }
252}
253
254/// Resolve the effective AGENTMUX_AGENT_ID for jekt auto-registration from a
255/// block's own spawn metadata — both the canonical key and the legacy
256/// WAVEMUX_AGENT_ID alias, checked in the SAME block-scoped `cmd:env` map.
257/// Deliberately does NOT fall back to `std::env::var` for either key: that
258/// reads THIS SRV PROCESS's own environment, shared by every block/pane
259/// this instance spawns — reintroducing exactly the same collision as the
260/// global-settings fallback below (#2694). Nor does it
261/// fall back to the global settings' cmd_env.AGENTMUX_AGENT_ID: that value
262/// is shared across every pane in the instance/channel, so a pane spawned
263/// without its own explicit per-block ID would silently inherit whatever
264/// another pane happened to configure there — and register_agent_with_nonce
265/// unconditionally evicts whoever previously held that agent_key, so the
266/// second such pane to register silently steals the first's jekt identity
267/// (same-host cross-instance jekt misdelivery). See `cmd_env_overrides` below
268/// (its `settings.cmd_env` loop) for the matching fix that keeps
269/// this global value out of the pane's OWN environment too — otherwise a
270/// pane could still pick it up via OSC 16162 and re-register through the
271/// frontend's `/agentmux/reactive/register` path instead, even with THIS
272/// function never reading it directly. A pane with
273/// no block-scoped identity is simply not jekt-registered, matching
274/// persistent/mod.rs's muxbus_agent_id_from_env, which never had either fallback.
275fn resolve_agent_id_for_jekt(block_meta: &MetaMapType) -> Option<String> {
276 let cmd_env = block_meta.get(META_KEY_CMD_ENV).and_then(|m| m.as_object());
277 crate::backend::blockcontroller::agent_id_from_env(|key| {
278 cmd_env.and_then(|obj| obj.get(key)).and_then(|v| v.as_str())
279 })
280}
281
282/// Whether `key` may be injected into a pane's actual OS environment from
283/// the global settings' `cmd_env` defaults (`cmd_env_overrides`, lowest
284/// priority — the block's own `cmd:env` override, highest
285/// priority, is never filtered by this and can always set either key
286/// explicitly). Identity keys are excluded (reagentx P1, round 2 on #2694):
287/// without this, a global cmd_env.AGENTMUX_AGENT_ID setting would still land
288/// in every pane's real environment even though `resolve_agent_id_for_jekt`
289/// never reads it for registration — shell integration echoes an injected
290/// AGENTMUX_AGENT_ID back via OSC 16162, and the frontend's own
291/// `POST /agentmux/reactive/register` path (triggered by that OSC) would
292/// pick it up and register the pane under the shared value anyway, silently
293/// reopening the same-host identity collision this PR removes from the
294/// backend auto-register path specifically.
295fn is_global_cmd_env_injectable(key: &str) -> bool {
296 !matches!(key, "AGENTMUX_AGENT_ID" | "WAVEMUX_AGENT_ID")
297}
298
299/// The `cmd:env` part of an interactive shell's environment, computed from
300/// the global settings and the block's own metadata. See
301/// [`cmd_env_overrides`].
302#[derive(Debug)]
303pub(super) struct CmdEnvOverrides {
304 /// `(key, value)` pairs in application order: global settings first,
305 /// block metadata last. Applied one by one, so a later entry for the same
306 /// key wins. Kept as a list rather than merged into a map because
307 /// `CommandBuilder` matches env keys case-insensitively on Windows: a
308 /// block's `PATH` must still override a global `Path`.
309 pub(super) vars: Vec<(String, String)>,
310 /// Whether the block's own `cmd:env` sets `AGENTMUX_AGENT_ID`. When it
311 /// does not, the inherited agent-identity vars are stripped.
312 block_sets_agent_id: bool,
313}
314
315impl CmdEnvOverrides {
316 pub(super) fn apply_to(&self, c: &mut CommandBuilder) {
317 for (k, v) in &self.vars {
318 c.env(k, v);
319 }
320 // Strip host-inherited agent identity unless the block's own cmd:env
321 // sets it. (Global settings never can: `is_global_cmd_env_injectable`.)
322 // This also supersedes the old WAVEMUX backward-compat bridge — both
323 // AGENTMUX_* and WAVEMUX_* vars are removed so new panes start as
324 // plain "Terminal".
325 if !self.block_sets_agent_id {
326 c.env_remove("AGENTMUX_AGENT_ID");
327 c.env_remove("WAVEMUX_AGENT_ID");
328 c.env_remove("WAVEMUX_AGENT_COLOR");
329 }
330 }
331}
332
333/// Compute an interactive shell's `cmd:env` overrides.
334///
335/// Precedence, lowest to highest:
336/// 1. `settings.cmd_env`, the global `cmd:env` from settings.json, minus the
337/// identity keys `is_global_cmd_env_injectable` excludes.
338/// 2. The block's own `cmd:env` metadata.
339///
340/// Values get `~` expanded. `settings` must come from the live config
341/// ([`ShellController::live_settings`]). The spawn once read a freshly built
342/// default config instead, whose `cmd_env` is always empty, so the global
343/// setting never reached any shell.
344pub(super) fn cmd_env_overrides(
345 settings: &crate::backend::wconfig::SettingsType,
346 block_meta: &MetaMapType,
347) -> CmdEnvOverrides {
348 let mut vars = Vec::new();
349 let mut block_sets_agent_id = false;
350
351 // Global defaults.
352 for (k, v) in &settings.cmd_env {
353 if !is_global_cmd_env_injectable(k) {
354 continue;
355 }
356 let expanded = crate::backend::base::expand_home_dir_safe(v);
357 vars.push((k.clone(), expanded.to_string_lossy().into_owned()));
358 }
359
360 // Block metadata (per-block overrides).
361 // Sorted, matching the key order serde_json's map gave before.
362 let mut block_env: Vec<(String, String)> = super::super::cmd_env_of(block_meta).into_iter().collect();
363 block_env.sort();
364 for (k, val) in block_env {
365 if k == "AGENTMUX_AGENT_ID" {
366 block_sets_agent_id = true;
367 }
368 let expanded = crate::backend::base::expand_home_dir_safe(&val);
369 vars.push((k, expanded.to_string_lossy().into_owned()));
370 }
371
372 CmdEnvOverrides { vars, block_sets_agent_id }
373}
374
375impl ShellController {
376 /// Apply `cmd:env` to an interactive shell's command: the live global
377 /// settings, the block's own (an agent's current identity in), the strip.
378 pub(super) fn apply_cmd_env(&self, c: &mut CommandBuilder, block_meta: &MetaMapType) {
379 cmd_env_overrides(&self.live_settings(), &self.with_agent_identity(block_meta)).apply_to(c);
380 }
381
382 /// Ends a start that was refused before anything ran: the pane is done,
383 /// with no exit code, and the controller can be started again.
384 fn refuse_start(&self, message: String) -> Result<(), String> {
385 let mut inner = self.inner.lock().unwrap();
386 Self::set_status(&mut inner, STATUS_DONE);
387 inner.proc_exit_code = -1;
388 inner.input_tx = None;
389 drop(inner);
390 self.unlock_run();
391 Err(message)
392 }
393}
394
395impl Controller for ShellController {
396 fn start(
397 &self,
398 block_meta: MetaMapType,
399 rt_opts: Option<serde_json::Value>,
400 force: bool,
401 ) -> Result<(), String> {
402 crate::backend::mcp_folder_rule::not_refused(&block_meta)?;
403 let cmd_str_preview = Self::get_cmd_str(&block_meta);
404 tracing::info!(
405 block_id = %self.block_id,
406 controller = %self.controller_type,
407 cmd = %cmd_str_preview,
408 interactive = Self::is_interactive(&block_meta),
409 force = force,
410 "block start requested"
411 );
412
413 // Check if we should run
414 if !force && !Self::should_run_on_start(&block_meta) {
415 tracing::info!(block_id = %self.block_id, "skipping start: run_on_start is false");
416 return Ok(());
417 }
418
419 self.check_connection_available(&block_meta)?;
420
421 // Try to acquire run lock
422 if !self.try_lock_run() {
423 return Err("controller is already running".to_string());
424 }
425
426 // Get connection info
427 let conn_name = Self::get_conn_name(&block_meta);
428
429 let input_rx = self.mark_running(&conn_name);
430
431 // The test-only mock connection factory: a synchronous connection, no PTY.
432 if self.conn_factory.lock().unwrap().is_some() {
433 return self.run_mock_connection(conn_name.clone(), &block_meta);
434 }
435
436 let pair = self.open_pty(&rt_opts)?;
437
438 // Determine shell command
439 let cmd_str = Self::get_cmd_str(&block_meta);
440 let cmd_args = Self::get_cmd_args(&block_meta);
441 let interactive = Self::is_interactive(&block_meta);
442
443 // Resolve effective AGENTMUX_AGENT_ID for jekt auto-registration.
444 // See resolve_agent_id_for_jekt's doc comment for why this
445 // deliberately does not fall back to global settings.
446 let agent_id_for_jekt: Option<String> = resolve_agent_id_for_jekt(&block_meta);
447
448 let close_on_exit = self.closes_on_exit(&block_meta);
449 let close_on_exit_delay_ms = Self::close_on_exit_delay_ms(&block_meta);
450
451 let is_agent = is_agent_pane(&cmd_str, agent_id_for_jekt.is_some());
452
453 if is_agent {
454 if let Some(refusal) = self.agent_spawn_refusal(&cmd_str) {
455 return self.refuse_start(refusal);
456 }
457 }
458
459 let RemotePlan { wsl_distro, ssh_plan, askpass_secret, askpass_guard } = self.remote_plan(&conn_name, &block_meta);
460 let container = self.mstore.as_ref().and_then(|s| super::container_pane::container_for(s, &self.block_id));
461 let pane_cwd = obj::meta_get_string(&block_meta, super::super::META_KEY_CMD_CWD, "");
462 let mut cmd = match self.build_command(
463 &block_meta,
464 &SpawnPlan {
465 cmd_str: &cmd_str,
466 cmd_args: &cmd_args,
467 interactive,
468 wsl_distro: wsl_distro.as_deref(),
469 ssh_plan: ssh_plan.as_ref(),
470 askpass_secret: askpass_secret.as_deref(),
471 container: container.as_deref(),
472 pane_cwd: &pane_cwd,
473 },
474 ) {
475 Ok(c) => c,
476 Err(e) => return self.refuse_start(e),
477 };
478
479 self.apply_pane_env(&mut cmd, &block_meta);
480
481 // Working directory: the pane's own, else (a local shell) the user's
482 // home, not srv's own working directory.
483 let remote = wsl_distro.is_some() || ssh_plan.is_some() || container.is_some();
484 let cwd = super::spawn_cwd::spawn_cwd(&pane_cwd, remote);
485 if !cwd.is_empty() && !remote {
486 cmd.cwd(&cwd);
487 }
488
489 let prog_name = program_name(&cmd);
490
491 let mut child = self.spawn_child(&pair, cmd, &cmd_str, is_agent)?;
492
493 let spawn_ts_ms = agentmux_common::time::now_ms();
494 self.record_spawn(child.process_id(), is_agent, &prog_name, agent_id_for_jekt.clone(), spawn_ts_ms);
495
496 // Re-publish now that the spawn metadata exists. The `running` status
497 // above goes out BEFORE the PTY child is created, so it carries no
498 // pid, program name or spawn time, and nothing else publishes until
499 // the process exits — a subscriber would show a running shell as an
500 // anonymous one for its whole life (Codex P1 on #3436). `persist: 1`
501 // means this snapshot is also what a later subscriber gets replayed.
502 self.publish_status();
503
504 // Auto-register with jekt if AGENTMUX_AGENT_ID was set in the block env, so jekt can deliver
505 // to this PTY without a separate register call.
506 if let Some(ref agent_id) = agent_id_for_jekt {
507 self.register_agent_with_jekt(agent_id);
508 }
509 self.seed_cmd_cwd(&cwd, remote);
510
511 let (reader, writer) = self.take_pty_io(&pair, &mut child)?;
512
513 let (flusher_handle, barrier_tx) = self.start_output(reader, is_agent);
514
515 // Spawn input task (routes input channel → PTY writer + resize + signals)
516 // Owns writer and master — dropping them closes the PTY, causing child to exit.
517 let master = pair.master;
518 super::pty_tasks::spawn_input_task(writer, master, input_rx);
519
520 // The exit watcher reaps the child and tears the pane down (`wait_task`).
521 // An SSH pane holds its connection open from here to its end (ssh_pane); counted only
522 // now, after every step that can still fail and return, so each start has exactly one end.
523 if ssh_plan.is_some() {
524 crate::backend::remote::link::pane_started(&conn_name, false);
525 }
526 self.exit_watch(ExitParts {
527 child,
528 askpass_guard,
529 ssh: ssh_plan.as_ref().map(|(_, dest)| (conn_name.clone(), dest.destination.clone())),
530 agent_id: agent_id_for_jekt.clone(),
531 close_on_exit,
532 close_on_exit_delay_ms,
533 flusher_handle,
534 barrier_tx,
535 })
536 .spawn();
537
538 // Return immediately — PTY tasks run in background
539 Ok(())
540 }
541
542 fn stop(&self, _graceful: bool, new_status: &str) -> Result<(), String> {
543 // Extract what we need from the lock, release it before any async work.
544 #[allow(unused_variables)] // used under #[cfg(unix)] only
545 let pid_to_kill = {
546 let mut inner = self.inner.lock().unwrap();
547 if inner.proc_status == new_status {
548 return Ok(());
549 }
550 let pid = inner.child_pid;
551 // Drop the input channel — closes PTY writer → delivers EOF/SIGHUP as
552 // belt-and-suspenders in case signal delivery fails on the platform.
553 inner.input_tx = None;
554 Self::set_status(&mut inner, new_status);
555 pid
556 };
557
558 // Send SIGTERM to the process group so that child processes spawned by
559 // the shell (e.g. `claude --dangerously-skip-permissions` and its subtree)
560 // are also signalled. Negative pid targets the whole process group.
561 // Schedule SIGKILL after KILL_GRACE_SECS as a backstop for processes
562 // that ignore or delay on SIGTERM.
563 #[cfg(unix)]
564 if let Some(pid) = pid_to_kill {
565 // SAFETY: kill() is a well-defined POSIX syscall.
566 unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGTERM) };
567 tokio::spawn(async move {
568 tokio::time::sleep(tokio::time::Duration::from_secs(KILL_GRACE_SECS)).await;
569 unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) };
570 });
571 }
572
573 // A declared-background descendant (bashwrap, and transitively
574 // whatever it PTY-spawned, e.g. `task dev`) deliberately detaches
575 // into its OWN session at startup (`setsid()` in bash_wrap.rs's
576 // `detach_declared_background_session`), specifically so a
577 // session-RESTART's narrower kill (`stop_for_replace`, above)
578 // can't reach it via PTY-hangup/session-leader-death SIGHUP. But
579 // that same detachment also removes it from THIS process's group
580 // — so the group-wide kill just above (intended to reach it on a
581 // genuine STOP, e.g. pane close) no longer can either. The agent's
582 // tracker reaches it (a cgroup on Linux, the best-effort
583 // `ScanTracker` on macOS and Linux without delegation, by its env
584 // tag), but only when the block's tracker is released; a terminal
585 // block has the no-op stub. This step doesn't wait for either.
586 // Without it, `stop()` (the real,
587 // unmodified deletion path — used by `delete_tab`/`delete_block`/
588 // `wcore::tab`) would leave it running past the stop on Unix (reagentx
589 // finding, PR #2683). Kill each `Running`, known-pid declared-
590 // background task's own (detached) process group explicitly, by
591 // pid from the durable registry — the one piece of state that
592 // still knows about it once it's escaped this controller's own
593 // process tree. Windows is unaffected: Job Object membership
594 // isn't process-group-based, so `delete_controller`'s existing
595 // whole-job close already reaches it there, unchanged.
596 #[cfg(unix)]
597 if let Some(store) = &self.mstore {
598 match store.background_task_list_for_block(&self.block_id) {
599 Ok(tasks) => {
600 for task in tasks {
601 if task.status != crate::backend::storage::background_tasks::BackgroundTaskStatus::Running {
602 continue;
603 }
604 let Some(pid) = task.pid else { continue };
605 let pid = pid as libc::pid_t;
606 // SAFETY: kill() is a well-defined POSIX syscall.
607 unsafe { libc::kill(-pid, libc::SIGTERM) };
608 tokio::spawn(async move {
609 tokio::time::sleep(tokio::time::Duration::from_secs(KILL_GRACE_SECS)).await;
610 unsafe { libc::kill(-pid, libc::SIGKILL) };
611 });
612 }
613 }
614 Err(e) => {
615 tracing::warn!(
616 block_id = %self.block_id,
617 error = %e,
618 "stop(): failed to list declared-background tasks for cleanup",
619 );
620 }
621 }
622 }
623
624 Ok(())
625 }
626
627 fn stop_for_replace(&self, new_status: &str) -> Result<(), String> {
628 // Same extraction as stop() — but the kill below targets ONLY this
629 // one pid, never the process group/job, so a declared-background
630 // descendant (e.g. `task dev`) survives. See
631 // docs/specs/SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md.
632 #[allow(unused_variables)] // used under #[cfg(unix)] only
633 let pid_to_kill = {
634 let mut inner = self.inner.lock().unwrap();
635 if inner.proc_status == new_status {
636 return Ok(());
637 }
638 let pid = inner.child_pid;
639 inner.input_tx = None;
640 Self::set_status(&mut inner, new_status);
641 pid
642 };
643
644 let Some(pid) = pid_to_kill else { return Ok(()) };
645
646 // Prefer the tracked kill (Windows: OpenProcess+TerminateProcess,
647 // with a membership check against the block's job first — see
648 // `process_tracker::registry::kill_pid`). This is expected to
649 // succeed in every real production case: `track_spawned` already
650 // ran for this exact pid right after this controller's own spawn.
651 if let Some(registry) = crate::backend::process_tracker::registry::global() {
652 if registry.kill_pid(&self.block_id, pid) {
653 return Ok(());
654 }
655 }
656
657 // Fallback — reached when the registry global isn't set (tests;
658 // same "silently skip tracker registration" convention
659 // `track_spawned`'s own doc comment describes), OR `kill_pid`
660 // itself returned `false` because this pid isn't (yet, or ever)
661 // a recognized member of the block's tracker — e.g.
662 // `track_spawned`'s own `assign_process` call failed at spawn
663 // time (a real, already-logged non-fatal warning path in
664 // `registry::track_spawned`). Unlike `stop()`, where a failed
665 // direct kill is backstopped by `delete_controller`'s whole-job
666 // teardown, `stop_for_replace` deliberately never touches the
667 // job — so without a fallback here, that failure mode would leak
668 // the old CLI process forever once resync_controller replaces it
669 // (reagentx P1, PR #2683). A direct, single-PID (not group,
670 // not job) kill on both platforms, so this can't reach a
671 // declared-background descendant the way stop()'s `-(pid)` /
672 // a whole-job close would.
673 //
674 // The primary path for a terminal block on Unix, whose tracker is the
675 // no-op stub (`kill_pid` returns `false`). An agent block's tracker
676 // (cgroup, or `ScanTracker` on macOS and Linux without delegation)
677 // SIGKILLs the pid itself and returns `true`.
678 #[cfg(unix)]
679 {
680 // SAFETY: kill() is a well-defined POSIX syscall.
681 unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
682 tokio::spawn(async move {
683 tokio::time::sleep(tokio::time::Duration::from_secs(KILL_GRACE_SECS)).await;
684 unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
685 });
686 }
687 #[cfg(windows)]
688 {
689 // Mirrors process_tracker::windows::JobObjectTracker::kill_pid's
690 // own kill step exactly, minus its job-membership pre-check
691 // (which is precisely what already failed to get us here) —
692 // a plain OpenProcess(PROCESS_TERMINATE) + TerminateProcess on
693 // the raw pid, best-effort (the process may have already
694 // exited on its own).
695 use windows_sys::Win32::Foundation::CloseHandle;
696 use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
697 unsafe {
698 let h = OpenProcess(PROCESS_TERMINATE, 0, pid);
699 if !h.is_null() {
700 let ok = TerminateProcess(h, 1);
701 CloseHandle(h);
702 if ok == 0 {
703 tracing::warn!(
704 block_id = %self.block_id,
705 pid,
706 error = %std::io::Error::last_os_error(),
707 "stop_for_replace: fallback TerminateProcess failed"
708 );
709 }
710 } else {
711 tracing::warn!(
712 block_id = %self.block_id,
713 pid,
714 error = %std::io::Error::last_os_error(),
715 "stop_for_replace: fallback OpenProcess failed — old CLI process may be leaked"
716 );
717 }
718 }
719 }
720
721 Ok(())
722 }
723
724 fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
725 self.get_status_snapshot()
726 }
727
728 fn send_input(&self, input: BlockInputUnion, seq: Option<u64>) -> Result<(), String> {
729 let mut inner = self.inner.lock().unwrap();
730 let tx = match &inner.input_tx {
731 Some(tx) => tx.clone(),
732 None => return Err("controller is not running".to_string()),
733 };
734 match seq {
735 None => tx.send(input).map_err(|e| format!("send_input: {e}")),
736 Some(s) => {
737 // Detect session reset: seq==0 means the TermViewModel
738 // restarted and its per-block counter is back at zero.
739 // (A gap-threshold heuristic was tried and removed — a
740 // stale/duplicate packet far behind could falsely trigger
741 // a reset and replay old input.)
742 if s == 0 && inner.input_seq_next > 0 {
743 tracing::info!(
744 block_id = %self.block_id,
745 prev_next = inner.input_seq_next,
746 new_seq = s,
747 "input seq reset (session reset detected)"
748 );
749 inner.input_seq_next = s;
750 inner.input_seq_buf.clear();
751 }
752
753 let next = inner.input_seq_next;
754 if s == next {
755 // Advance before sending — a send failure must not leave the
756 // backend stuck waiting for a seq the frontend will never resend.
757 inner.input_seq_next += 1;
758 if let Err(e) = tx.send(input) {
759 // Unbounded send only fails if the receiver is gone
760 // (controller stopped) — nothing to do but drop quietly.
761 tracing::warn!(
762 block_id = %self.block_id,
763 seq = s,
764 "send_input: input channel closed, discarding packet: {e}"
765 );
766 return Ok(());
767 }
768 // Drain any buffered out-of-order packets now in order.
769 loop {
770 let expected = inner.input_seq_next;
771 match inner.input_seq_buf.remove(&expected) {
772 Some(buffered) => {
773 inner.input_seq_next += 1;
774 if let Err(e) = tx.send(buffered) {
775 tracing::warn!(
776 block_id = %self.block_id,
777 seq = expected,
778 "send_input drain: input channel closed, discarding buffered packet: {e}"
779 );
780 }
781 }
782 None => break,
783 }
784 }
785 Ok(())
786 } else if s > next {
787 if inner.input_seq_buf.len() < SHELL_INPUT_CH_SIZE {
788 inner.input_seq_buf.insert(s, input);
789 } else {
790 tracing::warn!(block_id = %self.block_id, seq = s, "input reorder buffer full, dropping");
791 }
792 Ok(())
793 } else {
794 tracing::warn!(block_id = %self.block_id, seq = s, next, "duplicate input seq, discarding");
795 Ok(())
796 }
797 }
798 }
799 }
800
801 fn controller_type(&self) -> &str {
802 &self.controller_type
803 }
804
805 fn block_id(&self) -> &str {
806 &self.block_id
807 }
808
809 fn agent_id(&self) -> Option<String> {
810 self.inner.lock().unwrap().agent_id.clone()
811 }
812
813 fn set_agent_id(&self, id: Option<String>) {
814 self.inner.lock().unwrap().agent_id = id;
815 }
816
817 fn as_any(&self) -> &dyn std::any::Any {
818 self
819 }
820}
821
822#[cfg(test)]
823mod agent_id_for_jekt_tests {
824 use super::{is_global_cmd_env_injectable, resolve_agent_id_for_jekt};
825 use crate::backend::blockcontroller::META_KEY_CMD_ENV;
826 use crate::backend::obj::MetaMapType;
827
828 #[test]
829 fn identity_keys_are_never_globally_injectable() {
830 // reagentx P1, round 2 on #2694: these must never come from global
831 // settings.cmd_env — only from a block's own explicit override.
832 assert!(!is_global_cmd_env_injectable("AGENTMUX_AGENT_ID"));
833 assert!(!is_global_cmd_env_injectable("WAVEMUX_AGENT_ID"));
834 }
835
836 #[test]
837 fn other_global_cmd_env_keys_remain_injectable() {
838 // Unrelated global defaults (arbitrary user cmd_env entries) are
839 // unaffected — only the two identity keys are excluded. Was
840 // AGENTMUX_AGENT_COLOR before that var's decommission (2026-09-20,
841 // SPEC_AGENT_HEADER_COLOR_UNIFICATION_2026_09_20.md) — swapped to a
842 // generic name so this test doesn't reference a var with no live
843 // meaning left in the codebase.
844 assert!(is_global_cmd_env_injectable("SOME_COSMETIC_VAR"));
845 assert!(is_global_cmd_env_injectable("SOME_OTHER_VAR"));
846 }
847
848 fn meta_with_env(pairs: &[(&str, &str)]) -> MetaMapType {
849 let mut obj = serde_json::Map::new();
850 for (k, v) in pairs {
851 obj.insert(k.to_string(), serde_json::json!(v));
852 }
853 let mut meta = MetaMapType::new();
854 meta.insert(META_KEY_CMD_ENV.to_string(), serde_json::Value::Object(obj));
855 meta
856 }
857
858 #[test]
859 fn no_block_scoped_identity_resolves_to_none() {
860 // This is the collision-fix regression case: a pane with neither
861 // AGENTMUX_AGENT_ID nor WAVEMUX_AGENT_ID set in its OWN cmd:env is
862 // simply not jekt-registered — no fallback to global settings, and
863 // (reagentx P1, round 2) no fallback to this srv PROCESS's own
864 // std::env::var either, since that's process-global, not per-pane.
865 let empty_meta = MetaMapType::new();
866 assert_eq!(resolve_agent_id_for_jekt(&empty_meta), None);
867 }
868
869 #[test]
870 fn resolves_block_scoped_agentmux_agent_id() {
871 let meta = meta_with_env(&[("AGENTMUX_AGENT_ID", "agentx")]);
872 assert_eq!(resolve_agent_id_for_jekt(&meta), Some("agentx".to_string()));
873 }
874
875 #[test]
876 fn resolves_block_scoped_legacy_wavemux_agent_id() {
877 // The legacy alias is read from the SAME block-scoped cmd:env map,
878 // not process env (reagentx P1, round 2) — genuinely per-pane, so
879 // it can't reintroduce the same-host collision.
880 let meta = meta_with_env(&[("WAVEMUX_AGENT_ID", "legacy-agent")]);
881 assert_eq!(
882 resolve_agent_id_for_jekt(&meta),
883 Some("legacy-agent".to_string())
884 );
885 }
886
887 #[test]
888 fn agentmux_agent_id_wins_over_legacy_wavemux_when_both_set_on_the_same_block() {
889 let meta = meta_with_env(&[
890 ("AGENTMUX_AGENT_ID", "agentx"),
891 ("WAVEMUX_AGENT_ID", "legacy-agent"),
892 ]);
893 assert_eq!(resolve_agent_id_for_jekt(&meta), Some("agentx".to_string()));
894 }
895
896 #[test]
897 fn blank_value_is_treated_as_absent() {
898 // Matches persistent/mod.rs's muxbus_agent_id_from_env: a present-but-
899 // whitespace-only value doesn't count as a real identity.
900 let meta = meta_with_env(&[("AGENTMUX_AGENT_ID", " ")]);
901 assert_eq!(resolve_agent_id_for_jekt(&meta), None);
902 }
903
904 #[test]
905 fn a_different_blocks_env_never_leaks_in() {
906 // resolve_agent_id_for_jekt takes ONE block's own metadata — there
907 // is no code path here that could read another block's or the
908 // process's own env, unlike the bug this fn was rewritten to fix.
909 // This test exists to make that structurally obvious: the fn's
910 // only input is the map passed in.
911 let other_blocks_meta = meta_with_env(&[("AGENTMUX_AGENT_ID", "agenty")]);
912 let this_blocks_meta = MetaMapType::new();
913 assert_eq!(resolve_agent_id_for_jekt(&other_blocks_meta), Some("agenty".to_string()));
914 assert_eq!(resolve_agent_id_for_jekt(&this_blocks_meta), None);
915 }
916}
917
918/// Global `cmd:env` (settings.json) reaching an interactive shell's env.
919///
920/// Settings enter a `ConfigState` the way they do in production: a
921/// settings.json parsed by `read_config_file`, then `update_settings`, which
922/// is what `config_watcher_fs` does at startup and on every save. The env is
923/// read off a real `CommandBuilder` after `apply_cmd_env`, the call `start()`
924/// makes.
925#[cfg(test)]
926mod global_cmd_env_tests {
927 use std::sync::Arc;
928
929 use portable_pty::CommandBuilder;
930
931 use super::super::controller::ShellController;
932 use super::cmd_env_overrides;
933 use crate::backend::blockcontroller::META_KEY_CMD_ENV;
934 use crate::backend::obj::MetaMapType;
935 use crate::backend::wconfig::{self, ConfigState};
936
937 /// Load `settings_json` into `config` as the settings watcher does.
938 fn load_settings(config: &ConfigState, settings_json: &str) {
939 let dir = tempfile::tempdir().unwrap();
940 let path = dir.path().join(wconfig::SETTINGS_FILE);
941 std::fs::write(&path, settings_json).unwrap();
942 let (settings, errors): (wconfig::SettingsType, _) = wconfig::read_config_file(&path);
943 assert!(errors.is_empty(), "test settings.json must parse: {errors:?}");
944 config.update_settings(settings);
945 }
946
947 /// A config built like `bootstrap/background.rs`'s, with `settings_json` loaded.
948 fn live_config(settings_json: &str) -> Arc<ConfigState> {
949 let config = Arc::new(ConfigState::with_config(wconfig::build_default_config()));
950 load_settings(&config, settings_json);
951 config
952 }
953
954 fn controller(config: Option<Arc<ConfigState>>) -> ShellController {
955 ShellController::new(
956 "shell".to_string(),
957 "tab-cmd-env".to_string(),
958 "block-cmd-env".to_string(),
959 None,
960 None,
961 None,
962 None,
963 String::new(),
964 )
965 .with_config(config)
966 }
967
968 fn block_env(pairs: &[(&str, &str)]) -> MetaMapType {
969 let mut obj = serde_json::Map::new();
970 for (k, v) in pairs {
971 obj.insert(k.to_string(), serde_json::json!(v));
972 }
973 let mut meta = MetaMapType::new();
974 meta.insert(META_KEY_CMD_ENV.to_string(), serde_json::Value::Object(obj));
975 meta
976 }
977
978 /// The env a spawn from `ctrl` gets for `block_meta`. Starts from an empty
979 /// env so the test process's own variables can't leak into assertions.
980 fn spawn_env(ctrl: &ShellController, block_meta: &MetaMapType) -> CommandBuilder {
981 let mut c = CommandBuilder::new("shell-under-test");
982 c.env_clear();
983 ctrl.apply_cmd_env(&mut c, block_meta);
984 c
985 }
986
987 fn var(c: &CommandBuilder, key: &str) -> Option<String> {
988 c.get_env(key).map(|v| v.to_string_lossy().into_owned())
989 }
990
991 #[test]
992 fn a_command_pane_gets_its_cmd_env_direct_or_through_the_shell() {
993 // A login pane: the CLI run directly, with the account's config dir.
994 let ctrl = controller(None);
995 let meta = block_env(&[("CLAUDE_CONFIG_DIR", "/accounts/a")]);
996 let args = vec!["auth".to_string(), "login".to_string()];
997 let direct = ctrl.command_process("claude", &args, true, &meta).unwrap();
998 assert_eq!(var(&direct, "CLAUDE_CONFIG_DIR").as_deref(), Some("/accounts/a"));
999 let wrapped = ctrl.command_process("claude auth login", &[], false, &meta).unwrap();
1000 assert_eq!(var(&wrapped, "CLAUDE_CONFIG_DIR").as_deref(), Some("/accounts/a"));
1001 }
1002
1003 /// On Windows a direct-spawn pane runs what an npm `.cmd` shim points
1004 /// at, not the shim (which hangs under ConPTY), with the pane's args after.
1005 #[cfg(windows)]
1006 #[test]
1007 fn a_command_pane_runs_what_an_npm_shim_points_at() {
1008 let dir = tempfile::tempdir().unwrap();
1009 let bin = dir.path().join("node_modules").join(".bin");
1010 std::fs::create_dir_all(&bin).unwrap();
1011 let shim = bin.join("openclaw.cmd");
1012 std::fs::write(
1013 &shim,
1014 concat!(
1015 "@ECHO off
1016GOTO start
1017:find_dp0
1018SET dp0=%~dp0
1019EXIT /b
1020:start
1021SETLOCAL
1022",
1023 r#""%_prog%" "%dp0%\..\openclaw\cli.js" %*"#,
1024 "
1025"
1026 ),
1027 )
1028 .unwrap();
1029 let args = vec!["login".to_string()];
1030 let c = controller(None).command_process(&shim.to_string_lossy(), &args, true, &MetaMapType::new()).unwrap();
1031 let argv: Vec<String> = c.get_argv().iter().map(|a| a.to_string_lossy().into_owned()).collect();
1032 assert_eq!(argv[0], "node");
1033 assert!(argv[1].ends_with("cli.js"), "the shim's script, got {argv:?}");
1034 assert_eq!(argv[2], "login");
1035 }
1036
1037 /// A wrapper that can't be read is refused rather than started into a
1038 /// pane that would hang.
1039 #[cfg(windows)]
1040 #[test]
1041 fn a_command_pane_refuses_a_wrapper_it_cannot_read() {
1042 let dir = tempfile::tempdir().unwrap();
1043 let shim = dir.path().join("odd.cmd");
1044 std::fs::write(&shim, "@echo off\r\nsomething-else %*\r\n").unwrap();
1045 let err = controller(None)
1046 .command_process(&shim.to_string_lossy(), &[], true, &MetaMapType::new())
1047 .err()
1048 .expect("an unreadable wrapper is refused");
1049 assert!(err.contains("can't run"), "{err}");
1050 }
1051
1052 #[test]
1053 fn defaults_carry_no_cmd_env() {
1054 // Precondition for every test below: a value they observe can only
1055 // have come from the loaded settings, never from the defaults.
1056 assert!(wconfig::build_default_config().settings.cmd_env.is_empty());
1057 }
1058
1059 #[test]
1060 fn global_cmd_env_from_the_live_config_is_applied() {
1061 let ctrl = controller(Some(live_config(
1062 r#"{ "cmd:env": { "AMUX_TEST_GLOBAL": "from-settings" } }"#,
1063 )));
1064 let env = spawn_env(&ctrl, &MetaMapType::new());
1065 assert_eq!(var(&env, "AMUX_TEST_GLOBAL").as_deref(), Some("from-settings"));
1066 }
1067
1068 #[test]
1069 fn block_cmd_env_overrides_the_global_value() {
1070 let ctrl = controller(Some(live_config(
1071 r#"{ "cmd:env": { "AMUX_TEST_SHARED": "global", "AMUX_TEST_GLOBAL_ONLY": "g" } }"#,
1072 )));
1073 let env = spawn_env(&ctrl, &block_env(&[("AMUX_TEST_SHARED", "block")]));
1074 assert_eq!(var(&env, "AMUX_TEST_SHARED").as_deref(), Some("block"));
1075 assert_eq!(
1076 var(&env, "AMUX_TEST_GLOBAL_ONLY").as_deref(),
1077 Some("g"),
1078 "a global key the block doesn't set still applies"
1079 );
1080 }
1081
1082 /// Windows env names are case-insensitive, and `CommandBuilder` matches
1083 /// them that way there. The block must still win when its key differs
1084 /// from the global one only in case.
1085 #[cfg(windows)]
1086 #[test]
1087 fn block_cmd_env_overrides_a_global_key_differing_only_in_case() {
1088 let ctrl = controller(Some(live_config(
1089 r#"{ "cmd:env": { "Amux_Test_Case": "global" } }"#,
1090 )));
1091 let env = spawn_env(&ctrl, &block_env(&[("AMUX_TEST_CASE", "block")]));
1092 assert_eq!(var(&env, "AMUX_TEST_CASE").as_deref(), Some("block"));
1093 }
1094
1095 #[test]
1096 fn global_agent_identity_keys_are_still_not_injected() {
1097 let ctrl = controller(Some(live_config(
1098 r#"{ "cmd:env": {
1099 "AGENTMUX_AGENT_ID": "shared-id",
1100 "WAVEMUX_AGENT_ID": "shared-legacy-id",
1101 "AMUX_TEST_NEIGHBOUR": "applied"
1102 } }"#,
1103 )));
1104
1105 // Excluded at injection (#2694), not merely removed by the strip.
1106 let overrides = cmd_env_overrides(&ctrl.live_settings(), &MetaMapType::new());
1107 let keys: Vec<&str> = overrides.vars.iter().map(|(k, _)| k.as_str()).collect();
1108 assert_eq!(keys, vec!["AMUX_TEST_NEIGHBOUR"]);
1109
1110 let plain = spawn_env(&ctrl, &MetaMapType::new());
1111 assert_eq!(var(&plain, "AMUX_TEST_NEIGHBOUR").as_deref(), Some("applied"));
1112 assert_eq!(var(&plain, "AGENTMUX_AGENT_ID"), None);
1113 assert_eq!(var(&plain, "WAVEMUX_AGENT_ID"), None);
1114
1115 // A block with its own identity skips the strip, so only the global
1116 // exclusion keeps the shared legacy id out here.
1117 let agent = spawn_env(&ctrl, &block_env(&[("AGENTMUX_AGENT_ID", "block-id")]));
1118 assert_eq!(var(&agent, "AGENTMUX_AGENT_ID").as_deref(), Some("block-id"));
1119 assert_eq!(var(&agent, "WAVEMUX_AGENT_ID"), None);
1120 }
1121
1122 #[test]
1123 fn a_settings_change_reaches_the_next_spawn_of_the_same_controller() {
1124 let config = live_config(r#"{ "cmd:env": { "AMUX_TEST_LIVE": "v1" } }"#);
1125 let ctrl = controller(Some(Arc::clone(&config)));
1126 assert_eq!(var(&spawn_env(&ctrl, &MetaMapType::new()), "AMUX_TEST_LIVE").as_deref(), Some("v1"));
1127
1128 // A later settings.json save, reloaded as the watcher does.
1129 load_settings(&config, r#"{ "cmd:env": { "AMUX_TEST_LIVE": "v2" } }"#);
1130 assert_eq!(var(&spawn_env(&ctrl, &MetaMapType::new()), "AMUX_TEST_LIVE").as_deref(), Some("v2"));
1131
1132 // A Settings-pane save: the `setconfig` handler merges into memory.
1133 let mut keys = serde_json::Map::new();
1134 keys.insert("cmd:env".to_string(), serde_json::json!({ "AMUX_TEST_LIVE": "v3" }));
1135 let merged = crate::backend::config_watcher_fs::merge_settings_into_current(&config, keys);
1136 config.update_settings(merged);
1137 assert_eq!(var(&spawn_env(&ctrl, &MetaMapType::new()), "AMUX_TEST_LIVE").as_deref(), Some("v3"));
1138
1139 // Dropping the key from settings.json drops it from the next spawn.
1140 load_settings(&config, "{}");
1141 assert_eq!(var(&spawn_env(&ctrl, &MetaMapType::new()), "AMUX_TEST_LIVE"), None);
1142 }
1143
1144 #[test]
1145 fn no_attached_config_applies_only_the_block_env() {
1146 let ctrl = controller(None);
1147 let env = spawn_env(&ctrl, &block_env(&[("AMUX_TEST_BLOCK", "b")]));
1148 assert_eq!(var(&env, "AMUX_TEST_BLOCK").as_deref(), Some("b"));
1149 }
1150
1151 /// The production entry point: `resync_controller` must hand the config
1152 /// it is given to the shell controller it creates.
1153 #[test]
1154 fn resync_controller_gives_a_new_shell_controller_the_live_config() {
1155 use crate::backend::blockcontroller as bc;
1156
1157 let block_id = "cmd-env-resync-wiring";
1158 let config = live_config(r#"{ "cmd:env": { "AMUX_TEST_WIRED": "yes" } }"#);
1159 let mut meta = MetaMapType::new();
1160 meta.insert(bc::META_KEY_CONTROLLER.to_string(), serde_json::json!(bc::BLOCK_CONTROLLER_SHELL));
1161 // Register the controller without spawning a real shell.
1162 meta.insert(bc::META_KEY_CMD_RUN_ON_START.to_string(), serde_json::json!(false));
1163 let block = crate::backend::obj::Block {
1164 oid: block_id.to_string(),
1165 meta,
1166 ..Default::default()
1167 };
1168
1169 bc::resync_controller(
1170 &block, "tab-cmd-env", None, false, true,
1171 None, None, None, None, None, None, None,
1172 Arc::from("test-boot"), "test-key",
1173 Some(Arc::clone(&config)),
1174 )
1175 .expect("resync");
1176 let registered = bc::get_controller(block_id).expect("controller registered");
1177 let shell = registered
1178 .as_any()
1179 .downcast_ref::<ShellController>()
1180 .expect("a shell controller");
1181 let seen = var(&spawn_env(shell, &MetaMapType::new()), "AMUX_TEST_WIRED");
1182 bc::delete_controller(block_id);
1183
1184 assert_eq!(seen.as_deref(), Some("yes"));
1185 }
1186}
1187
1188/// Ask the output flusher to confirm that everything enqueued so far has been
1189/// committed, bounded by `timeout`.
1190///
1191/// This is the ordering guarantee the post-exit wait actually needs: clients
1192/// must not observe `STATUS_DONE` before the output that preceded it is
1193/// readable. `PtyShellStatus` → `PtyShellRead` is the sharpest case — an agent
1194/// polls until `running: false` and then reads the file, so a `STATUS_DONE`
1195/// that outran the final flush hands it truncated command output (Codex P1 on
1196/// PR #3261).
1197///
1198/// Waiting on the flusher TASK was the previous way to get that, and it is a
1199/// much blunter instrument: the task only ends when the channel closes, which
1200/// on Windows never happens (ConPTY's console host outlives the child, so the
1201/// read loop stays blocked in a read that never returns and never drops its
1202/// sender). Every ordinary exit therefore paid the full
1203/// `FLUSHER_DRAIN_TIMEOUT` while the flusher sat idle — a visible second of
1204/// dead UI, and the reason `exit` in a shell felt stuck.
1205///
1206/// `Err(())` means the barrier could not be confirmed within `timeout` (or the
1207/// flusher is already gone). Callers fall back to the old bounded wait.
1208pub(super) async fn flush_barrier(
1209 tx: &mpsc::Sender<PtyReadChunk>,
1210 timeout: std::time::Duration,
1211) -> Result<(), ()> {
1212 let (ack_tx, ack_rx) = tokio::sync::oneshot::channel();
1213 // The SEND is inside the timeout too, not just the ack wait (ReAgent P1 on
1214 // PR #3261). `tx` is a bounded channel: if it is full and the flusher is
1215 // stalled — a wedged FileStore write, a jammed broker — an unbounded
1216 // `send().await` blocks the whole wait/cleanup task forever, and with it
1217 // STATUS_DONE, the jekt lease release, and the close-on-exit trigger. The
1218 // entire point of this path is to be bounded; a bound with an unbounded
1219 // step inside it is not one.
1220 let deadline = tokio::time::Instant::now() + timeout;
1221 let send_fut = tx.send(PtyReadChunk {
1222 data: Vec::new(),
1223 osc_events: Vec::new(),
1224 ack: Some(ack_tx),
1225 });
1226 match tokio::time::timeout_at(deadline, send_fut).await {
1227 // Receiver gone — the flusher has already exited, which means the
1228 // channel closed, which means everything in it was drained.
1229 Ok(Err(_)) => return Ok(()),
1230 Ok(Ok(())) => {}
1231 Err(_) => return Err(()),
1232 }
1233 match tokio::time::timeout_at(deadline, ack_rx).await {
1234 Ok(Ok(())) => Ok(()),
1235 _ => Err(()),
1236 }
1237}
1238
1239/// Release `block_id`'s PtyShell agent lease — both copies — but ONLY if
1240/// `inner` still identifies the controller currently registered for that
1241/// block. Returns whether it released.
1242///
1243/// The guard is the same `Arc::ptr_eq` controller-identity check the
1244/// close-on-exit trigger uses, for the same reason (Codex P1 / ReAgent P1 on
1245/// PR #3249): a force-restart (`resync_controller` → `stop_for_replace`)
1246/// kills this child and registers a REPLACEMENT controller under the same
1247/// block_id. The killed child's wait/cleanup task belongs to the OLD
1248/// controller; without this check it fires afterwards and clears a lease the
1249/// agent legitimately took on the NEW shell, letting human input race the
1250/// agent's writes on a pane that never stopped being driven. Leases are keyed
1251/// by block_id alone, so a stale task cannot tell its own lease from its
1252/// successor's — controller identity is what distinguishes them.
1253///
1254/// Check-then-act, like its precedent: a replacement registered in the window
1255/// between the check and the remove would still lose its lease. Same residual
1256/// race the close-on-exit guard accepts, and self-correcting here, since
1257/// `lock_shell_for_agent` re-takes the lease before every agent write.
1258pub(super) fn release_lease_if_current(
1259 block_id: &str,
1260 inner: &Arc<std::sync::Mutex<super::controller::ShellControllerInner>>,
1261 mstore: &Option<Arc<crate::backend::storage::store::Store>>,
1262 event_bus: &Option<Arc<crate::backend::eventbus::EventBus>>,
1263) -> bool {
1264 let is_current = super::super::get_controller(block_id)
1265 .and_then(|ctrl| {
1266 ctrl.as_any()
1267 .downcast_ref::<ShellController>()
1268 .map(|sc| Arc::ptr_eq(&sc.inner, inner))
1269 })
1270 .unwrap_or(false);
1271 if !is_current {
1272 tracing::info!(
1273 block_id = %block_id,
1274 "agent lease: controller was replaced since this process exited \
1275 (restart in flight?) — leaving the successor's lease alone"
1276 );
1277 return false;
1278 }
1279 super::super::agent_lock::release_and_clear_meta(block_id, mstore, event_bus);
1280 true
1281}
1282
1283#[cfg(test)]
1284mod flush_barrier_tests {
1285 use super::{flush_barrier, run_pty_output_flusher, PtyReadChunk, PTY_CHANNEL_CAPACITY};
1286
1287 /// The guarantee Codex's P1 on PR #3261 is about: the barrier must not
1288 /// resolve until output enqueued BEFORE it has actually been flushed.
1289 /// `PtyShellStatus` -> `PtyShellRead` depends on this — an agent polls for
1290 /// `running: false` and then reads the file, so a `STATUS_DONE` that
1291 /// outran the final flush hands it truncated output.
1292 ///
1293 /// Uses the real flusher with no broker, which makes it return
1294 /// immediately and close the channel — so this asserts the OTHER half:
1295 /// that a gone flusher resolves rather than hanging (see below). The
1296 /// ordering itself is asserted by
1297 /// `barrier_does_not_resolve_until_prior_output_is_committed`.
1298 #[tokio::test]
1299 async fn a_gone_flusher_resolves_the_barrier_instead_of_hanging() {
1300 let (tx, rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(PTY_CHANNEL_CAPACITY);
1301 // No broker → the flusher returns at once, dropping the receiver.
1302 let flusher = tokio::spawn(run_pty_output_flusher(rx, None, "blk".into(), None, false));
1303 flusher.await.expect("flusher task");
1304
1305 let res = flush_barrier(&tx, std::time::Duration::from_secs(5)).await;
1306 assert_eq!(res, Ok(()), "a closed channel means nothing is left unflushed");
1307 }
1308
1309 /// THE load-bearing property: the ack must not fire until the output
1310 /// enqueued before it is actually COMMITTED — written to the FileStore,
1311 /// not merely dequeued.
1312 ///
1313 /// Runs the real flusher against a real in-memory FileStore and reads the
1314 /// file at the moment the barrier resolves. An earlier version of this
1315 /// test drained the channel by hand instead, which only proved the
1316 /// channel is FIFO — it passed unchanged when the ack was moved to BEFORE
1317 /// the flush, i.e. it could not see the bug it existed to catch.
1318 #[tokio::test]
1319 async fn barrier_does_not_resolve_until_prior_output_is_committed() {
1320 use super::super::super::super::storage::filestore::FileStore;
1321 use std::sync::Arc;
1322
1323 let (broker, _events) = super::pty_output_flusher_tests::broker_recording_block_file_events();
1324 let fs = Arc::new(FileStore::open_in_memory().expect("open in-memory filestore"));
1325 let (tx, rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(PTY_CHANNEL_CAPACITY);
1326
1327 tx.send(PtyReadChunk { data: b"committed output".to_vec(), osc_events: Vec::new(), ack: None })
1328 .await
1329 .expect("send data");
1330
1331 let flusher = tokio::spawn(run_pty_output_flusher(
1332 rx,
1333 Some(Arc::new(broker)),
1334 "block-1".to_string(),
1335 Some(fs.clone()),
1336 false,
1337 ));
1338
1339 flush_barrier(&tx, std::time::Duration::from_secs(5))
1340 .await
1341 .expect("barrier must resolve");
1342
1343 // The barrier has resolved — the output it was queued behind must be
1344 // readable RIGHT NOW, with no further waiting.
1345 let data = fs
1346 .read_file("block-1", "term")
1347 .expect("read_file ok")
1348 .expect("output must be committed by the time the barrier resolves");
1349 assert_eq!(
1350 data,
1351 b"committed output".to_vec(),
1352 "barrier resolved before the preceding output reached the FileStore"
1353 );
1354
1355 drop(tx);
1356 let _ = flusher.await;
1357 }
1358
1359 /// The property that makes the "prefer true EOF" fast path reachable at
1360 /// all, and the exact thing ReAgent's round-3 P1 found broken: the wait
1361 /// task's barrier handle must NOT keep the channel open.
1362 ///
1363 /// An mpsc channel closes only once EVERY `Sender` is dropped. A strong
1364 /// clone held across the EOF wait means `recv()` never yields `None`, the
1365 /// flusher never ends, `flusher_handle` never resolves — and the fast path
1366 /// is dead code on every platform, silently applying the fallback's
1367 /// residual race everywhere.
1368 ///
1369 /// The production site is additionally type-annotated as `WeakSender`, so
1370 /// swapping it back to `clone()` is a compile error rather than a silent
1371 /// behaviour change.
1372 #[tokio::test]
1373 async fn a_weak_barrier_handle_does_not_keep_the_flusher_alive() {
1374 use super::super::super::super::storage::filestore::FileStore;
1375 use std::sync::Arc;
1376
1377 let (broker, _events) = super::pty_output_flusher_tests::broker_recording_block_file_events();
1378 let fs = Arc::new(FileStore::open_in_memory().expect("open in-memory filestore"));
1379 let (tx, rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(PTY_CHANNEL_CAPACITY);
1380
1381 let weak: tokio::sync::mpsc::WeakSender<PtyReadChunk> = tx.downgrade();
1382 let flusher = tokio::spawn(run_pty_output_flusher(
1383 rx,
1384 Some(Arc::new(broker)),
1385 "block-1".to_string(),
1386 Some(fs),
1387 false,
1388 ));
1389
1390 // The read loop's sender going away is the ONLY strong sender.
1391 drop(tx);
1392
1393 tokio::time::timeout(std::time::Duration::from_secs(5), flusher)
1394 .await
1395 .expect("the flusher must end once the last STRONG sender drops — a weak handle must not hold it open")
1396 .expect("flusher task");
1397
1398 assert!(
1399 weak.upgrade().is_none(),
1400 "a closed channel must not be upgradeable — the barrier reads this as 'already drained'"
1401 );
1402 }
1403
1404 /// ReAgent P1 on PR #3261: the SEND has to be inside the timeout too.
1405 /// `tx` is bounded, so a full channel plus a stalled flusher makes an
1406 /// unbounded `send().await` block the whole wait/cleanup task forever —
1407 /// taking STATUS_DONE, the lease release and close-on-exit with it. A
1408 /// bound with an unbounded step inside it is not a bound.
1409 ///
1410 /// Fills the channel to capacity with a receiver that never reads, so the
1411 /// send genuinely cannot complete.
1412 #[tokio::test]
1413 async fn a_full_channel_expires_instead_of_blocking_forever() {
1414 let (tx, _rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(1);
1415 tx.send(PtyReadChunk { data: b"wedged".to_vec(), osc_events: Vec::new(), ack: None })
1416 .await
1417 .expect("first send fills the channel");
1418
1419 let started = std::time::Instant::now();
1420 let res = flush_barrier(&tx, std::time::Duration::from_millis(80)).await;
1421 assert_eq!(res, Err(()), "a send that cannot complete must expire");
1422 assert!(
1423 started.elapsed() < std::time::Duration::from_secs(5),
1424 "must expire on the timeout, not block: took {:?}",
1425 started.elapsed()
1426 );
1427 }
1428
1429 /// The bounded-wait contract: if nothing ever acks (a wedged flusher), the
1430 /// barrier gives up rather than hanging the exit path forever. This is the
1431 /// case the old code always hit, and it is now the fallback rather than
1432 /// the norm.
1433 #[tokio::test]
1434 async fn an_unanswered_barrier_times_out() {
1435 let (tx, _rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(PTY_CHANNEL_CAPACITY);
1436 // `_rx` is held open but never read, so the ack can never fire.
1437 let res = flush_barrier(&tx, std::time::Duration::from_millis(50)).await;
1438 assert_eq!(res, Err(()), "an unanswered barrier must expire, not block forever");
1439 }
1440}
1441
1442#[cfg(test)]
1443mod agent_lease_release_tests {
1444 use super::*;
1445 use crate::backend::blockcontroller::agent_lock;
1446
1447 fn controller_for(block_id: &str) -> Arc<ShellController> {
1448 Arc::new(ShellController::new(
1449 "shell".to_string(),
1450 "tab-lease".to_string(),
1451 block_id.to_string(),
1452 None,
1453 None,
1454 None,
1455 None,
1456 String::new(),
1457 ))
1458 }
1459
1460 /// The natural case: this task's own controller is still the registered
1461 /// one (a human typed `exit`), so the lease goes.
1462 #[test]
1463 fn releases_when_this_task_still_owns_the_controller() {
1464 let block_id = "lease-guard-current";
1465 let ctrl = controller_for(block_id);
1466 let inner = Arc::clone(&ctrl.inner);
1467 super::super::super::register_controller(block_id, ctrl);
1468
1469 agent_lock::lock_until(block_id, agentmux_common::time::now_ms() + 60_000);
1470 assert!(release_lease_if_current(block_id, &inner, &None, &None));
1471 assert!(!agent_lock::is_locked(block_id), "an exited shell must drop its lease");
1472
1473 super::super::super::delete_controller(block_id);
1474 agent_lock::release(block_id);
1475 }
1476
1477 /// Force-restart: a REPLACEMENT controller is registered under the same
1478 /// block_id and the agent takes a fresh lease on it. This stale task —
1479 /// from the killed old process — must not clear that live lease, or human
1480 /// keystrokes race the agent's writes on a shell still being driven.
1481 #[test]
1482 fn leaves_a_successors_lease_alone_after_a_force_restart() {
1483 let block_id = "lease-guard-replaced";
1484 let old = controller_for(block_id);
1485 let old_inner = Arc::clone(&old.inner);
1486 let replacement = controller_for(block_id);
1487
1488 // The replacement is what's registered now — exactly what
1489 // `stop_for_replace` + re-register leaves behind.
1490 super::super::super::register_controller(block_id, replacement);
1491 agent_lock::lock_until(block_id, agentmux_common::time::now_ms() + 60_000);
1492
1493 assert!(
1494 !release_lease_if_current(block_id, &old_inner, &None, &None),
1495 "a stale task must not release"
1496 );
1497 assert!(
1498 agent_lock::is_locked(block_id),
1499 "the successor's lease must survive the old controller's cleanup"
1500 );
1501
1502 super::super::super::delete_controller(block_id);
1503 agent_lock::release(block_id);
1504 }
1505
1506 /// No controller registered at all (block already torn down) — nothing to
1507 /// own the lease, so this task must not assume the lease is its own.
1508 #[test]
1509 fn does_not_release_when_no_controller_is_registered() {
1510 let block_id = "lease-guard-unregistered";
1511 let orphan = controller_for(block_id);
1512 let inner = Arc::clone(&orphan.inner);
1513
1514 agent_lock::lock_until(block_id, agentmux_common::time::now_ms() + 60_000);
1515 assert!(!release_lease_if_current(block_id, &inner, &None, &None));
1516 assert!(agent_lock::is_locked(block_id));
1517
1518 agent_lock::release(block_id);
1519 }
1520}
1521
1522#[cfg(test)]
1523mod controller_agent_id_tests {
1524 use super::super::controller::ShellController;
1525 use super::super::super::Controller;
1526
1527 fn controller() -> ShellController {
1528 ShellController::new(
1529 "shell".to_string(),
1530 "tab1".to_string(),
1531 "block1".to_string(),
1532 None,
1533 None,
1534 None,
1535 None,
1536 String::new(),
1537 )
1538 }
1539
1540 /// reagentx P1 on #2697: `agent_id()` was captured once at spawn and
1541 /// never refreshed on re-registration, so a legitimately renamed or
1542 /// reconfigured agent's own messages could be falsely rejected as an
1543 /// identity mismatch by `inject_message_inner`'s recipient-identity
1544 /// check (#2695). `set_agent_id` (called from `handle_reactive_register`
1545 /// on every re-registration) must actually overwrite the captured value,
1546 /// not just the initial spawn-time one.
1547 #[test]
1548 fn set_agent_id_overwrites_a_stale_captured_value() {
1549 let ctrl = controller();
1550 assert_eq!(ctrl.agent_id(), None);
1551
1552 ctrl.set_agent_id(Some("agentx".to_string()));
1553 assert_eq!(ctrl.agent_id(), Some("agentx".to_string()));
1554
1555 // A later re-registration under a different name (rename,
1556 // reconfigured cmd:env) must be reflected, not stuck at "agentx".
1557 ctrl.set_agent_id(Some("agenty".to_string()));
1558 assert_eq!(ctrl.agent_id(), Some("agenty".to_string()));
1559
1560 ctrl.set_agent_id(None);
1561 assert_eq!(ctrl.agent_id(), None);
1562 }
1563}
1564
1565#[cfg(test)]
1566pub(super) mod pty_output_flusher_tests {
1567 use super::{flush_pty_batch, run_pty_output_flusher, PtyReadChunk, PTY_CHANNEL_CAPACITY};
1568 use crate::backend::storage::filestore::FileStore;
1569 use crate::backend::mps;
1570 use std::sync::{Arc, Mutex};
1571
1572 /// Records every event delivered to it — lets a test count broadcasts
1573 /// rather than only inspect final file content, which is what actually
1574 /// distinguishes "coalesced into one broadcast" from "one broadcast per
1575 /// PTY read" (both produce identical final content; only the broadcast
1576 /// COUNT tells them apart). Holds an `Arc` (not an owned `Vec`) because
1577 /// `Broker::set_client` takes ownership of the client, so the test needs
1578 /// its own handle to read events back out afterward.
1579 struct RecordingClient {
1580 events: Arc<Mutex<Vec<mps::MuxEvent>>>,
1581 }
1582
1583 impl mps::WpsClient for RecordingClient {
1584 fn send_event(&self, _route_id: &str, event: mps::MuxEvent) {
1585 self.events.lock().unwrap().push(event);
1586 }
1587 }
1588
1589 /// A broker wired to a `RecordingClient`, subscribed (all-scopes, so
1590 /// this doesn't need to know the exact `block:<id>` scope string) to
1591 /// `EVENT_BLOCK_FILE` — the event `handle_append_block_file` publishes.
1592 pub(super) fn broker_recording_block_file_events() -> (mps::Broker, Arc<Mutex<Vec<mps::MuxEvent>>>) {
1593 let broker = mps::Broker::new();
1594 let events = Arc::new(Mutex::new(Vec::new()));
1595 broker.set_client(Box::new(RecordingClient {
1596 events: events.clone(),
1597 }));
1598 broker.subscribe(
1599 "test-route",
1600 mps::SubscriptionRequest {
1601 event: mps::EVENT_BLOCK_FILE.to_string(),
1602 scopes: vec![],
1603 allscopes: true,
1604 },
1605 );
1606 (broker, events)
1607 }
1608
1609 /// Decode the base64 `data64` payload of a `term`-file `EVENT_BLOCK_FILE`
1610 /// broadcast back to raw bytes, for asserting on content.
1611 fn decode_event_data(event: &mps::MuxEvent) -> Vec<u8> {
1612 use base64::Engine;
1613 let data: mps::WSFileEventData =
1614 serde_json::from_value(event.data.clone().expect("event has data")).expect("valid WSFileEventData");
1615 base64::engine::general_purpose::STANDARD
1616 .decode(&data.data64)
1617 .expect("valid base64")
1618 }
1619
1620 #[test]
1621 fn flush_pty_batch_writes_and_broadcasts_one_call() {
1622 let (broker, events) = broker_recording_block_file_events();
1623 let fs = Arc::new(FileStore::open_in_memory().expect("open in-memory filestore"));
1624 let mut line_buf = Vec::new();
1625
1626 flush_pty_batch(&broker, "block-1", b"hello world", &[], Some(&fs), &mut line_buf, None);
1627
1628 let data = fs
1629 .read_file("block-1", "term")
1630 .expect("read_file ok")
1631 .expect("data present");
1632 assert_eq!(data, b"hello world");
1633
1634 let evs = events.lock().unwrap();
1635 assert_eq!(evs.len(), 1, "one flush call must produce exactly one broadcast");
1636 assert_eq!(decode_event_data(&evs[0]), b"hello world");
1637 }
1638
1639 #[test]
1640 fn flush_pty_batch_is_a_no_op_for_empty_input() {
1641 // Guards against a spurious empty broadcast on a batch that ended
1642 // up with nothing in it (shouldn't happen given how the flusher
1643 // calls this, but a no-op guard here is cheap and cheaper than
1644 // debugging a phantom empty append if that assumption ever breaks).
1645 let (broker, events) = broker_recording_block_file_events();
1646 let mut line_buf = Vec::new();
1647 flush_pty_batch(&broker, "block-1", b"", &[], None, &mut line_buf, None);
1648 assert!(events.lock().unwrap().is_empty());
1649 }
1650
1651 /// The actual property this whole change exists to deliver: N chunks
1652 /// that arrive back-to-back (well inside the coalescing window and the
1653 /// byte cap) collapse into far fewer broadcasts than N — ideally one —
1654 /// with no data lost, duplicated, or reordered.
1655 ///
1656 /// Deterministic, not timing-dependent: every chunk is sent to the
1657 /// channel BEFORE the flusher is ever polled, so its first "opportunistic
1658 /// drain" pass finds them all already queued and drains them without
1659 /// actually waiting out any real wall-clock delay — it's exercising the
1660 /// "channel closed mid-accumulation" exit path (see
1661 /// `run_pty_output_flusher`'s `closed_mid_batch`). The drain never waits
1662 /// on unarrived output at all now, so there is no window to race.
1663 #[tokio::test]
1664 async fn rapid_chunks_coalesce_into_far_fewer_broadcasts_with_no_data_loss() {
1665 let (broker, events) = broker_recording_block_file_events();
1666 let fs = Arc::new(FileStore::open_in_memory().expect("open in-memory filestore"));
1667 // Bounded, matching production (PTY_CHANNEL_CAPACITY) — comfortably
1668 // above the 50 messages below, so every send below still completes
1669 // without actually waiting for capacity; the determinism this test's
1670 // own doc comment relies on is unaffected by the channel being bounded.
1671 let (tx, rx) = tokio::sync::mpsc::channel(PTY_CHANNEL_CAPACITY);
1672
1673 let mut expected = Vec::new();
1674 for i in 0..50 {
1675 let piece = format!("line {i}\n");
1676 expected.extend_from_slice(piece.as_bytes());
1677 tx.send(PtyReadChunk {
1678 ack: None,
1679 data: piece.into_bytes(),
1680 osc_events: Vec::new(),
1681 })
1682 .await
1683 .unwrap();
1684 }
1685 drop(tx); // closes the channel once these 50 are drained
1686
1687 run_pty_output_flusher(rx, Some(Arc::new(broker)), "block-1".to_string(), Some(fs.clone()), false)
1688 .await;
1689
1690 let data = fs.read_file("block-1", "term").expect("read_file ok").expect("data present");
1691 assert_eq!(data, expected, "coalescing must not lose, duplicate, or reorder bytes");
1692
1693 // Deterministic exact count, not a loose bound: every chunk was
1694 // already queued before the flusher was ever polled (see the test's
1695 // own doc comment), so its very first opportunistic-drain pass finds
1696 // all 50 sitting in the channel and drains them without actually
1697 // waiting out any real time — one batch, one broadcast. Verified
1698 // stable across repeated local runs before asserting on it exactly;
1699 // a looser "< 50" bound would also pass on a much weaker result
1700 // (say, 40 broadcasts) that wouldn't actually demonstrate the fix.
1701 let broadcast_count = events.lock().unwrap().len();
1702 assert_eq!(
1703 broadcast_count, 1,
1704 "50 chunks queued before the flusher ever polled should collapse into \
1705 exactly one broadcast; got {broadcast_count}"
1706 );
1707 // Concatenating every broadcast's own payload, in delivery order,
1708 // must also reconstruct the exact original stream — proves the
1709 // coalescing boundaries themselves never split/reordered content
1710 // even if more than one broadcast happened.
1711 let mut reconstructed = Vec::new();
1712 for ev in events.lock().unwrap().iter() {
1713 reconstructed.extend(decode_event_data(ev));
1714 }
1715 assert_eq!(reconstructed, expected);
1716 }
1717
1718 /// The byte cap must still force a flush even if chunks keep arriving
1719 /// faster than the coalescing window would otherwise close — otherwise
1720 /// a sustained fast producer (`yes` piped into a shell pane) could grow
1721 /// one "batch" unboundedly.
1722 #[tokio::test]
1723 async fn byte_cap_forces_a_flush_before_the_channel_closes() {
1724 let (broker, events) = broker_recording_block_file_events();
1725 let fs = Arc::new(FileStore::open_in_memory().expect("open in-memory filestore"));
1726 // Bounded, matching production — 80 messages below is comfortably
1727 // under PTY_CHANNEL_CAPACITY, so this test still exercises the byte
1728 // cap (not channel backpressure) as the thing forcing the split.
1729 let (tx, rx) = tokio::sync::mpsc::channel(PTY_CHANNEL_CAPACITY);
1730
1731 // Comfortably over PTY_COALESCE_MAX_BYTES (64 * 4096 = 256KiB) in
1732 // total, sent as many small chunks so the cap — not the channel
1733 // closing — is what has to trigger the split.
1734 let piece = vec![b'x'; 4096];
1735 let mut expected = Vec::new();
1736 for _ in 0..80 {
1737 expected.extend_from_slice(&piece);
1738 tx.send(PtyReadChunk {
1739 ack: None,
1740 data: piece.clone(),
1741 osc_events: Vec::new(),
1742 })
1743 .await
1744 .unwrap();
1745 }
1746 drop(tx);
1747
1748 run_pty_output_flusher(rx, Some(Arc::new(broker)), "block-1".to_string(), Some(fs.clone()), false)
1749 .await;
1750
1751 let data = fs.read_file("block-1", "term").expect("read_file ok").expect("data present");
1752 assert_eq!(data, expected);
1753
1754 let broadcast_count = events.lock().unwrap().len();
1755 assert!(
1756 broadcast_count >= 2,
1757 "80 * 4096 bytes exceeds PTY_COALESCE_MAX_BYTES; expected at least 2 broadcasts \
1758 (the cap forcing an early flush), got {broadcast_count}"
1759 );
1760 }
1761
1762 /// The actual property reagentx's P1 asked for: a full channel makes
1763 /// `blocking_send` — what the real PTY read loop calls, from a real
1764 /// blocking (`spawn_blocking`) thread, not an async one — block until
1765 /// the receiver drains it, rather than growing queued memory without
1766 /// limit. A tiny capacity (not `PTY_CHANNEL_CAPACITY`) so the test is
1767 /// fast and the blocking is unambiguous with only 2 messages.
1768 #[test]
1769 fn blocking_send_backpressures_once_the_channel_is_full() {
1770 let (tx, mut rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(1);
1771
1772 // Fills the one slot; must return immediately (room available).
1773 tx.blocking_send(PtyReadChunk { data: vec![1], osc_events: Vec::new(), ack: None })
1774 .expect("first send has room");
1775
1776 // A real background thread — mirrors the production shape exactly:
1777 // blocking_send is called from a spawn_blocking thread, never from
1778 // an async task.
1779 let sent_second = Arc::new(std::sync::atomic::AtomicBool::new(false));
1780 let sent_second_writer = sent_second.clone();
1781 let handle = std::thread::spawn(move || {
1782 tx.blocking_send(PtyReadChunk { data: vec![2], osc_events: Vec::new(), ack: None })
1783 .expect("second send eventually succeeds once drained");
1784 sent_second_writer.store(true, std::sync::atomic::Ordering::SeqCst);
1785 });
1786
1787 // The channel is full and nobody has drained it yet — the second
1788 // send must still be blocked. A short, generous sleep rather than
1789 // asserting instantaneously: proving a negative ("hasn't returned
1790 // yet") is inherently a bit timing-sensitive, but 50ms is enormous
1791 // next to what an unblocked send would take (microseconds), so a
1792 // false pass here would need a wildly unlikely scheduling delay.
1793 std::thread::sleep(std::time::Duration::from_millis(50));
1794 assert!(
1795 !sent_second.load(std::sync::atomic::Ordering::SeqCst),
1796 "second blocking_send must still be blocked while the channel is full"
1797 );
1798
1799 // Drain the one queued message — this is the "flusher catches up"
1800 // moment in production. The blocked send must now complete.
1801 let first = rx.try_recv().expect("first message still queued");
1802 assert_eq!(first.data, vec![1]);
1803
1804 handle.join().expect("background thread should complete once drained");
1805 assert!(sent_second.load(std::sync::atomic::Ordering::SeqCst));
1806
1807 let second = rx.try_recv().expect("second message now queued");
1808 assert_eq!(second.data, vec![2]);
1809 }
1810
1811 #[tokio::test]
1812 async fn no_broker_is_a_clean_no_op() {
1813 // Mirrors the read loop's own `broker_read.is_some()` gate — the
1814 // flusher must not panic or hang when there is nothing to flush to.
1815 let (_tx, rx) = tokio::sync::mpsc::channel::<PtyReadChunk>(PTY_CHANNEL_CAPACITY);
1816 run_pty_output_flusher(rx, None, "block-1".to_string(), None, false).await;
1817 }
1818
1819 /// Pins the exact ordering guarantee the round-3 fix (reagentx P1:
1820 /// STATUS_DONE could publish before the flusher's final batch was
1821 /// broadcast) relies on: awaiting the `JoinHandle` returned by
1822 /// `tokio::spawn(run_pty_output_flusher(...))` — exactly what the wait
1823 /// task now does, before its own cleanup/status-publish logic — only
1824 /// returns once every batch, including one forced out by the channel
1825 /// closing, has actually been broadcast. The wait task itself spawns a
1826 /// real PTY + child process and isn't practical to drive from a unit
1827 /// test; this pins the one guarantee that fix leans on, against this
1828 /// crate's own flusher function.
1829 #[tokio::test]
1830 async fn awaiting_the_flusher_join_handle_observes_every_broadcast_first() {
1831 let (broker, events) = broker_recording_block_file_events();
1832 let fs = Arc::new(FileStore::open_in_memory().expect("open in-memory filestore"));
1833 let (tx, rx) = tokio::sync::mpsc::channel(PTY_CHANNEL_CAPACITY);
1834
1835 let flusher_handle = tokio::spawn(run_pty_output_flusher(
1836 rx,
1837 Some(Arc::new(broker)),
1838 "block-1".to_string(),
1839 Some(fs.clone()),
1840 false,
1841 ));
1842
1843 // Sent on a delay from a separate task, standing in for the real PTY
1844 // read loop's own separate blocking thread — proves the ordering
1845 // holds even when the flusher genuinely has to wait on the channel,
1846 // not just the pre-queued-before-first-poll shortcut the coalescing
1847 // tests above deliberately use for their own determinism.
1848 let sender = tokio::spawn(async move {
1849 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1850 tx.send(PtyReadChunk {
1851 ack: None,
1852 data: b"trailing output".to_vec(),
1853 osc_events: Vec::new(),
1854 })
1855 .await
1856 .unwrap();
1857 // Dropping `tx` here closes the channel — the same signal the
1858 // real read loop sends by dropping `pty_tx` on PTY EOF — which
1859 // is what lets the flusher's final accumulation loop unstick
1860 // and return.
1861 });
1862 sender.await.expect("sender task should not panic");
1863
1864 flusher_handle.await.expect("flusher task should not panic");
1865
1866 // The property under test: by the time the join handle above has
1867 // returned, the trailing batch must already be visible — both in
1868 // FileStore and as a broadcast — with no extra yield/sleep needed to
1869 // "catch up" to it. This is the exact sequencing the wait task now
1870 // depends on before it publishes STATUS_DONE.
1871 assert_eq!(
1872 events.lock().unwrap().len(),
1873 1,
1874 "flusher_handle.await must not return until the final batch was broadcast"
1875 );
1876 let data = fs
1877 .read_file("block-1", "term")
1878 .expect("read_file ok")
1879 .expect("data present");
1880 assert_eq!(data, b"trailing output");
1881 }
1882}