chore(cli-rs): format the composer and client MCP files

This commit is contained in:
Simon Klee
2026-11-05 00:08:19 +01:00
Unverified
parent 3432fcdb0e
commit d77526b247
9 changed files with 262 additions and 123 deletions
+3 -3
View File
@@ -171,7 +171,8 @@ impl Connector for Tungstenite {
}
}
let close = tokio_tungstenite::tungstenite::protocol::CloseFrame {
code: tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::Normal,
code:
tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::Normal,
reason: "".into(),
};
let _ = sink.send(ws::Message::Close(Some(close))).await;
@@ -550,8 +551,7 @@ mod tests {
json!({ "content": [{ "type": "text", "text": "hi" }] })
);
assert_eq!(
peer.call(json!({ "name": "fail", "arguments": {} }))
.await["result"],
peer.call(json!({ "name": "fail", "arguments": {} })).await["result"],
json!({ "content": [{ "type": "text", "text": "boom" }], "isError": true })
);
assert_eq!(
@@ -10,7 +10,9 @@ use std::rc::Rc;
use std::sync::{Arc, Mutex};
use opencode_api::client::Auth;
use opencode_api::client_mcp::{self, Connection, Connector, Options, Tool, ToolResult, Tungstenite};
use opencode_api::client_mcp::{
self, Connection, Connector, Options, Tool, ToolResult, Tungstenite,
};
use opencode_api::generated::{SessionID, V2Event};
use serde_json::{Map, Value, json};
use tokio::sync::oneshot;
@@ -72,7 +74,12 @@ pub fn install(tui: &Rc<Tui>) {
})
}),
Kind::Write => {
let Some(text) = call.text.as_ref().and_then(Value::as_str).map(str::to_owned) else {
let Some(text) = call
.text
.as_ref()
.and_then(Value::as_str)
.map(str::to_owned)
else {
done(ToolResult::error("text must be a string"));
return;
};
@@ -105,7 +112,10 @@ pub fn sync(tui: &Tui) {
let client = tui.data.client();
let directory = crate::features::location::current(tui)
.map(|location| location.directory)
.unwrap_or_else(|| tui.data.read(|state| state.default_location().directory.clone()));
.unwrap_or_else(|| {
tui.data
.read(|state| state.default_location().directory.clone())
});
let (url, headers) = endpoint(client.base_url(), client.credentials());
let key = tui
.settings
@@ -143,9 +153,16 @@ pub fn sync(tui: &Tui) {
fn endpoint(base: &url::Url, auth: Option<&Auth>) -> (url::Url, Vec<(String, String)>) {
let mut url = base.clone();
match auth {
Some(auth @ Auth::Basic { .. }) => (url, vec![("authorization".to_owned(), format!("Basic {}", auth.token()))]),
Some(auth @ Auth::Basic { .. }) => (
url,
vec![(
"authorization".to_owned(),
format!("Basic {}", auth.token()),
)],
),
Some(auth @ Auth::Query { .. }) => {
url.query_pairs_mut().append_pair("auth_token", &auth.token());
url.query_pairs_mut()
.append_pair("auth_token", &auth.token());
(url, Vec::new())
}
None => (url, Vec::new()),
@@ -159,22 +176,24 @@ fn tools(proxy: opentui::prelude::AppProxy) -> Vec<Tool> {
name: name.to_owned(),
description: Some(description.to_owned()),
input_schema: schema.as_object().cloned().unwrap_or_default(),
handler: Arc::new(move |args: Map<String, Value>, context: client_mcp::Context| {
let (reply, result) = oneshot::channel();
let call = Call {
tool: kind,
session: context.session_id,
text: args.get("text").cloned(),
reply: Mutex::new(Some(reply)),
};
let sent = proxy.send(call).map_err(|error| error.to_string());
Box::pin(async move {
sent?;
result
.await
.map_err(|_| "Unable to load terminal".to_owned())
})
}),
handler: Arc::new(
move |args: Map<String, Value>, context: client_mcp::Context| {
let (reply, result) = oneshot::channel();
let call = Call {
tool: kind,
session: context.session_id,
text: args.get("text").cloned(),
reply: Mutex::new(Some(reply)),
};
let sent = proxy.send(call).map_err(|error| error.to_string());
Box::pin(async move {
sent?;
result
.await
.map_err(|_| "Unable to load terminal".to_owned())
})
},
),
}
};
vec![
@@ -203,7 +222,11 @@ type Done = Box<dyn FnOnce(&Tui, Result<String, ToolResult>)>;
/// The terminal `open_terminal` shows for the calling session (the selected one, else the newest, else a new one),
/// or a tool failure.
fn terminal_for(tui: &Tui, called_by: Option<String>, done: impl FnOnce(&Tui, Result<String, ToolResult>) + 'static) {
fn terminal_for(
tui: &Tui,
called_by: Option<String>,
done: impl FnOnce(&Tui, Result<String, ToolResult>) + 'static,
) {
let done: Done = Box::new(done);
let Some(called_by) = called_by.map(SessionID) else {
return done(tui, Err(ToolResult::error("Unknown session")));
@@ -214,7 +237,10 @@ fn terminal_for(tui: &Tui, called_by: Option<String>, done: impl FnOnce(&Tui, Re
}
// The server's answer to `/api/info` arrives on connect, long before a model can call the tool.
if !tui.terminals.available() {
return done(tui, Err(ToolResult::error("This server does not support terminals")));
return done(
tui,
Err(ToolResult::error("This server does not support terminals")),
);
}
let (root, routed_root) = tui.data.read(|state| {
let routed = match tui.route() {
@@ -226,7 +252,9 @@ fn terminal_for(tui: &Tui, called_by: Option<String>, done: impl FnOnce(&Tui, Re
// Terminal panes render for the routed session; tabs hold root sessions, which become routed when selected.
let target = match routed_root {
Some((routed, routed_root)) if routed_root == root => Some(routed),
_ if crate::tabs::Tabs::enabled(tui) && tui.tabs.open_ids(tui).contains(&root.0) => Some(root),
_ if crate::tabs::Tabs::enabled(tui) && tui.tabs.open_ids(tui).contains(&root.0) => {
Some(root)
}
_ => None,
};
let Some(target) = target else {
@@ -237,9 +265,12 @@ fn terminal_for(tui: &Tui, called_by: Option<String>, done: impl FnOnce(&Tui, Re
crate::terminal::refresh(tui, &target, false, move |tui| {
// The agent opened it, so don't move the user's keyboard focus into a live shell.
let selected = tui.terminals.selected_id(&session.0);
let existing = selected
.clone()
.or_else(|| tui.terminals.list(&session.0).last().map(|terminal| terminal.id.0.clone()));
let existing = selected.clone().or_else(|| {
tui.terminals
.list(&session.0)
.last()
.map(|terminal| terminal.id.0.clone())
});
match existing {
Some(id) => {
if selected.as_ref() != Some(&id) {
@@ -247,10 +278,12 @@ fn terminal_for(tui: &Tui, called_by: Option<String>, done: impl FnOnce(&Tui, Re
}
done(tui, Ok(id));
}
None => crate::terminal::create(tui, &session, false, move |tui, id| match id {
Some(id) => done(tui, Ok(id)),
None => done(tui, Err(ToolResult::error("Unable to load terminal"))),
}),
None => {
crate::terminal::create(tui, &session, false, move |tui, id| match id {
Some(id) => done(tui, Ok(id)),
None => done(tui, Err(ToolResult::error("Unable to load terminal"))),
})
}
}
});
});
@@ -263,9 +296,10 @@ fn known(tui: &Tui, session: SessionID, then: impl FnOnce(&Tui) + 'static) {
return then(tui);
}
let weak = tui.weak();
tui.app.spawn(tui.data.session_sync(&session, false), move |_, _| {
if let Some(tui) = weak.upgrade() {
then(&tui);
}
});
tui.app
.spawn(tui.data.session_sync(&session, false), move |_, _| {
if let Some(tui) = weak.upgrade() {
then(&tui);
}
});
}
+3 -12
View File
@@ -348,11 +348,8 @@ impl Inner {
let reset = open
&& (!self.open.get() || *self.tabs.borrow() != tabs || self.default.get() != default);
if reset {
self.active.set(
default
.filter(|tab| tabs.contains(tab))
.unwrap_or(tabs[0]),
);
self.active
.set(default.filter(|tab| tabs.contains(tab)).unwrap_or(tabs[0]));
}
*self.tabs.borrow_mut() = tabs;
self.default.set(default);
@@ -519,13 +516,7 @@ fn row(
.padding_edge(Edge::Left, 1)
.padding_edge(Edge::Right, 1)
.bg(background)
.child(
&View::new(app)
.row()
.grow(1.0)
.min_width(0)
.child(&text),
);
.child(&View::new(app).row().grow(1.0).min_width(0).child(&text));
if let Some(status) = label.status {
view.add(
&Text::new(app, status)
@@ -29,7 +29,8 @@ impl State {
let height = self.entries.len().min(super::ROWS) as isize;
let y = self.selected as isize - self.offset as isize;
if y >= height || y < 0 {
self.offset = super::clamp_offset(self.offset as isize + y - height / 2, self.entries.len());
self.offset =
super::clamp_offset(self.offset as isize + y - height / 2, self.entries.len());
}
}
}
@@ -88,7 +89,11 @@ pub(super) fn commands(inner: &Rc<Inner>) -> Vec<TuiCommand> {
}
inner.refresh(tui);
}),
command("composer.shell.select", "View shell output", |inner, tui| open(inner, tui)),
command(
"composer.shell.select",
"View shell output",
|inner, tui| open(inner, tui),
),
command("composer.shell.kill", "Kill shell command", |inner, tui| {
let Some(shell) = selected(inner) else { return };
let client = tui.data.client().clone();
@@ -99,7 +104,10 @@ pub(super) fn commands(inner: &Rc<Inner>) -> Vec<TuiCommand> {
directory: Some(shell.location.directory),
}),
};
if let Err(error) = client.shell_remove(&input, &RequestOptions::default()).await {
if let Err(error) = client
.shell_remove(&input, &RequestOptions::default())
.await
{
log::warn!("failed to kill the shell command: {error}");
}
});
@@ -159,7 +167,12 @@ pub(super) fn draw(inner: &Rc<Inner>, tui: &Tui, theme: &Theme) -> Vec<(String,
});
}
};
let command = entries[index].info.command.split('\n').next().unwrap_or_default();
let command = entries[index]
.info
.command
.split('\n')
.next()
.unwrap_or_default();
inner.body.add(&row(
tui,
theme,
@@ -183,11 +196,15 @@ pub(super) fn draw(inner: &Rc<Inner>, tui: &Tui, theme: &Theme) -> Vec<(String,
vec![
(
"output".to_owned(),
tui.keymap.shortcut("composer.shell.select").unwrap_or_default(),
tui.keymap
.shortcut("composer.shell.select")
.unwrap_or_default(),
),
(
"kill".to_owned(),
tui.keymap.shortcut("composer.shell.kill").unwrap_or_default(),
tui.keymap
.shortcut("composer.shell.kill")
.unwrap_or_default(),
),
]
}
@@ -77,7 +77,9 @@ pub(super) fn update(inner: &Rc<Inner>, tui: &Tui) {
let sessions = state.sessions();
family(&sessions, &inner.session)
.into_iter()
.map(|(session, prefix)| entry(session, prefix, &inner.session, state.status(&session.id)))
.map(|(session, prefix)| {
entry(session, prefix, &inner.session, state.status(&session.id))
})
.collect::<Vec<_>>()
})
.into_iter()
@@ -94,7 +96,11 @@ pub(super) fn update(inner: &Rc<Inner>, tui: &Tui) {
return;
}
if state.centered.as_ref() != Some(&inner.session) && !state.entries.is_empty() {
let next = state.entries.iter().position(|entry| entry.current).unwrap_or(0);
let next = state
.entries
.iter()
.position(|entry| entry.current)
.unwrap_or(0);
state.centered = Some(inner.session.clone());
state.selected = next;
state.scroll_to_index(next, true);
@@ -140,15 +146,22 @@ pub(super) fn commands(inner: &Rc<Inner>) -> Vec<TuiCommand> {
}
inner.refresh(tui);
}),
command("composer.subagent.select", "Navigate to subagent", |inner, tui| {
let session = {
let state = inner.subagents.borrow();
state.entries.get(state.selected).map(|entry| entry.session.clone())
};
if let Some(id) = session {
tui.navigate(Route::Session { id });
}
}),
command(
"composer.subagent.select",
"Navigate to subagent",
|inner, tui| {
let session = {
let state = inner.subagents.borrow();
state
.entries
.get(state.selected)
.map(|entry| entry.session.clone())
};
if let Some(id) = session {
tui.navigate(Route::Session { id });
}
},
),
command(
"composer.subagent.toggle-activity",
"Toggle active subagents",
@@ -163,27 +176,34 @@ pub(super) fn commands(inner: &Rc<Inner>) -> Vec<TuiCommand> {
},
)
.bind(Bind::Key("ctrl+a".to_owned())),
command("composer.subagent.interrupt", "Interrupt subagent", |inner, tui| {
let session = {
let state = inner.subagents.borrow();
state
.entries
.get(state.selected)
.filter(|entry| entry.running)
.map(|entry| entry.session.clone())
};
let Some(session) = session else { return };
let client = tui.data.client().clone();
tui.app.runtime().spawn(async move {
let input = SessionInterruptInput {
session_id: session,
resume: None,
command(
"composer.subagent.interrupt",
"Interrupt subagent",
|inner, tui| {
let session = {
let state = inner.subagents.borrow();
state
.entries
.get(state.selected)
.filter(|entry| entry.running)
.map(|entry| entry.session.clone())
};
if let Err(error) = client.session_interrupt(&input, &RequestOptions::default()).await {
log::warn!("failed to interrupt the subagent: {error}");
}
});
}),
let Some(session) = session else { return };
let client = tui.data.client().clone();
tui.app.runtime().spawn(async move {
let input = SessionInterruptInput {
session_id: session,
resume: None,
};
if let Err(error) = client
.session_interrupt(&input, &RequestOptions::default())
.await
{
log::warn!("failed to interrupt the subagent: {error}");
}
});
},
),
]
}
@@ -270,7 +290,12 @@ pub(super) fn draw(inner: &Rc<Inner>, tui: &Tui, theme: &Theme) -> Vec<(String,
hints
}
fn entry(session: &SessionInfo, prefix: String, current: &SessionID, status: SessionStatus) -> Entry {
fn entry(
session: &SessionInfo,
prefix: String,
current: &SessionID,
status: SessionStatus,
) -> Entry {
let title = crate::dialogs::session_list::title(session);
let found = AGENT.captures(&title);
let agent = match (&session.agent, &found) {
@@ -341,7 +366,10 @@ fn walk<'a>(
};
out.push((session, prefix));
// A cycle in `parentID` would recurse forever; TS has the same walk, so stop at a session already listed.
if out[..out.len() - 1].iter().any(|(seen, _)| seen.id == session.id) {
if out[..out.len() - 1]
.iter()
.any(|(seen, _)| seen.id == session.id)
{
continue;
}
let mut next = ancestors.to_vec();
@@ -402,17 +430,34 @@ mod tests {
#[test]
fn entries_take_the_agent_from_the_session_or_the_title() {
let current = SessionID("x".into());
let titled = session("a", Some("root"), "Find the parser (@explore subagent)", 1.0);
let titled = session(
"a",
Some("root"),
"Find the parser (@explore subagent)",
1.0,
);
let found = entry(&titled, String::new(), &current, SessionStatus::Running);
assert_eq!((found.agent.as_str(), found.title.as_str(), found.running), ("Explore", "Find the parser ()", true));
assert_eq!(
(found.agent.as_str(), found.title.as_str(), found.running),
("Explore", "Find the parser ()", true)
);
let mut named = session("b", Some("root"), "Review", 1.0);
named.agent = Some(opencode_api::generated::AgentID("code-review".into()));
let found = entry(&named, String::new(), &current, SessionStatus::Idle);
assert_eq!((found.agent.as_str(), found.title.as_str()), ("Code-Review", "Review"));
assert_eq!(
(found.agent.as_str(), found.title.as_str()),
("Code-Review", "Review")
);
let bare = session("x", Some("root"), "@general subagent", 1.0);
let found = entry(&bare, String::new(), &current, SessionStatus::Idle);
assert_eq!((found.agent.as_str(), found.title.as_str(), found.current), ("General", "@general subagent", true));
assert_eq!(
(found.agent.as_str(), found.title.as_str(), found.current),
("General", "@general subagent", true)
);
let plain = session("c", Some("root"), "Plain", 1.0);
assert_eq!(entry(&plain, String::new(), &current, SessionStatus::Idle).agent, "Subagent");
assert_eq!(
entry(&plain, String::new(), &current, SessionStatus::Idle).agent,
"Subagent"
);
}
}
@@ -37,7 +37,11 @@ pub(super) fn update(inner: &Rc<Inner>, tui: &Tui) {
}
// The effect selects the shown terminal when the tab shows and whenever the list or the shown one changes.
let seen = (
state.entries.iter().map(|terminal| terminal.id.0.clone()).collect(),
state
.entries
.iter()
.map(|terminal| terminal.id.0.clone())
.collect(),
state.visible.clone(),
);
if state.seen.as_ref() != Some(&seen) {
@@ -88,7 +92,10 @@ fn select(inner: &Rc<Inner>, tui: &Tui) {
let terminal = {
let state = inner.terminals.borrow();
let Some(index) = state.selected else { return };
state.entries.get(index).map(|terminal| terminal.id.0.clone())
state
.entries
.get(index)
.map(|terminal| terminal.id.0.clone())
};
let session: SessionID = inner.session.clone();
inner.close(tui);
@@ -152,20 +159,18 @@ pub(super) fn draw(inner: &Rc<Inner>, tui: &Tui, theme: &Theme) -> Vec<(String,
});
}
};
inner
.body
.add(&row(
tui,
theme,
state,
Label {
text: label,
status: None,
truncate: true,
},
hover,
click,
));
inner.body.add(&row(
tui,
theme,
state,
Label {
text: label,
status: None,
truncate: true,
},
hover,
click,
));
}
Vec::new()
}
@@ -70,7 +70,11 @@ impl Session {
Rc::new(move |tui: &Tui, open: bool| {
rest.visible(!open);
if open {
if tui.app.focused().is_some_and(|widget| widget.id() == textarea.id()) {
if tui
.app
.focused()
.is_some_and(|widget| widget.id() == textarea.id())
{
tui.app.blur();
}
} else if prompt_root.is_visible() {
@@ -274,7 +274,12 @@ fn check(tui: &Tui) {
/// Lists a session's terminals, and clears its selection when the selected one is gone. `then` runs after. A failure
/// is logged; for a command (`toast`) it also shows "Unable to load terminal", as the TS commands do.
pub(crate) fn refresh(tui: &Tui, session: &SessionID, toast: bool, then: impl FnOnce(&Tui) + 'static) {
pub(crate) fn refresh(
tui: &Tui,
session: &SessionID,
toast: bool,
then: impl FnOnce(&Tui) + 'static,
) {
tui.terminals
.lists
.borrow_mut()
+48 -10
View File
@@ -250,7 +250,11 @@ impl Harness {
fn experiment(&self, on: bool) {
opencode_tui::dialogs::settings::update(&self.tui, move |value| {
opencode_tui::dialogs::settings::set_path(value, &["experimental", "client-mcp"], json!(on));
opencode_tui::dialogs::settings::set_path(
value,
&["experimental", "client-mcp"],
json!(on),
);
});
}
@@ -259,7 +263,15 @@ impl Harness {
let id = self.next.get() + 1;
self.next.set(id);
let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
let deliver = self.opened.lock().unwrap().last().unwrap().2.deliver.clone();
let deliver = self
.opened
.lock()
.unwrap()
.last()
.unwrap()
.2
.deliver
.clone();
deliver
.try_send(Incoming::Text(message.to_string()))
.unwrap();
@@ -350,7 +362,9 @@ fn the_client_mcp_experiment_serves_the_terminal_tools() {
("Wrote to terminal pty_1", false)
);
assert!(
harness.requests("POST", "/api/experimental/session/ses_a/terminal").is_empty(),
harness
.requests("POST", "/api/experimental/session/ses_a/terminal")
.is_empty(),
"an existing terminal is reused"
);
@@ -376,12 +390,19 @@ fn the_subagents_tab_interrupts_a_running_subagent_and_hides_the_queued_dock() {
assert!(harness.wait(|harness| harness.app.text().contains("Explore: Scan ()")));
let text = harness.app.text();
assert!(text.contains("interrupt ctrl+d"), "{text}");
assert!(!text.contains("1 queued"), "the dock hides under the composer");
assert!(
!text.contains("1 queued"),
"the dock hides under the composer"
);
harness
.tui
.keymap
.dispatch("composer.subagent.interrupt", None);
assert!(harness.wait(|harness| !harness.requests("POST", "/api/session/ses_c/interrupt").is_empty()));
assert!(harness.wait(|harness| {
!harness
.requests("POST", "/api/session/ses_c/interrupt")
.is_empty()
}));
// Escape closes the composer, and the dock and the prompt come back.
harness.app.press("escape");
assert!(harness.wait(|harness| harness.app.text().contains("1 queued")));
@@ -393,7 +414,10 @@ fn terminal_select_opens_the_terminal_list_and_enter_shows_the_terminal() {
let harness = mount();
harness.tui.keymap.dispatch("terminal.select", None);
assert!(harness.wait(|harness| harness.app.text().contains("+ New terminal")));
assert!(harness.app.text().contains("vim"), "the foreground process names the terminal");
assert!(
harness.app.text().contains("vim"),
"the foreground process names the terminal"
);
harness.app.press("down");
harness.app.press("enter");
assert!(harness.wait(|harness| harness.selection()["sessions"]["ses_a"] == "pty_1"));
@@ -414,13 +438,27 @@ fn the_shell_output_dialog_shows_the_output_without_escapes() {
harness.app.press("enter");
assert!(harness.wait(|harness| harness.app.text().contains("hello red")));
let text = harness.app.text();
assert!(text.contains("Shell output") && text.contains("Running"), "{text}");
assert!(
text.contains("Shell output") && text.contains("Running"),
"{text}"
);
assert!(text.contains("world"));
assert!(!text.contains("Earlier output omitted"));
let outputs = harness.requests("GET", "/api/shell/sh_1/output");
let query = |logged: &Logged, name: &str| logged.query.get(name).and_then(|values| values.first().cloned());
assert_eq!(query(&outputs[0], "cursor").as_deref(), Some("9007199254740991"));
let query = |logged: &Logged, name: &str| {
logged
.query
.get(name)
.and_then(|values| values.first().cloned())
};
assert_eq!(
query(&outputs[0], "cursor").as_deref(),
Some("9007199254740991")
);
assert_eq!(query(&outputs[1], "cursor").as_deref(), Some("0"));
assert_eq!(query(&outputs[1], "limit").as_deref(), Some("65536"));
assert_eq!(query(&outputs[1], "location[directory]").as_deref(), Some("/project"));
assert_eq!(
query(&outputs[1], "location[directory]").as_deref(),
Some("/project")
);
}