//! Interactive shell output with paging, live follow, and copy actions. use opencode_api::client::Client; use opencode_api::error::Error; use opencode_api::generated::{ LocationQueryInput, SessionMessageShellOutput, SessionMessageShellStatus, ShellGetInput, ShellInfo, ShellOutputInput, }; use opencode_store::Location; use opencode_ui::dialog::{DIALOG_INSET, DialogCx, FooterAction, FooterProps, footer, layout_view}; use opentui::widget::ScrollEdge; use opencode_util::text_boundary; use opentui::input::strip_ansi_sequences; use crate::prelude::*; const PAGE_BYTES: i64 = 64 * 1024; const END: i64 = 9_007_199_254_740_991; pub fn show(tui: &Tui, shell: ShellInfo, location: Location) { let weak = tui.weak(); tui.dialogs.replace( move |cx| build(&weak, cx, shell.clone(), location.clone()), None, DialogOptions::new(DialogSize::XLarge).key("shell-output"), ); tui.dialogs.set_centered(true); } struct Poll { tui: Weak, cx: Weak, id: opencode_api::generated::ShellID, command: String, location: Location, info: RefCell, output: RefCell>, omitted: Cell, error: RefCell, cursor: Cell>, disposed: Cell, timer: Cell>, copied: Cell>, status: Text, note: Text, text: Text, failure: Text, scroll: ScrollBox, foot: View, } #[derive(Clone, Copy, PartialEq, Eq)] enum Copied { Command, Output, } /// What one load read: the info while the shell ran, the first cursor on the first load, and a page. struct Loaded { info: Option, start: Option, page: SessionMessageShellOutput, } fn build(tui: &Weak, cx: &Rc, shell: ShellInfo, location: Location) -> View { let app = &cx.app; let theme = &cx.theme; let height = (i32::from(app.size().1) * 6 / 10 - 6).max(3) as u32; let status = Text::new(app, "").fg(theme.text.muted); let close = Text::new(app, "esc").fg(theme.text.muted).shrink(0.0); let dialogs = cx.dialogs.clone(); close.mouse_pointer(MousePointer::POINTER).on_mouse(move |_, event| { if matches!(event.kind, MouseEventKind::Up(_)) { dialogs.clear(); } }); let header = View::new(app) .row() .justify(Justify::SpaceBetween) .gap(if cx.width() < 60 { 1 } else { 2 }) .child(&Text::new(app, "Shell output").fg(theme.text.base).bold().grow(1.0)) .child(&status) .child(&close); let note = Text::new(app, "Earlier output omitted · showing recent output").fg(theme.text.muted).visible(false); let text = Text::new(app, "").fg(theme.text.base).wrap(WrapMode::Word); let scroll = ScrollBox::new(app).scrollbars(false).sticky(true).sticky_start(ScrollEdge::Bottom).height(height); scroll.add(&text); let failure = Text::new(app, "").fg(theme.text.feedback.error.base).visible(false); let body = View::new(app) .gap(1) .child(&Text::new(app, shell.command.clone()).fg(theme.text.muted).max_height(3).wrap(WrapMode::Word)) .child(¬e) .child(&scroll) .child(&failure); let poll = Rc::new(Poll { tui: tui.clone(), cx: Rc::downgrade(cx), id: shell.id.clone(), command: shell.command.clone(), location, info: RefCell::new(shell), output: RefCell::new(None), omitted: Cell::new(false), error: RefCell::new(String::new()), cursor: Cell::new(None), disposed: Cell::new(false), timer: Cell::new(None), copied: Cell::new(None), status, note, text, failure, scroll: scroll.clone(), foot: View::new(app), }); let kept = cx.keep(bind!(poll, |poll| { let read = (poll.info.borrow().clone(), poll.output.borrow().clone(), poll.omitted.get()); Some((read, poll.error.borrow().clone(), poll.cursor.get(), poll.copied.get(), poll.scroll.scroll_position())) })); if let Some(((info, output, omitted), error, cursor, copied, (x, y))) = kept.flatten() { *poll.info.borrow_mut() = info; *poll.output.borrow_mut() = output; poll.omitted.set(omitted); *poll.error.borrow_mut() = error; poll.cursor.set(cursor); poll.copied.set(copied); scroll.scroll_to(x, y); } let page = f64::from(height); let scroll_command = |key: &str, title: &str, run: fn(&ScrollBox, f64)| { let scroll = scroll.clone(); TuiCommand::inline(key, move |_, _| run(&scroll, page)).title(title).group("Shell") }; let copy_command = |key: &str, title: &str, kind: Copied| { TuiCommand::inline(key, bind!(poll, |poll, _, _| poll.copy(kind))).title(title).group("Shell") }; cx.layer(KeymapLayer::new(vec![ copy_command("c", "Copy command", Copied::Command), copy_command("o", "Copy output", Copied::Output), scroll_command("up", "Scroll output up", |scroll, _| { scroll.scroll_by(0.0, -1.0); }), scroll_command("down", "Scroll output down", |scroll, _| { scroll.scroll_by(0.0, 1.0); }), scroll_command("pageup", "Previous output page", |scroll, page| { scroll.scroll_by(0.0, -page); }), scroll_command("pagedown", "Next output page", |scroll, page| { scroll.scroll_by(0.0, page); }), scroll_command("home", "First loaded output", |scroll, _| { scroll.scroll_to(0.0, 0.0); }), scroll_command("end", "Follow shell output", |scroll, _| { scroll.scroll_to_bottom(); }), ])); poll.render(); poll.draw_footer(); let stop = poll.clone(); let app_for_stop = app.clone(); cx.on_close(Disposer::new(move || { stop.disposed.set(true); if let Some(timer) = stop.timer.take() { app_for_stop.cancel_timer(timer); } })); poll.poll(); layout_view(cx, &header, &body, Some(&poll.foot), DIALOG_INSET, 1) } impl Poll { /// Reads once, then schedules the next read: at once while pages remain, after a second once caught up, and never /// after the shell is gone. fn poll(self: &Rc) { let Some(tui) = self.tui.upgrade() else { return }; let client = tui.data.client().clone(); let running = self.info.borrow().status == SessionMessageShellStatus::Running; let future = load(client, self.id.clone(), self.location.directory.clone(), running, self.cursor.get()); let poll = self.clone(); tui.app.spawn(future, move |cx, result| { if poll.disposed.get() { return; } let (more, missing) = match result { Ok(loaded) => (poll.apply(loaded), false), Err(error) => { let missing = error.reason() == "ShellNotFoundError"; *poll.error.borrow_mut() = if missing { "Shell output is no longer available.".to_owned() } else { "Unable to read shell output. Retrying…".to_owned() }; (false, missing) } }; poll.render(); if missing { return; } let next = poll.clone(); let delay = if more { Duration::ZERO } else { Duration::from_secs(1) }; poll.timer.set(Some(cx.set_timeout(delay, move |_| next.poll()))); }); } /// Takes a load in; returns whether more output is waiting. fn apply(&self, loaded: Loaded) -> bool { if let Some(info) = loaded.info { *self.info.borrow_mut() = info; } if let Some(start) = loaded.start { self.omitted.set(start > 0); } // A live shell's last character may be incomplete: the server then keeps the cursor, and the next read waits. let advanced = self.cursor.get().or(loaded.start).is_none_or(|cursor| loaded.page.cursor > cursor); self.cursor.set(Some(loaded.page.cursor)); let mut output = self.output.borrow_mut(); let mut next = output.take().unwrap_or_default(); next.push_str(&loaded.page.output); // The tail limit counts UTF-16 units but must not split a character. let tail = text_boundary::tail(&next, PAGE_BYTES as usize); if tail.len() < next.len() { self.omitted.set(true); next = tail.to_owned(); } *output = Some(next); self.error.borrow_mut().clear(); advanced && loaded.page.cursor < loaded.page.size } fn render(&self) { let info = self.info.borrow(); let status = match &info.status { SessionMessageShellStatus::Running => "Running".to_owned(), SessionMessageShellStatus::Timeout => "Timed out".to_owned(), SessionMessageShellStatus::Killed => "Killed".to_owned(), _ => match info.exit { Some(code) => format!("Exited · code {code}"), None => "Exited".to_owned(), }, }; self.status.set_text(status); self.note.visible(self.omitted.get()); let text = self.shown(); self.text.set_text(if !text.is_empty() { text } else if self.output.borrow().is_none() { "Loading output…".to_owned() } else { "No captured output. Output redirected to files is not shown here.".to_owned() }); let error = self.error.borrow(); self.failure.set_text(error.as_str()); self.failure.visible(!error.is_empty()); if let Some(tui) = self.tui.upgrade() { tui.app.request_redraw(); } } /// The output without ANSI codes and with `\n` line ends. fn shown(&self) -> String { let output = self.output.borrow(); strip_ansi_sequences(output.as_deref().unwrap_or_default()).replace("\r\n", "\n").replace('\r', "\n") } fn copy(self: &Rc, kind: Copied) { let Some(tui) = self.tui.upgrade() else { return }; let value = match kind { Copied::Command => self.command.clone(), Copied::Output => self.shown(), }; if value.is_empty() { return; } if !crate::features::selection::put(&tui.app, &value) { tui.toasts.error("Failed to copy to clipboard"); return; } self.copied.set(Some(kind)); // A footer action runs inside the footer it replaces, so the redraw waits. tui.app.defer(bind!(self, |poll, _| poll.draw_footer())); } /// The new-designs footer: follow, then a copy action for the command and the output that reads `✓ copied` /// once it copied. fn draw_footer(self: &Rc) { let Some(cx) = self.cx.upgrade() else { return }; let scroll = self.scroll.clone(); let mut follow = FooterAction::new("follow").key("end"); follow.on_trigger = Some(Rc::new(move || { scroll.scroll_to_bottom(); })); let copies = [(Copied::Command, "copy command", "c"), (Copied::Output, "copy output", "o")].map(|(kind, title, key)| { let mut action = if self.copied.get() == Some(kind) { let mut action = FooterAction::new("✓ copied"); action.color = Some(cx.theme.text.feedback.success.base); action } else { FooterAction::new(title).key(key) }; action.on_trigger = Some(Rc::new(bind!(self, |poll| poll.copy(kind)))); action }); self.foot.clear(); self.foot.add(&footer( &cx, FooterProps { primary: [vec![follow], copies.to_vec()].concat(), ..FooterProps::default() }, )); } } async fn load( client: Client, id: opencode_api::generated::ShellID, directory: String, running: bool, cursor: Option, ) -> Result { let location = || Some(LocationQueryInput { directory: Some(directory.clone()) }); let info = match running { true => Some(client.shell_get(&ShellGetInput { id: id.clone(), location: location() }).await?.data), false => None, }; let (cursor, start) = match cursor { Some(cursor) => (cursor, None), None => { let head = client .shell_output(&ShellOutputInput { id: id.clone(), location: location(), cursor: Some(END), limit: None, }) .await?; let start = (head.data.size - PAGE_BYTES).max(0); (start, Some(start)) } }; let page = client .shell_output(&ShellOutputInput { id, location: location(), cursor: Some(cursor), limit: Some(PAGE_BYTES) }) .await? .data; Ok(Loaded { info, start, page }) }