1#![allow(clippy::print_stdout, clippy::print_stderr, clippy::expect_used)]
14
15use anyhow::{Context, Result};
16use ed25519_dalek::SigningKey;
17use std::io::Write;
18use tracing::info;
19
20use hyprstream_rpc_std::tui_client::{ConnectRequest, DisplayMode, SendInputRequest, TuiClient};
21
22pub fn create_tui_client(signing_key: &SigningKey) -> Result<TuiClient> {
27 let sk = signing_key.clone();
28
29 TuiClient::from_provider(&hyprstream_discovery::ProductionRpcClientProvider, sk, None)
30 .context("Failed to create TuiClient")
31}
32
33pub async fn handle_tui_attach(signing_key: &SigningKey, session_id: Option<u32>) -> Result<()> {
39 let sid = session_id.unwrap_or(0);
40 info!(session_id = sid, "Attaching to TUI session");
41
42 let client = create_tui_client(signing_key)?;
43 let (cols, rows) = terminal_size();
44
45 let result = client
47 .connect(&ConnectRequest {
48 session_id: sid,
49 display_mode: DisplayMode::Ansi,
50 cols,
51 rows,
52 })
53 .await
54 .context("Failed to connect to TUI session. Is the TUI service running?")?;
55
56 println!(
57 "Connected to session {} (viewer {})",
58 result.session_id, result.viewer_id
59 );
60
61 let stdout_stream = result.streams.get(1);
63 if let Some(si) = stdout_stream {
64 if !si.topic.is_empty() {
65 info!(
66 topic = %si.topic,
67 broadcast_path = %si.broadcast_path,
68 "Stream info received"
69 );
70 }
71 }
72
73 for win in &result.windows {
75 println!(
76 " Window {}: {} ({} panes)",
77 win.id,
78 win.name,
79 win.panes.len()
80 );
81 }
82
83 if let Some(stream_info) = stdout_stream {
85 if !stream_info.topic.is_empty() {
86 run_attach_loop(stream_info, &client, result.viewer_id).await?;
87 } else {
88 println!("No stream info — session may be inactive.");
89 }
90 } else {
91 println!("No stream info — session may be inactive.");
92 }
93
94 Ok(())
95}
96
97async fn run_attach_loop(
102 stream_info: &hyprstream_rpc_std::tui_client::StreamInfo,
103 client: &TuiClient,
104 viewer_id: u32,
105) -> Result<()> {
106 use hyprstream_rpc::moq_stream::MoqStreamHandle;
107 use hyprstream_rpc::streaming::StreamPayload;
108
109 let broadcast_path = stream_info.broadcast_path.clone();
110 anyhow::ensure!(
111 !broadcast_path.is_empty(),
112 "TUI service did not return a moq broadcast path — server may be in ZMQ-only mode"
113 );
114
115 let mac_key: [u8; 32] = stream_info
116 .mac_key
117 .as_slice()
118 .try_into()
119 .context("mac_key must be 32 bytes")?;
120 let topic = stream_info.topic.clone();
121
122 let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(64);
123
124 let reach = stream_info.announced_at.clone();
131 let qos = hyprstream_rpc::stream_info::StreamOpt::default();
135 let enc_key = *hyprstream_rpc::crypto::StreamKeys::new(topic.clone(), mac_key).enc_key;
139 let mut handle = MoqStreamHandle::networked_with_server_identity(
140 reach,
141 &qos,
142 broadcast_path,
143 mac_key,
144 enc_key,
145 topic,
146 stream_info.moql_server_identity.clone(),
147 );
148 let recv_handle = tokio::spawn(async move {
149 loop {
150 match handle.recv_next().await {
151 Ok(Some(StreamPayload::Data(data))) => {
152 if tx.send(data).await.is_err() {
153 return;
154 }
155 }
156 Ok(Some(StreamPayload::Complete(_))) | Ok(None) => return,
157 Ok(Some(StreamPayload::Error(msg))) => {
158 tracing::warn!("moq stream error: {msg}");
159 return;
160 }
161 Ok(Some(_)) => continue,
162 Err(e) => {
163 tracing::warn!("moq frame recv: {e}");
164 return;
165 }
166 }
167 }
168 });
169
170 let result = run_attach_io(rx, |input| async move {
171 client
172 .send_input(&SendInputRequest {
173 viewer_id,
174 data: input,
175 })
176 .await
177 })
178 .await;
179 recv_handle.abort();
180 result
181}
182
183async fn run_attach_io<F, Fut>(
185 mut rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
186 mut send_input: F,
187) -> Result<()>
188where
189 F: FnMut(Vec<u8>) -> Fut,
190 Fut: std::future::Future<Output = Result<()>>,
191{
192 let (cancel_reader, cancel_writer) = std::os::unix::net::UnixStream::pair()?;
193
194 let orig_termios = enter_raw_mode()?;
196 println!("\r\nAttached to session (ctrl-b d to detach)\r");
197
198 let mut stdout = std::io::stdout();
199
200 let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(64);
202 let stdin_handle = std::thread::spawn(move || {
205 use std::os::fd::AsRawFd;
206 let mut buf = [0u8; 256];
207 loop {
208 let mut fds = [
209 libc::pollfd {
210 fd: libc::STDIN_FILENO,
211 events: libc::POLLIN,
212 revents: 0,
213 },
214 libc::pollfd {
215 fd: cancel_reader.as_raw_fd(),
216 events: libc::POLLIN,
217 revents: 0,
218 },
219 ];
220 let result = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
221 if result < 0
222 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted
223 {
224 continue;
225 }
226 if result <= 0 || fds[1].revents != 0 {
227 break;
228 }
229 if fds[0].revents & libc::POLLIN != 0 {
230 let n =
231 unsafe { libc::read(libc::STDIN_FILENO, buf.as_mut_ptr().cast(), buf.len()) };
232 if n <= 0 || stdin_tx.blocking_send(buf[..n as usize].to_vec()).is_err() {
233 break;
234 }
235 } else if fds[0].revents != 0 {
236 break;
237 }
238 }
239 });
240
241 let mut saw_ctrl_b = false;
243
244 loop {
245 tokio::select! {
246 Some(ansi_data) = rx.recv() => {
247 let _ = stdout.write_all(&ansi_data);
249 let _ = stdout.flush();
250 }
251 Some(input) = stdin_rx.recv() => {
252 let mut detach = false;
254 for &byte in &input {
255 if saw_ctrl_b && byte == b'd' {
256 detach = true;
257 break;
258 }
259 saw_ctrl_b = byte == 0x02; }
261 if detach {
262 break;
263 }
264
265 if let Err(e) = send_input(input).await {
267 tracing::debug!("sendInput failed: {}", e);
268 }
269 }
270 else => break,
271 }
272 }
273
274 drop(stdin_rx);
277 drop(cancel_writer);
278 let reader_result = stdin_handle.join();
279 restore_terminal(&orig_termios);
280 reader_result.map_err(|_| anyhow::anyhow!("attach stdin reader panicked"))?;
281 println!("\r\nDetached from session.");
282 Ok(())
283}
284
285pub async fn handle_tui_new(signing_key: &SigningKey) -> Result<()> {
287 info!("Creating new TUI session");
288
289 let client = create_tui_client(signing_key)?;
290 let window_info = client
291 .create_window()
292 .await
293 .context("Failed to create window. Is the TUI service running?")?;
294
295 println!("Created window {}:", window_info.id);
296 println!(" Name: {}", window_info.name);
297 println!(" Active pane: {}", window_info.active_pane_id);
298 for pane in &window_info.panes {
299 println!(
300 " Pane {}: {}x{} \"{}\"",
301 pane.id, pane.cols, pane.rows, pane.title
302 );
303 }
304
305 Ok(())
306}
307
308pub async fn handle_tui_list(signing_key: &SigningKey) -> Result<()> {
310 info!("Listing TUI sessions");
311
312 let client = create_tui_client(signing_key)?;
313
314 let window_list = client
315 .list_windows(0)
316 .await
317 .context("Failed to list windows. Is the TUI service running?")?;
318
319 if window_list.windows.is_empty() {
320 println!("No active sessions.");
321 println!("\nCreate one with: hyprstream tui new");
322 } else {
323 println!("┌─────────────────────────────────────────────────┐");
324 println!("│ TUI Sessions │");
325 println!("├──────┬──────────────────┬───────┬───────────────┤");
326 println!("│ ID │ Name │ Panes │ Active Pane │");
327 println!("├──────┼──────────────────┼───────┼───────────────┤");
328 for win in &window_list.windows {
329 println!(
330 "│ {:4} │ {:16} │ {:5} │ {:13} │",
331 win.id,
332 truncate_str(&win.name, 16),
333 win.panes.len(),
334 win.active_pane_id,
335 );
336 }
337 println!("└──────┴──────────────────┴───────┴───────────────┘");
338 }
339
340 Ok(())
341}
342
343pub async fn handle_tui_detach() -> Result<()> {
345 info!("Detaching from TUI session");
346 println!("Detached.");
348 Ok(())
349}
350
351pub fn terminal_size() -> (u16, u16) {
353 #[cfg(unix)]
354 {
355 use std::os::unix::io::AsRawFd;
356 let fd = std::io::stdout().as_raw_fd();
357 let mut ws = libc::winsize {
358 ws_row: 0,
359 ws_col: 0,
360 ws_xpixel: 0,
361 ws_ypixel: 0,
362 };
363 if unsafe { libc::ioctl(fd, libc::TIOCGWINSZ, &mut ws) } == 0
364 && ws.ws_col > 0
365 && ws.ws_row > 0
366 {
367 return (ws.ws_col, ws.ws_row);
368 }
369 }
370 (80, 24)
371}
372
373#[cfg(unix)]
375pub fn enter_raw_mode() -> Result<libc::termios> {
376 use std::os::unix::io::AsRawFd;
377
378 let fd = std::io::stdin().as_raw_fd();
379 let mut orig = std::mem::MaybeUninit::<libc::termios>::uninit();
380 if unsafe { libc::tcgetattr(fd, orig.as_mut_ptr()) } != 0 {
381 anyhow::bail!("Failed to get terminal attributes");
382 }
383 let orig = unsafe { orig.assume_init() };
384
385 let mut raw = orig;
386 raw.c_lflag &= !(libc::ECHO | libc::ICANON | libc::ISIG | libc::IEXTEN);
387 raw.c_iflag &= !(libc::IXON | libc::ICRNL | libc::BRKINT | libc::INPCK | libc::ISTRIP);
388 raw.c_cflag |= libc::CS8;
389 raw.c_oflag &= !libc::OPOST;
390 raw.c_cc[libc::VMIN] = 1;
391 raw.c_cc[libc::VTIME] = 0;
392
393 if unsafe { libc::tcsetattr(fd, libc::TCSAFLUSH, &raw) } != 0 {
394 anyhow::bail!("Failed to set raw terminal mode");
395 }
396
397 Ok(orig)
398}
399
400#[cfg(not(unix))]
401pub fn enter_raw_mode() -> Result<()> {
402 Ok(())
403}
404
405#[cfg(unix)]
407pub fn restore_terminal(orig: &libc::termios) {
408 use std::os::unix::io::AsRawFd;
409 let fd = std::io::stdin().as_raw_fd();
410 unsafe { libc::tcsetattr(fd, libc::TCSAFLUSH, orig) };
411}
412
413#[cfg(not(unix))]
414pub fn restore_terminal(_orig: &()) {}
415
416pub async fn handle_tui_play(
422 signing_key: &SigningKey,
423 cast_file: &std::path::Path,
424 session_id: u32,
425 loop_playback: bool,
426) -> Result<()> {
427 use hyprstream_tui::cast_app::{CastPlayerApp, LogEntry};
428 use waxterm::app::TerminalConfig;
429
430 info!(?cast_file, session_id, "Playing cast file");
431
432 let content = std::fs::read_to_string(cast_file)
433 .with_context(|| format!("Failed to read cast file: {}", cast_file.display()))?;
434
435 let name = cast_file
436 .file_stem()
437 .and_then(|s| s.to_str())
438 .unwrap_or("cast")
439 .to_owned();
440
441 let mut app = CastPlayerApp::new(vec![LogEntry {
442 name,
443 cast_content: content,
444 }]);
445 app.set_loop(loop_playback);
446
447 let client = create_tui_client(signing_key)?;
449 let (cols, rows) = terminal_size();
450
451 let result = client
452 .connect(&ConnectRequest {
453 session_id,
454 display_mode: DisplayMode::Capnp,
455 cols,
456 rows,
457 })
458 .await
459 .context("Failed to connect to TUI session. Is the TUI service running?")?;
460
461 println!(
462 "Playing {} in session {} (viewer {})",
463 cast_file.display(),
464 result.session_id,
465 result.viewer_id,
466 );
467
468 let active_pane_id = result
470 .windows
471 .first()
472 .map(|w| w.active_pane_id)
473 .unwrap_or(1);
474
475 let (pane_cols, pane_rows) = result
476 .windows
477 .first()
478 .and_then(|w| w.panes.iter().find(|p| p.id == active_pane_id))
479 .map(|p| (p.cols, p.rows))
480 .unwrap_or((cols, rows));
481
482 let config = TerminalConfig::new().cols(pane_cols).rows(pane_rows);
484 let process = crate::tui::process::spawn_app_process(app, config);
485
486 let _ = client
488 .send_input(&SendInputRequest {
489 viewer_id: result.viewer_id,
490 data: vec![],
491 })
492 .await;
493
494 let stdin_stream = result.streams.first();
498 forward_process_output(
499 process,
500 &client,
501 signing_key,
502 result.viewer_id,
503 active_pane_id,
504 pane_cols,
505 pane_rows,
506 stdin_stream,
507 )
508 .await?;
509
510 println!("Playback complete.");
511 Ok(())
512}
513
514pub async fn forward_process_output(
525 mut process: crate::tui::process::PaneProcess,
526 client: &TuiClient,
527 signing_key: &SigningKey,
528 viewer_id: u32,
529 _pane_id: u32,
530 initial_cols: u16,
531 initial_rows: u16,
532 stdin_stream: Option<&hyprstream_rpc_std::tui_client::StreamInfo>,
533) -> Result<()> {
534 use crate::tui::process::ProcessInput;
535
536 let resize_tx = process.input_tx.clone();
537
538 let resize_client = create_tui_client(signing_key)?;
542 let poll_client = if stdin_stream.is_some_and(|stream| !stream.topic.is_empty()) {
543 Some(create_tui_client(signing_key)?)
544 } else {
545 None
546 };
547
548 let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO) } == 1;
551 let orig_termios = if is_tty {
552 Some(enter_raw_mode()?)
553 } else {
554 None
555 };
556
557 let stdin_forward;
562 let mut cancel_fd: Option<std::os::unix::io::RawFd> = None;
563 if is_tty {
564 let stdin_tx = process.input_tx.clone();
565 let (stdin_async_tx, mut stdin_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(64);
566
567 let mut pipe_fds = [0i32; 2];
569 if unsafe { libc::pipe(pipe_fds.as_mut_ptr()) } == 0 {
570 let read_pipe = pipe_fds[0];
571 let write_pipe = pipe_fds[1];
572 cancel_fd = Some(write_pipe);
573
574 std::thread::spawn(move || {
576 let stdin_fd = libc::STDIN_FILENO;
577 let mut buf = [0u8; 256];
578 loop {
579 let mut fds = [
581 libc::pollfd {
582 fd: stdin_fd,
583 events: libc::POLLIN,
584 revents: 0,
585 },
586 libc::pollfd {
587 fd: read_pipe,
588 events: libc::POLLIN,
589 revents: 0,
590 },
591 ];
592 let ret = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
593 if ret <= 0 {
594 break;
595 }
596 if fds[1].revents & libc::POLLIN != 0 {
598 break;
599 }
600 if fds[0].revents & libc::POLLIN != 0 {
602 let n = unsafe { libc::read(stdin_fd, buf.as_mut_ptr().cast(), buf.len()) };
603 if n <= 0 {
604 break;
605 }
606 let data = buf[..n as usize].to_vec();
607 if stdin_async_tx.blocking_send(data).is_err() {
608 break;
609 }
610 }
611 }
612 unsafe {
613 libc::close(read_pipe);
614 }
615 });
616 }
617
618 stdin_forward = Some(tokio::spawn(async move {
619 while let Some(data) = stdin_rx.recv().await {
620 if stdin_tx.send(ProcessInput::Stdin(data)).await.is_err() {
621 break;
622 }
623 }
624 }));
625 } else {
626 stdin_forward = None;
627 };
628
629 let resize_handle = tokio::spawn(async move {
631 let mut cur = (initial_cols, initial_rows);
632 loop {
633 tokio::time::sleep(std::time::Duration::from_secs(1)).await;
634 if let Ok((c, r)) = query_pane_size(&resize_client).await {
635 if c > 0 && r > 0 && (c, r) != cur {
636 cur = (c, r);
637 let _ = resize_tx
638 .send(ProcessInput::Resize { cols: c, rows: r })
639 .await;
640 }
641 }
642 }
643 });
644
645 let stdin_input_tx = process.input_tx.clone();
649 let stdin_handle = if let Some(poll_client) = poll_client {
650 let poll_viewer_id = viewer_id;
651 let handle = tokio::spawn(async move {
652 use crate::tui::shell_client::poll_stdin_rpc;
653 loop {
654 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
655 match poll_stdin_rpc(&poll_client, poll_viewer_id).await {
656 Ok(data) if !data.is_empty() => {
657 if stdin_input_tx
658 .send(ProcessInput::Stdin(data))
659 .await
660 .is_err()
661 {
662 break;
663 }
664 }
665 Err(_) => break,
666 _ => {}
667 }
668 }
669 });
670 Some(handle)
671 } else {
672 None
673 };
674
675 #[cfg(unix)]
677 let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
678
679 loop {
681 #[cfg(unix)]
682 let recv = tokio::select! {
683 biased;
684 _ = sigterm.recv() => None,
685 maybe = process.stdout_rx.recv() => maybe,
686 };
687 #[cfg(not(unix))]
688 let recv = process.stdout_rx.recv().await;
689
690 let data = match recv {
691 Some(d) => d,
692 None => break,
693 };
694
695 if let Err(e) = client
696 .send_input(&SendInputRequest {
697 viewer_id,
698 data: data.clone(),
699 })
700 .await
701 {
702 tracing::debug!("sendInput failed: {}", e);
703 break;
704 }
705 }
706
707 let _ = tokio::time::timeout(
711 std::time::Duration::from_millis(500),
712 client.disconnect(viewer_id),
713 )
714 .await;
715
716 resize_handle.abort();
717 if let Some(h) = stdin_forward {
718 h.abort();
719 }
720 if let Some(h) = stdin_handle {
721 h.abort();
722 }
723 if let Some(fd) = cancel_fd {
725 unsafe {
726 libc::write(fd, b"x".as_ptr().cast(), 1);
727 }
728 unsafe {
729 libc::close(fd);
730 }
731 }
732 if let Some(ref orig) = orig_termios {
733 restore_terminal(orig);
734 }
735 Ok(())
736}
737
738async fn query_pane_size(client: &TuiClient) -> Result<(u16, u16)> {
740 let window_list = client.list_windows(0).await?;
741 if let Some(win) = window_list.windows.first() {
742 if let Some(pane) = win.panes.iter().find(|p| p.id == win.active_pane_id) {
743 return Ok((pane.cols, pane.rows));
744 }
745 if let Some(pane) = win.panes.first() {
746 return Ok((pane.cols, pane.rows));
747 }
748 }
749 anyhow::bail!("no panes found")
750}
751
752fn truncate_str(s: &str, max_len: usize) -> String {
754 if s.len() <= max_len {
755 s.to_owned()
756 } else {
757 format!("{}…", &s[..max_len - 1])
758 }
759}
760
761#[cfg(test)]
762mod attach_lifecycle_tests {
763 #[test]
764 #[ignore = "child seam; run tests/tui_attach_pty.py against this test binary"]
765 fn attach_pty_child() {
766 if std::env::var_os("HYPRSTREAM_ATTACH_PTY_CHILD").is_none() {
767 return;
768 }
769 let rt = tokio::runtime::Builder::new_current_thread()
770 .enable_all()
771 .build()
772 .expect("create attach test runtime");
773 rt.block_on(async {
774 let (_tx, rx) = tokio::sync::mpsc::channel(64);
775 super::run_attach_io(rx, |_| async { Ok(()) })
776 .await
777 .expect("attach terminal loop");
778 });
779 eprintln!("ATTACH_LOOP_RETURNED");
780 drop(rt);
781 eprintln!("ATTACH_RUNTIME_DROPPED");
782 }
783}