fix(cli-rs): drop the diff viewer with its panel or route

Shared::current kept the last viewer alive after its panel closed or its
route left, so an open file menu held the keymap in menu mode and the
last-turn watch kept loading diffs. The panel host now keeps what its
builder returns, and the route slot keeps the route viewer; dropping
them ends the viewer's keys, menu, and watch (carbon-1).
This commit is contained in:
Simon Klee
2026-11-05 01:19:50 +01:00
Unverified
parent ba712f9654
commit 165541e854
5 changed files with 226 additions and 29 deletions
+11 -5
View File
@@ -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<dyn Fn(&Tui, &View, &Input<'_>)>;
/// 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<dyn Fn(&Tui, &View, &Input<'_>) -> Box<dyn Any>>;
#[derive(Default)]
pub struct Panels {
@@ -128,6 +129,7 @@ impl Panels {
pub struct Host {
pub root: View,
target: Target,
_content: Option<Box<dyn Any>>,
}
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 {
@@ -161,8 +161,6 @@ struct RouteData {
pub struct Shared {
pub memory: RefCell<Memory>,
route: RefCell<Option<RouteData>>,
/// The viewer last mounted; it lives until the next one replaces it.
current: RefCell<Option<Rc<Viewer>>>,
}
pub fn plugin() -> Definition<Tui> {
@@ -180,6 +178,8 @@ pub fn plugin() -> Definition<Tui> {
};
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<Tui> {
));
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),
@@ -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<MemoryRoute> {
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<Tui>,
memory: Memory,
turns: Cell<i64>,
}
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();
}
@@ -11,6 +11,7 @@ mod app;
mod attach;
mod complete;
mod composer;
mod diffs;
mod editor;
mod form;
mod integrations;
@@ -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<dyn std::any::Any>
},
),
);