diff --git a/packages/cli-rs/crates/tui/src/panel/mod.rs b/packages/cli-rs/crates/tui/src/panel/mod.rs index b7296b8a674..1151769b565 100644 --- a/packages/cli-rs/crates/tui/src/panel/mod.rs +++ b/packages/cli-rs/crates/tui/src/panel/mod.rs @@ -5,6 +5,7 @@ //! raised, focusable box that the plugin fills through the builder it registered with [`Panels::register`] //! (P.1 connects the `session.panel` slot to it; E.15a's diff viewer is the first user). +use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::rc::Rc; @@ -36,8 +37,8 @@ pub struct Input<'a> { pub focused: bool, } -/// Builds a panel's content into the host's root. -pub type Builder = Rc)>; +/// Builds a panel's content into the host's root, and returns what the host keeps alive while it shows the panel. +pub type Builder = Rc) -> Box>; #[derive(Default)] pub struct Panels { @@ -128,6 +129,7 @@ impl Panels { pub struct Host { pub root: View, target: Target, + _content: Option>, } impl Host { @@ -144,7 +146,7 @@ impl Host { Presentation::Panel => theme.background.raised.base, Presentation::Fullscreen => theme.background.base, }); - if let Some(builder) = tui.panels.builder(&target) { + let content = tui.panels.builder(&target).map(|builder| { builder( tui, &root, @@ -154,9 +156,13 @@ impl Host { presentation, focused, }, - ); + ) + }); + Self { + root, + target, + _content: content, } - Self { root, target } } pub fn target(&self) -> &Target { diff --git a/packages/cli-rs/crates/tui/src/plugins/diffs/viewer.rs b/packages/cli-rs/crates/tui/src/plugins/diffs/viewer.rs index 85df2ea934f..b9b6fd6fd62 100644 --- a/packages/cli-rs/crates/tui/src/plugins/diffs/viewer.rs +++ b/packages/cli-rs/crates/tui/src/plugins/diffs/viewer.rs @@ -161,8 +161,6 @@ struct RouteData { pub struct Shared { pub memory: RefCell, route: RefCell>, - /// The viewer last mounted; it lives until the next one replaces it. - current: RefCell>>, } pub fn plugin() -> Definition { @@ -180,6 +178,8 @@ pub fn plugin() -> Definition { }; let viewer = Viewer::mount(tui, &panel, place, i64::from(input.width)); host.add(&viewer.root); + // The panel's host keeps the viewer, so its keys, menu, and watch go when the panel closes. + Box::new(viewer) }), ); let route = shared.clone(); @@ -206,11 +206,6 @@ pub fn plugin() -> Definition { )); let weak = tui.weak(); setup.on_dispose(move || { - if let Some(viewer) = shared.current.take() - && let Some(layer) = viewer.layer.borrow_mut().take() - { - layer.dispose(); - } if let Some(tui) = weak.upgrade() { tui.panels.release(&tui, ID); } @@ -400,11 +395,6 @@ impl Viewer { passes: Cell::new(0), this: this.clone(), }); - // The previous viewer's keys go with it. - let previous = shared.current.replace(Some(viewer.clone())); - if let Some(layer) = previous.and_then(|previous| previous.layer.borrow_mut().take()) { - layer.dispose(); - } viewer.install(tui); viewer.load(); super::sources::watch(&viewer); @@ -423,17 +413,15 @@ impl Viewer { (Some(host.id()), Condition::Always) } Place::Route { .. } => { - let weak = self.this.clone(); let tui = self.tui.clone(); let enabled = Condition::when(move || { - let shown = tui.upgrade().is_some_and(|tui| { + tui.upgrade().is_some_and(|tui| { tui.route() == Route::Plugin { id: ID.to_owned(), name: ROUTE.to_owned(), } - }); - shown && weak.upgrade().is_some_and(|viewer| viewer.is_current()) + }) }); (None, enabled) } @@ -453,14 +441,6 @@ impl Viewer { }); } - fn is_current(&self) -> bool { - self.shared - .current - .borrow() - .as_ref() - .is_some_and(|current| std::ptr::eq(Rc::as_ptr(current), self)) - } - pub(super) fn session(&self) -> Option<&SessionID> { match &self.place { Place::Panel { session, .. } => Some(session), diff --git a/packages/cli-rs/crates/tui/tests/all/diffs.rs b/packages/cli-rs/crates/tui/tests/all/diffs.rs new file mode 100644 index 00000000000..1810dd948c8 --- /dev/null +++ b/packages/cli-rs/crates/tui/tests/all/diffs.rs @@ -0,0 +1,209 @@ +//! The diff viewer's lifetime (`reviews/ms3-ms4.review-carbon.md` carbon-1): a viewer goes with its panel, so its +//! file menu and its last-turn watch end when the panel closes. + +use std::cell::Cell; +use std::sync::Arc; +use std::time::Duration; + +use opencode_api::client::Client; +use opencode_api::generated::SessionID; +use opencode_api::memory::{Memory, Route as MemoryRoute}; +use opencode_local::cli_config::{self, Resolved}; +use opencode_store::SessionStatus; +use opencode_tui::{Deps, Route, Tui}; +use opentui::prelude::{MouseButton, MouseEventKind}; +use opentui::testing::TestApp; +use serde_json::{Value, json}; + +const DIRECTORY: &str = "/project"; + +fn routes() -> Vec { + let location = json!({ "directory": DIRECTORY, "project": { "id": "proj", "directory": DIRECTORY, "canonical": DIRECTORY } }); + let list = |data: Value| json!({ "location": location, "data": data }); + let session = json!({ + "id": "ses_a", "title": "Review", "projectID": "proj", "cost": 0, + "tokens": { "input": 0, "output": 0, "reasoning": 0, "cache": { "read": 0, "write": 0 } }, + "time": { "created": 1, "updated": 1 }, + "location": { "directory": DIRECTORY }, + }); + let diff = json!({ + "file": "src/main.rs", "patch": "@@ -1 +1 @@\n-old\n+new\n", "additions": 1, "deletions": 1, + "status": "modified", + }); + vec![ + MemoryRoute::json("GET", "/api/location", 200, &location), + MemoryRoute::json("GET", "/api/agent", 200, &list(json!([]))), + MemoryRoute::json("GET", "/api/model", 200, &list(json!([]))), + MemoryRoute::json( + "GET", + "/api/session/ses_a", + 200, + &json!({ "data": session }), + ), + MemoryRoute::json( + "GET", + "/api/session", + 200, + &json!({ "data": [], "cursor": {} }), + ), + MemoryRoute::json( + "GET", + "/api/session/ses_a/diff", + 200, + &json!({ "data": [diff] }), + ), + MemoryRoute::json("GET", "/api/vcs/base", 200, &list(Value::Null)), + MemoryRoute::json("GET", "/api/vcs/diff", 200, &list(json!([diff]))), + MemoryRoute::json( + "GET", + "/api/session/:id/message", + 200, + &json!({ "data": [], "cursor": {} }), + ), + MemoryRoute::json("GET", "/api/session/:id/inbox", 200, &json!({ "data": [] })), + MemoryRoute::json( + "GET", + "/api/session/:id/permission", + 200, + &json!({ "data": [] }), + ), + ] +} + +struct Harness { + app: TestApp, + tui: std::rc::Rc, + memory: Memory, + turns: Cell, +} + +fn mount(route: Route) -> Harness { + let memory = Memory::new(routes()); + let client = Client::with_transport("http://opencode.local", Arc::new(memory.clone())).unwrap(); + let app = TestApp::new(140, 30); + let config = json!({ "animations": false, "session": { "sidebar": "hide" }, "diffs": { "source": "turn" } }); + let info = cli_config::decode_text(&config.to_string()).unwrap(); + let tui = opencode_tui::mount( + &app, + Deps { + client, + directory: DIRECTORY.into(), + config: Resolved::new(info, |_| None), + roots: None, + route, + continue_: false, + events: true, + }, + ); + Harness { + app, + tui, + memory, + turns: Cell::new(0), + } +} + +impl Harness { + fn wait_for(&self, what: &str) -> String { + let found = self + .app + .wait_until(Duration::from_secs(5), || self.app.text().contains(what)); + let screen = self.app.text(); + assert!(found, "{what} never showed:\n{screen}"); + screen + } + + /// Right-clicks the file's header, and waits for its menu. + fn open_menu(&self) { + let screen = self.wait_for("src/main.rs"); + let (y, line) = screen + .lines() + .enumerate() + .find(|(_, line)| line.contains("src/main.rs")) + .unwrap(); + let x = line[..line.find("src/main.rs").unwrap()].chars().count() as u16; + self.app + .mouse(MouseEventKind::Down(MouseButton::Right), x, y as u16); + self.wait_for("Mark complete"); + assert_eq!(self.tui.keymap.mode(), "menu"); + } + + /// The menu is gone, with its mode. + fn assert_menu_closed(&self) { + self.app.advance(Duration::from_millis(1)); + let screen = self.app.text(); + assert!( + !screen.contains("Mark complete"), + "the menu stayed:\n{screen}" + ); + assert_ne!(self.tui.keymap.mode(), "menu", "the menu kept its mode"); + } + + fn diff_reads(&self) -> usize { + self.memory + .requests() + .iter() + .filter(|logged| logged.method == "GET" && logged.path == "/api/session/ses_a/diff") + .count() + } + + /// A turn of `ses_a` starts and ends. + fn turn(&self) { + for (kind, status) in [ + ("session.execution.started", SessionStatus::Running), + ("session.execution.succeeded", SessionStatus::Idle), + ] { + let turn = self.turns.get() + 1; + self.turns.set(turn); + self.memory.emit(&json!({ + "id": format!("evt_{turn}"), "created": turn, "type": kind, + "durable": { "aggregateID": "ses_a", "seq": turn, "version": 1 }, + "data": { "sessionID": "ses_a" }, + })); + let id = SessionID("ses_a".into()); + let seen = self.app.wait_until(Duration::from_secs(5), || { + self.tui.data.read(|state| state.status(&id)) == status + }); + assert!(seen, "{kind} did not set the status"); + } + } +} + +#[test] +fn closing_the_panel_ends_its_file_menu_and_turn_watch() { + let h = mount(Route::Session { + id: SessionID("ses_a".into()), + }); + h.wait_for("Review"); + h.tui.keymap.dispatch("diff.open", None); + h.wait_for("src/main.rs"); + // While the panel is open, an ended turn loads the diff again. + let reads = h.diff_reads(); + h.turn(); + let found = h + .app + .wait_until(Duration::from_secs(5), || h.diff_reads() > reads); + assert!(found, "an ended turn did not load the diff again"); + h.open_menu(); + h.tui.panels.close(&h.tui); + h.assert_menu_closed(); + + let reads = h.diff_reads(); + h.turn(); + h.app.advance(Duration::from_millis(200)); + assert_eq!( + h.diff_reads(), + reads, + "the closed viewer loaded the turn again" + ); +} + +#[test] +fn leaving_the_route_ends_its_file_menu() { + let h = mount(Route::Home); + h.wait_for("/project"); + h.tui.keymap.dispatch("diff.open", None); + h.open_menu(); + h.tui.navigate(Route::Home); + h.assert_menu_closed(); +} diff --git a/packages/cli-rs/crates/tui/tests/all/main.rs b/packages/cli-rs/crates/tui/tests/all/main.rs index 262349cadd7..5a37807e3c3 100644 --- a/packages/cli-rs/crates/tui/tests/all/main.rs +++ b/packages/cli-rs/crates/tui/tests/all/main.rs @@ -11,6 +11,7 @@ mod app; mod attach; mod complete; mod composer; +mod diffs; mod editor; mod form; mod integrations; diff --git a/packages/cli-rs/crates/tui/tests/all/tabs.rs b/packages/cli-rs/crates/tui/tests/all/tabs.rs index 0b9a75fcc13..4a81eb2e736 100644 --- a/packages/cli-rs/crates/tui/tests/all/tabs.rs +++ b/packages/cli-rs/crates/tui/tests/all/tabs.rs @@ -260,6 +260,7 @@ fn a_split_panel_shows_beside_the_session_and_resizes() { &tui.app, format!("panel for {}", input.target.session), )); + Box::new(()) as Box }, ), );