1#[cfg(windows)]
17use agentmux_common::win32::NoWindow;
18use std::collections::{HashMap, VecDeque};
19use std::sync::Arc;
20use parking_lot::Mutex;
21use serde::Serialize;
22use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter};
23use tokio::sync::{mpsc, oneshot};
24
25use crate::backend::mps::Broker;
26use agentmux_common::api_types::ShellInputFailure;
27
28use agentmux_common::time::now_ms_u64 as now_ms;
29
30const TAIL_LINES: usize = 400;
32const TAIL_LINE_CHARS: usize = 4000;
33
34#[derive(Clone, Default)]
44pub struct ShellStatusInfo {
45 pub running: bool,
46 pub exit_code: Option<i32>,
47 pub line_count: u64,
48 pub block_id: String,
49 pub cmd: String,
50 pub title: String,
51 pub started_at: u64,
52 pub tail: Option<Arc<Mutex<VecDeque<String>>>>,
55 pub tail_clipped: bool,
57 pub captured: Vec<String>,
59 pub withheld: Option<String>,
61}
62
63#[derive(Clone, Serialize)]
70pub struct ShellSummary {
71 pub shell_id: String,
72 pub block_id: String,
73 pub cmd: String,
74 pub title: String,
75 pub started_at: u64,
76 pub line_count: u64,
77}
78
79struct ShellEntry {
85 stop_tx: oneshot::Sender<()>,
86 stdin_tx: Option<mpsc::UnboundedSender<String>>,
88}
89
90const MAX_EXITED_STATUS: usize = 512;
98
99#[derive(Default)]
100pub struct ShellSessionRegistry {
101 shells: Mutex<HashMap<String, ShellEntry>>,
102 status_map: Mutex<HashMap<String, Arc<Mutex<ShellStatusInfo>>>>,
107 status_order: Mutex<VecDeque<String>>,
110}
111
112impl ShellSessionRegistry {
113 pub fn new() -> Arc<Self> {
114 Arc::new(Self::default())
115 }
116
117 #[cfg(test)]
119 fn insert(&self, shell_id: String, tx: oneshot::Sender<()>) {
120 self.shells.lock().insert(shell_id, ShellEntry { stop_tx: tx, stdin_tx: None });
121 }
122
123 pub fn register_full(
136 &self,
137 shell_id: String,
138 stop_tx: oneshot::Sender<()>,
139 stdin_tx: Option<mpsc::UnboundedSender<String>>,
140 status: Arc<Mutex<ShellStatusInfo>>,
141 ) -> Vec<String> {
142 self.shells.lock().insert(shell_id.clone(), ShellEntry { stop_tx, stdin_tx });
143 self.status_map.lock().insert(shell_id.clone(), status);
144 self.status_order.lock().push_back(shell_id);
145 self.prune_exited_statuses()
147 }
148
149 fn prune_exited_statuses(&self) -> Vec<String> {
155 let mut map = self.status_map.lock();
156 let mut order = self.status_order.lock();
157 let mut evicted = Vec::new();
158 let mut exited = map
159 .values()
160 .filter(|arc| !arc.lock().running)
161 .count();
162 let mut i = 0;
163 while exited > MAX_EXITED_STATUS && i < order.len() {
164 let id = order[i].clone();
165 match map.get(&id) {
166 Some(arc) if !arc.lock().running => {
168 map.remove(&id);
169 order.remove(i);
170 exited -= 1;
171 evicted.push(id);
172 }
173 Some(_) => i += 1,
175 None => {
177 order.remove(i);
178 }
179 }
180 }
181 evicted
182 }
183
184 pub fn stop(&self, shell_id: &str) -> bool {
188 if let Some(entry) = self.shells.lock().remove(shell_id) {
191 let _ = entry.stop_tx.send(());
193 true
194 } else {
195 false
196 }
197 }
198
199 fn remove(&self, shell_id: &str) {
203 self.shells.lock().remove(shell_id);
204 }
207
208 pub fn stop_all(&self) -> usize {
210 self.status_map.lock().clear();
211 self.status_order.lock().clear();
212 let drained: Vec<_> = self.shells.lock().drain().map(|(_, e)| e.stop_tx).collect();
213 let n = drained.len();
214 for tx in drained {
215 let _ = tx.send(());
216 }
217 n
218 }
219
220 pub fn resolve_stdin(
226 &self,
227 shell_id: &str,
228 ) -> Result<mpsc::UnboundedSender<String>, ShellInputFailure> {
229 let shells = self.shells.lock();
230 match shells.get(shell_id) {
231 Some(entry) => match &entry.stdin_tx {
232 Some(tx) => Ok(tx.clone()),
233 None => Err(ShellInputFailure::StdinNotCaptured),
234 },
235 None => Err(ShellInputFailure::NotRunning),
236 }
237 }
238
239 pub fn get_status(&self, shell_id: &str) -> ShellStatusInfo {
244 self.status_map.lock()
245 .get(shell_id)
246 .map(|arc| arc.lock().clone())
247 .unwrap_or_default()
248 }
249
250 pub fn get_status_if_known(&self, shell_id: &str) -> Option<ShellStatusInfo> {
265 self.status_map.lock().get(shell_id).map(|arc| arc.lock().clone())
266 }
267
268 pub fn list_active(&self) -> Vec<ShellSummary> {
277 self.status_map
278 .lock()
279 .iter()
280 .filter_map(|(shell_id, arc)| {
281 let s = arc.lock();
282 if s.running {
283 Some(ShellSummary {
284 shell_id: shell_id.clone(),
285 block_id: s.block_id.clone(),
286 cmd: s.cmd.clone(),
287 title: s.title.clone(),
288 started_at: s.started_at,
289 line_count: s.line_count,
290 })
291 } else {
292 None
293 }
294 })
295 .collect()
296 }
297}
298
299fn kill_tree(pid: u32) {
307 agentmux_common::process::kill_process_group(pid);
312}
313
314pub struct ShellNodeRunner {
315 pub shell_id: String,
316 pub block_id: String,
317 pub cmd: String,
318 pub title: String,
322 pub cwd: Option<String>,
323 pub launch: Option<(String, Vec<String>)>,
327 pub askpass_secret: Option<String>,
330 pub extra_env: HashMap<String, String>,
331 pub broker: Arc<Broker>,
332 pub registry: Arc<ShellSessionRegistry>,
335 pub capture_stdin: bool,
339 pub scrubber: Option<Arc<crate::backend::vault::scrub::Scrubber>>,
342 pub stdin_once: Option<zeroize::Zeroizing<String>>,
345 pub secret_dir: Option<crate::backend::vault::files::SecretDir>,
348 pub capture: Option<crate::backend::vault::capture::Job>,
351}
352
353fn local_command(cmd: &str) -> tokio::process::Command {
358 #[cfg(windows)]
359 {
360 use std::os::windows::process::CommandExt;
361 let mut c = tokio::process::Command::new("cmd");
362 c.as_std_mut().args(["/S", "/C"]).raw_arg(format!("\"{cmd}\""));
363 c
364 }
365 #[cfg(not(windows))]
366 {
367 let mut c = tokio::process::Command::new("sh");
368 c.args(["-c", cmd]);
369 c
370 }
371}
372
373impl ShellNodeRunner {
374 pub async fn run(mut self) {
375 let shell_id = self.shell_id.clone();
376 let block_id = self.block_id.clone();
377 let broker = self.broker.clone();
378
379 let _askpass = self.askpass_secret.clone().map(crate::backend::remote::askpass::Revoke);
380 let mut child_cmd = if let Some((program, args)) = &self.launch {
381 let mut c = tokio::process::Command::new(program);
382 c.args(args);
383 c
384 } else {
385 local_command(&self.cmd)
386 };
387
388 crate::backend::pane_env::sanitize_process_command(&mut child_cmd);
396
397 if let Some(ref cwd) = self.cwd {
406 if std::path::Path::new(cwd).is_dir() {
407 child_cmd.current_dir(cwd);
408 } else {
409 publish_chunk(
410 &broker,
411 &block_id,
412 &shell_id,
413 "system",
414 &format!("[cwd not found: {cwd} — running in the server's working directory]"),
415 now_ms(),
416 );
417 }
418 }
419 for (k, v) in &self.extra_env {
420 child_cmd.env(k, v);
421 }
422
423 child_cmd.stdout(std::process::Stdio::piped());
424 child_cmd.stderr(std::process::Stdio::piped());
425 if self.capture_stdin || self.stdin_once.is_some() {
430 child_cmd.stdin(std::process::Stdio::piped());
431 } else {
432 child_cmd.stdin(std::process::Stdio::null());
433 }
434 #[cfg(windows)]
438 {
439 child_cmd.no_window();
440 }
441 child_cmd.kill_on_drop(true);
443 #[cfg(unix)]
446 {
447 child_cmd.process_group(0);
448 }
449
450 let mut child = match crate::backend::process_tracker::registry::spawn_tracked(&block_id, &mut child_cmd, crate::backend::process_tracker::registry::Join::Adopted) {
454 Ok(c) => c,
455 Err(e) => {
456 publish_chunk(&broker, &block_id, &shell_id, "system", &format!("[spawn error: {e}]"), now_ms());
457 publish_exit(&broker, &block_id, &shell_id, 1, false, now_ms());
458 return;
459 }
460 };
461
462 let pid = child.id();
463 tracing::info!(shell_id = %shell_id, pid = ?pid, capture_stdin = self.capture_stdin, "shell.spawn");
464
465 if let Some(value) = self.stdin_once.take() {
468 if !self.capture_stdin {
469 if let Some(mut writer) = child.stdin.take() {
470 tokio::spawn(async move {
471 let _ = writer.write_all(value.as_bytes()).await;
472 let _ = writer.write_all(b"\n").await;
473 let _ = writer.flush().await;
474 });
475 }
476 }
477 }
478
479 let stdin_tx: Option<mpsc::UnboundedSender<String>> = if self.capture_stdin {
481 let child_stdin = child.stdin.take().expect("stdin piped");
482 let (tx, mut rx) = mpsc::unbounded_channel::<String>();
483 tokio::spawn(async move {
484 let mut writer = BufWriter::new(child_stdin);
485 while let Some(text) = rx.recv().await {
486 if writer.write_all(text.as_bytes()).await.is_err() { break; }
487 if writer.flush().await.is_err() { break; }
488 }
489 });
491 Some(tx)
492 } else {
493 None
494 };
495
496 let status_arc = Arc::new(Mutex::new(ShellStatusInfo {
497 running: true,
498 exit_code: None,
499 line_count: 0,
500 block_id: block_id.clone(),
501 cmd: self.cmd.clone(),
502 title: self.title.clone(),
503 started_at: now_ms(),
504 tail: (self.scrubber.is_some() || self.capture.is_some()).then(|| Arc::new(Mutex::new(VecDeque::new()))),
505 ..Default::default()
506 }));
507 let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
508 let evicted = self.registry.register_full(
509 shell_id.clone(),
510 cancel_tx,
511 stdin_tx,
512 Arc::clone(&status_arc),
513 );
514 for evicted_id in evicted {
515 broker.purge_scope(&format!("shell:{evicted_id}"));
516 }
517 let kill_task = tokio::spawn(async move {
518 match cancel_rx.await {
519 Ok(()) => {
520 if let Some(pid) = pid {
521 let _ = tokio::task::spawn_blocking(move || kill_tree(pid)).await;
522 }
523 true }
525 Err(_) => false, }
527 });
528
529 let stdout = child.stdout.take().expect("stdout piped");
530 let stderr = child.stderr.take().expect("stderr piped");
531
532 type Line = (&'static str, String, u64);
536 let (tx, mut rx) = mpsc::unbounded_channel::<Line>();
537
538 let tx_out = tx.clone();
539 let t_stdout = tokio::spawn(async move {
540 let mut lines = BufReader::new(stdout).lines();
541 while let Ok(Some(line)) = lines.next_line().await {
542 let ts = now_ms();
543 let _ = tx_out.send(("stdout", line, ts));
544 }
545 });
546
547 let tx_err = tx.clone();
548 let t_stderr = tokio::spawn(async move {
549 let mut lines = BufReader::new(stderr).lines();
550 while let Ok(Some(line)) = lines.next_line().await {
551 let ts = now_ms();
552 let _ = tx_err.send(("stderr", line, ts));
553 }
554 });
555
556 drop(tx);
558
559 let mut line_count: u64 = 0;
560 let mut held: Vec<Line> = Vec::new();
563 let mut held_bytes = 0usize;
564 let mut held_cut = false;
565 while let Some((kind, content, ts)) = rx.recv().await {
566 line_count += 1;
567 status_arc.lock().line_count = line_count;
568 if self.capture.is_some() {
569 if held_bytes + content.len() + 1 > crate::backend::vault::capture::MAX_HELD {
570 held_cut = true;
571 } else {
572 held_bytes += content.len() + 1;
573 held.push((kind, content, ts));
574 }
575 continue;
576 }
577 let clean = match &self.scrubber {
578 Some(s) => s.scrub(&content),
579 None => std::borrow::Cow::Borrowed(content.as_str()),
580 };
581 emit(&status_arc, &broker, &block_id, &shell_id, kind, &clean, ts);
582 }
583
584 let _ = tokio::join!(t_stdout, t_stderr);
585
586 self.registry.remove(&shell_id);
589
590 let exit_code = match child.wait().await {
591 Ok(status) => status.code().unwrap_or(-1),
592 Err(_) => -1,
593 };
594
595 if let Some(job) = self.capture.take() {
596 self.publish_captured(job, held, held_cut, exit_code, &status_arc).await;
597 }
598
599 let was_stopped = kill_task.await.unwrap_or(false);
600 tracing::info!(shell_id = %shell_id, exit_code, was_stopped, line_count, "shell.exit");
601
602 {
604 let mut s = status_arc.lock();
605 s.running = false;
606 s.exit_code = Some(exit_code);
607 s.line_count = line_count;
608 }
609
610 publish_exit(&broker, &block_id, &shell_id, exit_code, was_stopped, now_ms());
611 }
612}
613
614impl ShellNodeRunner {
615 async fn publish_captured(&self, mut job: crate::backend::vault::capture::Job, held: Vec<(&'static str, String, u64)>, cut: bool, exit_code: i32, status: &Arc<Mutex<ShellStatusInfo>>) {
618 use crate::backend::vault::capture::Outcome;
619 let given = |line: &str| -> String {
620 match &self.scrubber {
621 Some(s) => s.scrub(line).into_owned(),
622 None => line.to_string(),
623 }
624 };
625 let stdout = zeroize::Zeroizing::new(held.iter().filter(|l| l.0 == "stdout").map(|l| l.1.as_str()).collect::<Vec<_>>().join("\n"));
626 let output = zeroize::Zeroizing::new(held.iter().map(|l| given(&l.1)).collect::<Vec<_>>().join("\n"));
627 let lines = held.len();
628 job.reservation.settle();
630 let (store, capture) = (job.store.clone(), job.capture.clone());
631 let outcome = tokio::task::spawn_blocking(move || capture.finish(&store, &stdout, &output, cut, exit_code))
632 .await
633 .unwrap_or_else(|e| Outcome::Withheld { why: format!("the capture stopped: {e}"), kept_as: None });
634 (job.changed)();
635 match outcome {
636 Outcome::Stored { ids, scrubber, short } => {
637 let all = match &self.scrubber {
639 Some(given) => given.merged(&scrubber),
640 None => scrubber,
641 };
642 match crate::backend::vault::capture::clean_held(&held, &all, &short) {
643 Ok(lines) => {
644 for (kind, clean, ts) in lines {
645 emit(status, &self.broker, &self.block_id, &self.shell_id, kind, &clean, ts);
646 }
647 }
648 Err(why) => {
649 let line = format!("The values went into the Vault, but the output ({lines} lines) is withheld: {why}.");
650 emit(status, &self.broker, &self.block_id, &self.shell_id, "system", &line, now_ms());
651 status.lock().withheld = Some(why);
652 }
653 }
654 status.lock().captured = ids;
655 }
656 Outcome::Withheld { why, kept_as } => {
657 let kept = match &kept_as {
658 Some(id) => format!(" The person can open it in the Vault as [vault:{id}]."),
659 None => String::new(),
660 };
661 let line = format!("The output ({lines} lines) is withheld: the capture failed: {why}.{kept}");
662 emit(status, &self.broker, &self.block_id, &self.shell_id, "system", &line, now_ms());
663 status.lock().withheld = Some(why);
664 }
665 }
666 }
667}
668
669fn emit(status: &Arc<Mutex<ShellStatusInfo>>, broker: &Broker, block_id: &str, shell_id: &str, kind: &str, clean: &str, ts: u64) {
671 {
672 let mut s = status.lock();
673 if s.tail.is_some() && clean.chars().count() > TAIL_LINE_CHARS {
674 s.tail_clipped = true;
675 }
676 if let Some(tail) = &s.tail {
677 let mut t = tail.lock();
678 if t.len() >= TAIL_LINES {
679 t.pop_front();
680 }
681 t.push_back(clean.chars().take(TAIL_LINE_CHARS).collect());
682 }
683 }
684 publish_chunk(broker, block_id, shell_id, kind, clean, ts);
685}
686
687fn shell_scopes(shell_id: &str) -> Vec<String> {
712 vec![format!("shell:{shell_id}")]
713}
714
715#[derive(Debug, Clone, Serialize, ts_rs::TS)]
717#[ts(export, export_to = "../../../frontend/types/rpc/")]
718#[serde(tag = "op", rename_all = "lowercase")]
719pub enum ShellChunkEvent {
720 Chunk {
721 shell_id: String,
722 #[ts(type = r#""stdout" | "stderr" | "system""#)]
723 kind: String,
724 content: String,
725 #[ts(type = "number")]
726 timestamp: u64,
727 },
728 Exit {
729 shell_id: String,
730 exit_code: i32,
731 stopped: bool,
734 #[ts(type = "number")]
735 timestamp: u64,
736 },
737}
738
739#[derive(Debug, Clone, Serialize, ts_rs::TS)]
742#[ts(export, export_to = "../../../frontend/types/rpc/")]
743pub struct ShellNodeCreateEvent {
744 pub shell_id: String,
745 pub cmd: String,
746 pub cwd: Option<String>,
747 pub title: String,
748 #[ts(type = "number")]
749 pub timestamp: u64,
750}
751
752fn publish_chunk(broker: &Broker, _block_id: &str, shell_id: &str, kind: &str, content: &str, ts: u64) {
753 let event = ShellChunkEvent::Chunk { shell_id: shell_id.to_string(), kind: kind.to_string(), content: content.to_string(), timestamp: ts };
754 broker.publish_event::<crate::backend::mps_events::ShellChunk>(&event, shell_scopes(shell_id), 1024);
755}
756
757#[cfg(test)]
758mod tests {
759 #[tokio::test]
762 #[ignore]
763 async fn a_runner_with_a_scrubber_publishes_the_output_without_the_value() {
764 use crate::backend::vault::scrub::Scrubber;
765 const VALUE: &str = "sk_live_abcdefgh1234";
766 let broker = Arc::new(Broker::new());
767 let registry = ShellSessionRegistry::new();
768 let runner = ShellNodeRunner {
769 shell_id: "scrub-1".into(),
770 block_id: "block-1".into(),
771 cmd: format!("echo token={VALUE} && echo fine"),
772 title: "t".into(),
773 cwd: None,
774 launch: None,
775 askpass_secret: None,
776 extra_env: HashMap::new(),
777 broker: Arc::clone(&broker),
778 registry,
779 capture_stdin: false,
780 scrubber: Some(Arc::new(Scrubber::new(&[("api-key-x".to_string(), VALUE.to_string())]))),
781 stdin_once: None,
782 secret_dir: None,
783 capture: None,
784 };
785 runner.run().await;
786 let events = broker.read_event_history(crate::backend::mps::EVENT_SHELL_CHUNK, "shell:scrub-1", 20);
787 let text = events.iter().map(|e| e.data.clone().unwrap_or_default().to_string()).collect::<Vec<_>>().join("
788");
789 assert!(text.contains("token=[vault:api-key-x]") && text.contains("fine"), "{text}");
790 assert!(!text.contains(VALUE), "{text}");
791 }
792
793 #[tokio::test]
795 #[ignore]
796 async fn a_runner_with_a_capture_publishes_only_once_the_value_is_in_the_vault() {
797 use agentmux_common::api_types::{CaptureFrom, CaptureInto, CaptureRule};
798 use crate::backend::vault::{capture, seal};
799 const VALUE: &str = "ghp_abcdefgh12345678";
800 seal::use_test_key();
801 let store = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
802 store.apply_identity_schema_for_tests().unwrap();
803 let run = |id: &str, pattern: &str| {
804 let rule = CaptureRule { into: CaptureInto { kind: Some("api-key".into()), label: Some(format!("Token {id}")), ..Default::default() }, from: CaptureFrom::Regex(pattern.into()) };
805 let cmd = format!("echo token={VALUE} && echo fine");
806 let plan = capture::plan(&store, &[rule], "Agent2-6", &cmd).unwrap();
807 ShellNodeRunner {
808 shell_id: id.into(),
809 block_id: "block-1".into(),
810 cmd,
811 title: "t".into(),
812 cwd: None,
813 launch: None,
814 askpass_secret: None,
815 extra_env: HashMap::new(),
816 broker: Arc::new(Broker::new()),
817 registry: ShellSessionRegistry::new(),
818 capture_stdin: false,
819 scrubber: None,
820 stdin_once: None,
821 secret_dir: None,
822 capture: Some(capture::Job { capture: plan, store: Arc::clone(&store), changed: Box::new(|| {}), reservation: Default::default() }),
823 }
824 };
825 let published = |broker: &Broker, id: &str| {
826 let events = broker.read_event_history(crate::backend::mps::EVENT_SHELL_CHUNK, &format!("shell:{id}"), 20);
827 events.iter().map(|e| e.data.clone().unwrap_or_default().to_string()).collect::<Vec<_>>().join("\n")
828 };
829
830 let r = run("cap-1", r"token=(\S+)");
831 let (broker, registry) = (Arc::clone(&r.broker), Arc::clone(&r.registry));
832 r.run().await;
833 let text = published(&broker, "cap-1");
834 assert!(text.contains("token=[vault:api-key-token-cap-1]") && text.contains("fine"), "{text}");
835 assert!(!text.contains(VALUE), "{text}");
836 assert_eq!(registry.get_status("cap-1").captured, ["api-key-token-cap-1"]);
837
838 let r = run("cap-2", r"key=(\S+)");
839 let (broker, registry) = (Arc::clone(&r.broker), Arc::clone(&r.registry));
840 r.run().await;
841 let text = published(&broker, "cap-2");
842 assert!(text.contains("withheld: the capture failed: the regex matched nothing"), "{text}");
843 assert!(!text.contains(VALUE) && !text.contains("fine"), "{text}");
844 assert_eq!(registry.get_status("cap-2").withheld.as_deref(), Some("the regex matched nothing"));
845 }
846
847 use super::*;
848
849 async fn args_seen_by_script(line: &str) -> String {
852 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
854 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
855 let dir = std::env::temp_dir().join(format!("amx-local-command-{}-{n}", std::process::id()));
856 std::fs::create_dir_all(&dir).unwrap();
857 let (name, body) = if cfg!(windows) {
858 ("args.bat", "@echo off\r\necho [%~1][%~2][%~3]\r\n")
859 } else {
860 ("args.sh", "printf '[%s][%s][%s]' \"$1\" \"$2\" \"$3\"\n")
861 };
862 std::fs::write(dir.join(name), body).unwrap();
863 let script = dir.join(name).display().to_string();
865 let line = if cfg!(windows) { line.replace("SCRIPT", &script) } else { line.replace("SCRIPT", &format!("sh {script}")) };
866 let out = local_command(&line).current_dir(&dir).output().await.unwrap();
867 let _ = std::fs::remove_dir_all(&dir);
868 let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
869 if text.is_empty() {
870 return format!("(no output; {}; stderr: {})", out.status, String::from_utf8_lossy(&out.stderr).trim());
871 }
872 text
873 }
874
875 #[tokio::test]
876 async fn a_quoted_argument_with_spaces_is_one_argument_without_its_quotes() {
877 assert_eq!(args_seen_by_script(r#"SCRIPT "two words" x y"#).await, "[two words][x][y]");
878 assert_eq!(args_seen_by_script(r#"SCRIPT --reason "two words" -- "#).await, "[--reason][two words][--]");
879 }
880
881 #[tokio::test]
882 async fn quotes_inside_an_argument_and_an_apostrophe_survive() {
883 assert_eq!(args_seen_by_script(r#"SCRIPT "it's here" "a=b c" z"#).await, "[it's here][a=b c][z]");
884 }
885
886 #[tokio::test]
887 async fn a_command_line_with_two_commands_runs_both() {
888 let out = local_command("echo one && echo two").output().await.unwrap();
889 let text = String::from_utf8_lossy(&out.stdout);
890 let lines: Vec<&str> = text.lines().map(str::trim).collect();
891 assert_eq!(lines, ["one", "two"]);
892 }
893
894 #[test]
895 fn shell_events_serialize_as_before() {
896 let chunk = ShellChunkEvent::Chunk { shell_id: "s1".into(), kind: "stdout".into(), content: "ok".into(), timestamp: 5 };
897 assert_eq!(
898 serde_json::to_value(&chunk).unwrap(),
899 serde_json::json!({ "shell_id": "s1", "op": "chunk", "kind": "stdout", "content": "ok", "timestamp": 5 })
900 );
901 let exit = ShellChunkEvent::Exit { shell_id: "s1".into(), exit_code: 1, stopped: true, timestamp: 6 };
902 assert_eq!(
903 serde_json::to_value(&exit).unwrap(),
904 serde_json::json!({ "shell_id": "s1", "op": "exit", "exit_code": 1, "stopped": true, "timestamp": 6 })
905 );
906 let created = ShellNodeCreateEvent { shell_id: "s1".into(), cmd: "npm test".into(), cwd: None, title: "npm test".into(), timestamp: 7 };
907 assert_eq!(
908 serde_json::to_value(&created).unwrap(),
909 serde_json::json!({ "shell_id": "s1", "cmd": "npm test", "cwd": null, "title": "npm test", "timestamp": 7 })
910 );
911 }
912
913 #[tokio::test]
914 async fn stop_signals_then_is_idempotent() {
915 let reg = ShellSessionRegistry::new();
916 let (tx, rx) = oneshot::channel::<()>();
917 reg.insert("s1".to_string(), tx);
918 assert!(reg.stop("s1")); assert!(rx.await.is_ok());
920 assert!(!reg.stop("s1")); }
922
923 #[tokio::test]
924 async fn remove_drops_sender_without_signalling() {
925 let reg = ShellSessionRegistry::new();
926 let (tx, rx) = oneshot::channel::<()>();
927 reg.insert("s2".to_string(), tx);
928 reg.remove("s2"); assert!(rx.await.is_err()); assert!(!reg.stop("s2"));
931 }
932
933 #[tokio::test]
934 async fn stop_all_fires_every_handle() {
935 let reg = ShellSessionRegistry::new();
936 let (tx1, rx1) = oneshot::channel::<()>();
937 let (tx2, rx2) = oneshot::channel::<()>();
938 reg.insert("a".to_string(), tx1);
939 reg.insert("b".to_string(), tx2);
940 reg.stop_all();
941 assert!(rx1.await.is_ok());
942 assert!(rx2.await.is_ok());
943 }
944
945 fn register_exited(reg: &ShellSessionRegistry, id: &str, running: bool) {
946 let (tx, _rx) = oneshot::channel::<()>();
947 let status = Arc::new(Mutex::new(ShellStatusInfo {
948 running,
949 exit_code: if running { None } else { Some(0) },
950 line_count: 1,
951 ..Default::default()
952 }));
953 reg.register_full(id.to_string(), tx, None, status);
955 }
956
957 #[tokio::test]
958 async fn exited_statuses_are_capped_oldest_first() {
959 let reg = ShellSessionRegistry::new();
960 let total = MAX_EXITED_STATUS + 10;
961 for i in 0..total {
962 register_exited(®, &format!("s{i}"), false);
963 }
964 assert_eq!(reg.status_map.lock().len(), MAX_EXITED_STATUS);
966 assert!(reg.get_status("s0").exit_code.is_none());
968 assert!(reg.get_status("s9").exit_code.is_none());
969 assert_eq!(reg.get_status(&format!("s{}", total - 1)).exit_code, Some(0));
971 }
972
973 #[tokio::test]
974 async fn running_statuses_are_never_evicted() {
975 let reg = ShellSessionRegistry::new();
976 let total = MAX_EXITED_STATUS + 5;
977 for i in 0..total {
978 register_exited(®, &format!("r{i}"), true); }
980 assert_eq!(reg.status_map.lock().len(), total);
982 assert!(reg.get_status("r0").running);
983 }
984
985 fn register_running_for_block(reg: &ShellSessionRegistry, id: &str, block_id: &str, cmd: &str) {
986 let (tx, _rx) = oneshot::channel::<()>();
987 let status = Arc::new(Mutex::new(ShellStatusInfo {
988 running: true,
989 block_id: block_id.to_string(),
990 cmd: cmd.to_string(),
991 title: cmd.to_string(),
992 started_at: 1_000,
993 ..Default::default()
994 }));
995 reg.register_full(id.to_string(), tx, None, status);
996 }
997
998 #[tokio::test]
999 async fn list_active_returns_only_running_shells_across_all_blocks() {
1000 let reg = ShellSessionRegistry::new();
1001 register_running_for_block(®, "s1", "block-a", "npm run dev");
1002 register_running_for_block(®, "s2", "block-b", "task dev");
1003 register_exited(®, "s3", false); let mut active = reg.list_active();
1006 active.sort_by(|a, b| a.shell_id.cmp(&b.shell_id));
1007
1008 assert_eq!(active.len(), 2);
1009 assert_eq!(active[0].shell_id, "s1");
1010 assert_eq!(active[0].block_id, "block-a");
1011 assert_eq!(active[0].cmd, "npm run dev");
1012 assert_eq!(active[1].shell_id, "s2");
1013 assert_eq!(active[1].block_id, "block-b");
1014 }
1015}
1016
1017fn publish_exit(broker: &Broker, _block_id: &str, shell_id: &str, exit_code: i32, stopped: bool, ts: u64) {
1018 let event = ShellChunkEvent::Exit { shell_id: shell_id.to_string(), exit_code, stopped, timestamp: ts };
1019 broker.publish_event::<crate::backend::mps_events::ShellChunk>(&event, shell_scopes(shell_id), 1024);
1020}