mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
Render selected MCP statusline providers in the TUI footer (#61979)
## What changed - With `tui_extensions_statusline` enabled, resolve the saved MCP provider and read its resource with a snapshot of the displayed thread's statusline state. - Show initialization and error messages, validate the JSON UI tree response, and preserve provider content through native statusline refreshes. Ignore stale results when the thread, provider, or working directory changes. - Request workspace headlines and thread usage for custom providers even when no built-in statusline items are selected. ## Testing Add unit coverage for response validation and footer lifecycle, plus end-to-end tests for embedded and remote app servers, startup delays, current thread metadata, and rejection of project-level provider overrides. GitOrigin-RevId: 80a46ec780c1f1536f1fd4749f468629627dedf6
This commit is contained in:
@@ -53,6 +53,8 @@ struct TestToolServer {
|
||||
invalidated_listing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
const STATUSLINE_RECORD: &str = "MCP_TEST_STATUSLINE_RECORD";
|
||||
const STATUSLINE_URI: &str = "ui://fixture/footer";
|
||||
const MEMO_URI: &str = "memo://codex/example-note";
|
||||
const MEMO_CONTENT: &str = "This is a sample MCP resource served by the rmcp test server.";
|
||||
const SANDBOX_STATE_CAPABILITY: &str = "codex/sandbox-state";
|
||||
@@ -158,6 +160,15 @@ impl TestToolServer {
|
||||
);
|
||||
encrypted_output_tool.annotations = Some(ToolAnnotations::new().read_only(true));
|
||||
|
||||
if std::env::var_os(STATUSLINE_RECORD).is_some() {
|
||||
sandbox_meta_tool
|
||||
.meta
|
||||
.get_or_insert_with(MetaObject::new)
|
||||
.insert(
|
||||
"openai/ui".to_owned(),
|
||||
json!({"entrypoints": [{"type": "statusline", "resourceUri": STATUSLINE_URI}]}),
|
||||
);
|
||||
}
|
||||
let mut tools = vec![
|
||||
Self::echo_tool(),
|
||||
Self::echo_dash_tool(),
|
||||
@@ -699,6 +710,34 @@ impl ServerHandler for TestToolServer {
|
||||
ReadResourceRequestParams { uri, .. }: ReadResourceRequestParams,
|
||||
context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> Result<rmcp::model::ReadResourceResponse, McpError> {
|
||||
if uri == STATUSLINE_URI
|
||||
&& let Some(path) = std::env::var_os(STATUSLINE_RECORD)
|
||||
{
|
||||
use std::io::Write;
|
||||
let state = context
|
||||
.meta
|
||||
.0
|
||||
.0
|
||||
.get("com.openai/codex-statusline-state")
|
||||
.ok_or_else(|| McpError::invalid_params("missing statusline state", None))?;
|
||||
std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)
|
||||
.and_then(|mut file| writeln!(file, "{state}"))
|
||||
.map_err(|error| McpError::internal_error(error.to_string(), None))?;
|
||||
let thread = state["thread"]["id"].as_str().unwrap_or_default();
|
||||
return Ok(
|
||||
ReadResourceResult::new(vec![ResourceContents::TextResourceContents {
|
||||
uri,
|
||||
mime_type: Some("APPLICATION/JSON; charset=utf-8".into()),
|
||||
text: json!({"type":"text", "children":[format!("Provider thread {thread}")]})
|
||||
.to_string(),
|
||||
meta: None,
|
||||
}])
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if uri == "test://codex/request-metadata" {
|
||||
let metadata = serde_json::Value::Object(context.meta.0.0);
|
||||
return Ok(ReadResourceResult::new(vec![ResourceContents::text(
|
||||
|
||||
@@ -9,6 +9,7 @@ codex_rust_crate(
|
||||
crate_name = "codex_tui",
|
||||
extra_binaries = [
|
||||
"//codex-rs/cli:codex",
|
||||
"//codex-rs/rmcp-client:test_stdio_server",
|
||||
],
|
||||
integration_compile_data_extra = ["src/test_backend.rs"],
|
||||
rustc_flags_extra = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
|
||||
|
||||
@@ -476,6 +476,9 @@ impl App {
|
||||
}
|
||||
}
|
||||
}
|
||||
AppEvent::StatuslineRead(event) => {
|
||||
self.chat_widget.handle_statusline_read(event, app_server);
|
||||
}
|
||||
AppEvent::TaskToolsAvailable { thread_id } => {
|
||||
app_server.remember_task_tool_thread(thread_id);
|
||||
}
|
||||
|
||||
@@ -354,6 +354,7 @@ impl CapturedSideWork {
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Debug, IntoStaticStr)]
|
||||
pub(crate) enum AppEvent {
|
||||
StatuslineRead(crate::chatwidget::StatuslineReadEvent),
|
||||
AccountEmailLoaded {
|
||||
request_id: uuid::Uuid,
|
||||
email: Option<String>,
|
||||
|
||||
@@ -402,6 +402,9 @@ use self::status_state::TerminalTitleStatusKind;
|
||||
mod status_controls;
|
||||
mod status_surface_commands;
|
||||
mod status_surfaces;
|
||||
mod statusline_reader;
|
||||
pub(crate) use statusline_reader::StatuslineReadEvent;
|
||||
|
||||
pub(crate) mod statusline_state;
|
||||
use self::status_surface_commands::StatusSurfaceOverrides;
|
||||
mod streaming;
|
||||
@@ -574,6 +577,7 @@ pub(crate) struct ChatWidget {
|
||||
pub(crate) initial_user_message: Option<UserMessage>,
|
||||
status_account_display: Option<StatusAccountDisplay>,
|
||||
pub(crate) remote_connection: Option<RemoteConnectionStatus>,
|
||||
statusline_read: Option<statusline_reader::ActiveStatuslineRead>,
|
||||
/// Remote app servers cannot read image paths on the TUI host.
|
||||
pub(crate) snapshot_local_images: bool,
|
||||
pub(crate) thread_params_mode: crate::app_server_session::ThreadParamsMode,
|
||||
|
||||
@@ -148,6 +148,7 @@ impl ChatWidget {
|
||||
initial_user_message,
|
||||
status_account_display,
|
||||
remote_connection: None,
|
||||
statusline_read: None,
|
||||
snapshot_local_images: false,
|
||||
thread_params_mode: crate::app_server_session::ThreadParamsMode::Embedded,
|
||||
pending_image_submission: None,
|
||||
|
||||
@@ -222,6 +222,11 @@ impl ChatWidget {
|
||||
&mut self,
|
||||
notification: McpServerStatusUpdatedNotification,
|
||||
) {
|
||||
if notification.status == McpServerStartupState::Ready
|
||||
&& let Some(footer) = &self.statusline_read
|
||||
{
|
||||
footer.server_ready(¬ification.name);
|
||||
}
|
||||
let refresh_connector_mentions = notification.name == "codex_apps"
|
||||
&& notification.environment_id.is_none()
|
||||
&& notification.status == McpServerStartupState::Ready;
|
||||
|
||||
@@ -71,25 +71,6 @@ impl StatusSurfaceSelections {
|
||||
.status_line_items
|
||||
.contains(&StatusLineItem::BranchChanges)
|
||||
}
|
||||
|
||||
fn uses_workspace_headline(&self) -> bool {
|
||||
self.status_line_items
|
||||
.contains(&StatusLineItem::WorkspaceHeadline)
|
||||
}
|
||||
|
||||
fn uses_thread_usage(&self) -> bool {
|
||||
self.status_line_items.iter().any(|item| {
|
||||
matches!(
|
||||
item,
|
||||
StatusLineItem::ThreadCredits | StatusLineItem::EstimatedThreadCost
|
||||
)
|
||||
}) || self.terminal_title_items.iter().any(|item| {
|
||||
matches!(
|
||||
item,
|
||||
TerminalTitleItem::ThreadCredits | TerminalTitleItem::EstimatedThreadCost
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Cached project-root display name keyed by the cwd used for the last lookup.
|
||||
@@ -183,7 +164,7 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
if !selections.uses_workspace_headline() {
|
||||
if !self.uses_workspace_headline(&selections.status_line_items) {
|
||||
self.status_line_workspace_headline = None;
|
||||
self.status_line_workspace_headline_pending_request_id = None;
|
||||
self.status_line_workspace_headline_last_requested_at = None;
|
||||
@@ -192,7 +173,7 @@ impl ChatWidget {
|
||||
self.request_status_line_workspace_headline_if_due(Instant::now());
|
||||
}
|
||||
|
||||
if selections.uses_thread_usage() {
|
||||
if self.thread_usage_is_selected() {
|
||||
self.ensure_thread_usage_requested();
|
||||
} else {
|
||||
self.cancel_thread_usage_polling();
|
||||
@@ -200,6 +181,9 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn refresh_status_line_from_selections(&mut self, selections: &StatusSurfaceSelections) {
|
||||
if self.refresh_provider_footer() {
|
||||
return;
|
||||
}
|
||||
let enabled = !selections.status_line_items.is_empty();
|
||||
self.bottom_pane.set_status_line_enabled(enabled);
|
||||
if !enabled {
|
||||
@@ -503,7 +487,7 @@ impl ChatWidget {
|
||||
})
|
||||
}
|
||||
|
||||
fn status_line_cwd(&self) -> &Path {
|
||||
pub(super) fn status_line_cwd(&self) -> &Path {
|
||||
self.current_cwd
|
||||
.as_deref()
|
||||
.unwrap_or(self.config.cwd.as_path())
|
||||
@@ -662,6 +646,11 @@ impl ChatWidget {
|
||||
});
|
||||
}
|
||||
|
||||
fn uses_workspace_headline(&self, status_line_items: &[StatusLineItem]) -> bool {
|
||||
self.selected_statusline_provider().is_some()
|
||||
|| status_line_items.contains(&StatusLineItem::WorkspaceHeadline)
|
||||
}
|
||||
|
||||
fn request_status_line_workspace_headline_if_due(&mut self, now: Instant) {
|
||||
if !self.status_line_workspace_headline_should_fetch(now) {
|
||||
return;
|
||||
@@ -693,10 +682,7 @@ impl ChatWidget {
|
||||
pub(super) fn refresh_status_line_if_workspace_headline_due(&mut self) {
|
||||
let now = Instant::now();
|
||||
if self.status_line_workspace_headline_should_fetch(now)
|
||||
&& self
|
||||
.status_line_items_with_invalids()
|
||||
.0
|
||||
.contains(&StatusLineItem::WorkspaceHeadline)
|
||||
&& self.uses_workspace_headline(&self.status_line_items_with_invalids().0)
|
||||
{
|
||||
self.refresh_status_line();
|
||||
}
|
||||
@@ -730,10 +716,7 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
if !self.status_line_workspace_messages_disabled
|
||||
&& self
|
||||
.status_line_items_with_invalids()
|
||||
.0
|
||||
.contains(&StatusLineItem::WorkspaceHeadline)
|
||||
&& self.uses_workspace_headline(&self.status_line_items_with_invalids().0)
|
||||
{
|
||||
self.frame_requester
|
||||
.schedule_frame_in(crate::workspace_messages::WORKSPACE_HEADLINE_REFRESH_INTERVAL);
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Read one statusline resource for the displayed thread and keep its footer through native refreshes.
|
||||
|
||||
use super::ChatWidget;
|
||||
use super::statusline_state::StatuslineState;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::backend_id::BackendId;
|
||||
use crate::statusline_provider::ProviderId;
|
||||
use crate::statusline_provider::ProviderSelection;
|
||||
use crate::statusline_provider::ResolvedStatuslineProvider;
|
||||
use crate::ui_tree::UiNode;
|
||||
use crate::ui_tree::UiTree;
|
||||
use codex_app_server_protocol::McpResourceContent;
|
||||
use codex_config::types::StatusLineProviderId;
|
||||
use codex_config::types::StatusLineSelection;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::WrapErr;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) struct ActiveStatuslineRead {
|
||||
token: Uuid,
|
||||
thread: Option<ThreadId>,
|
||||
selection: StatusLineProviderId,
|
||||
host_cwd: PathBuf,
|
||||
startup: watch::Sender<()>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct StatuslineReadEvent {
|
||||
token: Uuid,
|
||||
step: ReadStep,
|
||||
}
|
||||
|
||||
#[derive(derive_more::Debug)]
|
||||
enum ReadStep {
|
||||
Start(watch::Receiver<()>),
|
||||
#[debug("Snapshot(..)")]
|
||||
Snapshot(BackendId, oneshot::Sender<StatuslineState>),
|
||||
#[debug("Finished(..)")]
|
||||
Finished(BackendId, Result<UiTree, String>),
|
||||
}
|
||||
|
||||
impl StatuslineReadEvent {
|
||||
fn send(sender: &AppEventSender, token: Uuid, step: ReadStep) {
|
||||
sender.send(AppEvent::StatuslineRead(Self { token, step }));
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatWidget {
|
||||
pub(super) fn selected_statusline_provider(&self) -> Option<&StatusLineProviderId> {
|
||||
if self.read_only_history
|
||||
|| !self
|
||||
.config
|
||||
.features
|
||||
.enabled(Feature::TuiExtensionsStatusLine)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
match self.local_settings.tui.status_line_provider.as_deref()? {
|
||||
StatusLineSelection::Builtin(_) => None,
|
||||
StatusLineSelection::Mcp(id) => Some(id),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn refresh_provider_footer(&mut self) -> bool {
|
||||
let Some(selection) = self.selected_statusline_provider() else {
|
||||
self.statusline_read = None;
|
||||
return false;
|
||||
};
|
||||
if self
|
||||
.statusline_read
|
||||
.as_ref()
|
||||
.is_some_and(|read| read.is_current(self))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let token = Uuid::new_v4();
|
||||
let (startup, ready) = watch::channel(());
|
||||
self.statusline_read = Some(ActiveStatuslineRead {
|
||||
token,
|
||||
thread: self.thread_id,
|
||||
selection: selection.clone(),
|
||||
host_cwd: self.status_line_cwd().to_owned(),
|
||||
startup,
|
||||
});
|
||||
self.bottom_pane.set_status_line_enabled(/*enabled*/ true);
|
||||
self.set_status_line(Some(
|
||||
UiTree(Some(UiNode::String("Initializing…".into()))).into(),
|
||||
));
|
||||
if self.thread_id.is_some() {
|
||||
StatuslineReadEvent::send(&self.app_event_tx, token, ReadStep::Start(ready));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn handle_statusline_read(
|
||||
&mut self,
|
||||
event: StatuslineReadEvent,
|
||||
owner: &AppServerSession,
|
||||
) {
|
||||
let Some(footer) = self.statusline_read.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if event.token != footer.token {
|
||||
return;
|
||||
}
|
||||
if !footer.is_current(self) {
|
||||
self.refresh_status_line();
|
||||
return;
|
||||
}
|
||||
match event.step {
|
||||
ReadStep::Start(ready) => footer.start(owner, &self.app_event_tx, ready),
|
||||
ReadStep::Snapshot(backend, reply) => {
|
||||
if backend == owner.backend_id()
|
||||
&& let Some(state) = self.statusline_state()
|
||||
{
|
||||
let _ = reply.send(state);
|
||||
}
|
||||
}
|
||||
ReadStep::Finished(backend, result) => {
|
||||
if backend != owner.backend_id() {
|
||||
return;
|
||||
}
|
||||
let tree = result.unwrap_or_else(|name| UiTree(Some(UiNode::String(format!(
|
||||
"Error loading statusline contents from {name}. Use /statusline to (re)select your provider and try again."
|
||||
)))));
|
||||
self.set_status_line(Some(tree.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveStatuslineRead {
|
||||
fn is_current(&self, chat: &ChatWidget) -> bool {
|
||||
self.thread == chat.thread_id
|
||||
&& Some(&self.selection) == chat.selected_statusline_provider()
|
||||
&& self.host_cwd == chat.status_line_cwd()
|
||||
}
|
||||
|
||||
pub(super) fn server_ready(&self, server: &str) {
|
||||
if self.selection.server == server {
|
||||
self.startup.send_replace(());
|
||||
}
|
||||
}
|
||||
|
||||
fn start(
|
||||
&self,
|
||||
owner: &AppServerSession,
|
||||
events: &AppEventSender,
|
||||
mut ready: watch::Receiver<()>,
|
||||
) {
|
||||
let Some(thread) = self.thread else { return };
|
||||
let id = ProviderId {
|
||||
server: self.selection.server.as_str().into(),
|
||||
tool: self.selection.tool.as_str().into(),
|
||||
};
|
||||
let mut name = self.selection.tool.clone();
|
||||
let token = self.token;
|
||||
let events = events.clone();
|
||||
let client = owner.request_handle();
|
||||
let backend = owner.backend_id();
|
||||
let cwd = LegacyAppPathString::from_path(&self.host_cwd).to_inferred_path_uri();
|
||||
tokio::spawn(async move {
|
||||
let result: Result<UiTree> = async {
|
||||
let cwd = cwd.ok_or_else(|| eyre!("invalid app-server working directory"))?;
|
||||
let provider = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
|
||||
loop {
|
||||
if let Ok(Some(provider)) = ResolvedStatuslineProvider::lookup(
|
||||
&client,
|
||||
thread,
|
||||
&cwd,
|
||||
ProviderSelection::Saved(&id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok::<_, watch::error::RecvError>(provider);
|
||||
}
|
||||
// A cold catalog may arrive before the selected MCP server finishes starting.
|
||||
ready.changed().await?;
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
name.clone_from(&provider.provider().title);
|
||||
// Lookup can outlive the displayed thread or its current usage measurements.
|
||||
let (reply, current) = oneshot::channel();
|
||||
StatuslineReadEvent::send(&events, token, ReadStep::Snapshot(backend, reply));
|
||||
let response = provider.read(serde_json::to_value(current.await?)?).await?;
|
||||
decode_tree(&provider.provider().uri, &response.contents)
|
||||
}
|
||||
.await;
|
||||
StatuslineReadEvent::send(
|
||||
&events,
|
||||
token,
|
||||
ReadStep::Finished(backend, result.map_err(|_| name)),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_tree(uri: &str, contents: &[McpResourceContent]) -> Result<UiTree> {
|
||||
let [
|
||||
McpResourceContent::Text {
|
||||
uri: returned_uri,
|
||||
mime_type: Some(mime),
|
||||
text,
|
||||
..
|
||||
},
|
||||
] = contents
|
||||
else {
|
||||
bail!("expected one text resource");
|
||||
};
|
||||
let media_type = mime.split(';').next().unwrap_or_default().trim();
|
||||
if uri != returned_uri || !media_type.eq_ignore_ascii_case("application/json") {
|
||||
bail!("expected application/json at the advertised resource URI");
|
||||
}
|
||||
text.parse().wrap_err("invalid UI tree")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "statusline_reader_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,177 @@
|
||||
#![cfg(test)]
|
||||
//! Exercise the MCP response envelope and the displayed footer's one-shot lifecycle.
|
||||
|
||||
use super::*;
|
||||
use crate::bottom_pane::StatusLineFocus;
|
||||
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use crate::chatwidget::tests::render_bottom_popup;
|
||||
use codex_config::types::BuiltinStatusLine;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::buffer::Cell;
|
||||
use ratatui::layout::Rect;
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
|
||||
#[test]
|
||||
fn statusline_resource_requires_one_matching_json_text_item() {
|
||||
let uri = "ui://provider/footer";
|
||||
let content = |value| serde_json::from_value::<McpResourceContent>(value).unwrap();
|
||||
let text = |mime: &str, body: &str| content(json!({"uri":uri, "mimeType":mime, "text":body}));
|
||||
let item = text("APPLICATION/JSON; charset=utf-8", "null");
|
||||
assert_eq!(
|
||||
decode_tree(uri, std::slice::from_ref(&item)).unwrap(),
|
||||
UiTree(None)
|
||||
);
|
||||
for contents in [
|
||||
vec![],
|
||||
vec![item.clone(), item],
|
||||
vec![content(
|
||||
json!({"uri":"ui://wrong","mimeType":"application/json","text":"null"}),
|
||||
)],
|
||||
vec![content(json!({"uri":uri,"text":"null"}))],
|
||||
vec![content(
|
||||
json!({"uri":uri,"mimeType":"application/json","blob":"bnVsbA=="}),
|
||||
)],
|
||||
vec![text("text/plain", "null")],
|
||||
vec![text("application/json", "{")],
|
||||
] {
|
||||
assert!(decode_tree(uri, &contents).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn read_events(rx: &mut UnboundedReceiver<AppEvent>) -> Vec<StatuslineReadEvent> {
|
||||
std::iter::from_fn(|| rx.try_recv().ok())
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::StatuslineRead(read) => Some(read),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn footer(chat: &ChatWidget) -> Option<String> {
|
||||
let content = chat.bottom_pane.status_line_content()?;
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 160, /*height*/ 1,
|
||||
);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
content.render(area, &mut buffer, StatusLineFocus::Focused);
|
||||
let row: String = buffer.content.iter().map(Cell::symbol).collect();
|
||||
Some(row.trim_end().to_owned())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_statusline_requests_headline_and_billing_with_no_native_items() {
|
||||
let (mut chat, _, mut rx, _) = make_chatwidget_manual_with_sender().await;
|
||||
let thread = ThreadId::new();
|
||||
chat.thread_id = Some(thread);
|
||||
chat.has_codex_backend_auth = true;
|
||||
chat.plan_type = Some(codex_protocol::account::PlanType::Business);
|
||||
chat.local_settings.tui.status_line = Some(Vec::new());
|
||||
chat.local_settings.tui.terminal_title = Some(Vec::new());
|
||||
chat.local_settings.tui.status_line_provider =
|
||||
Some(Box::new(StatusLineSelection::Mcp(StatusLineProviderId {
|
||||
server: "fixture".into(),
|
||||
tool: "line".into(),
|
||||
})));
|
||||
chat.set_feature_enabled(Feature::TuiExtensionsStatusLine, /*enabled*/ true);
|
||||
chat.refresh_status_line();
|
||||
|
||||
let events: Vec<_> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|event| matches!(event, AppEvent::RefreshStatusLineWorkspaceHeadline { .. }))
|
||||
);
|
||||
assert!(events.iter().any(|event| matches!(event, AppEvent::RefreshThreadUsage { thread_id, .. } if *thread_id == thread)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn statusline_reader_waits_for_the_displayed_thread_and_keeps_its_result() {
|
||||
let (mut chat, _, mut rx, _) = make_chatwidget_manual_with_sender().await;
|
||||
let server = crate::start_embedded_app_server_for_picker(&chat.config)
|
||||
.await
|
||||
.unwrap();
|
||||
let selected = Box::new(StatusLineSelection::Mcp(StatusLineProviderId {
|
||||
server: "fixture".into(),
|
||||
tool: "line".into(),
|
||||
}));
|
||||
chat.local_settings.tui.status_line = Some(Vec::new());
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.local_settings.tui.status_line_provider = Some(selected.clone());
|
||||
chat.set_feature_enabled(Feature::TuiExtensionsStatusLine, /*enabled*/ false);
|
||||
chat.refresh_status_line();
|
||||
assert!(read_events(&mut rx).is_empty());
|
||||
|
||||
chat.local_settings.tui.status_line_provider = Some(Box::new(StatusLineSelection::Builtin(
|
||||
BuiltinStatusLine::Default,
|
||||
)));
|
||||
chat.set_feature_enabled(Feature::TuiExtensionsStatusLine, /*enabled*/ true);
|
||||
chat.refresh_status_line();
|
||||
assert!(read_events(&mut rx).is_empty());
|
||||
chat.thread_id = None;
|
||||
chat.local_settings.tui.status_line_provider = Some(selected);
|
||||
chat.refresh_status_line();
|
||||
let initializing = footer(&chat).unwrap();
|
||||
assert!(read_events(&mut rx).is_empty());
|
||||
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.refresh_status_line();
|
||||
chat.refresh_status_line();
|
||||
let [start] = read_events(&mut rx).try_into().unwrap();
|
||||
let token = start.token;
|
||||
chat.set_active_agent_label(Some("native-agent-label".into()));
|
||||
let finish = |token, root| StatuslineReadEvent {
|
||||
token,
|
||||
step: ReadStep::Finished(server.backend_id(), Ok(UiTree(root))),
|
||||
};
|
||||
chat.handle_statusline_read(finish(token, Some(UiNode::String("Ready".into()))), &server);
|
||||
chat.refresh_status_line();
|
||||
let ready = footer(&chat).unwrap();
|
||||
insta::assert_snapshot!(format!("{initializing}\n{ready}"), @"
|
||||
Initializing…
|
||||
Ready
|
||||
");
|
||||
chat.handle_statusline_read(finish(token, /*root*/ None), &server);
|
||||
chat.refresh_status_line();
|
||||
assert_eq!(footer(&chat).as_deref(), Some(""));
|
||||
assert!(!render_bottom_popup(&chat, /*width*/ 80).contains("native-agent-label"));
|
||||
assert!(read_events(&mut rx).is_empty());
|
||||
|
||||
chat.read_only_history = true;
|
||||
chat.refresh_status_line();
|
||||
assert!(footer(&chat).is_none());
|
||||
assert!(read_events(&mut rx).is_empty());
|
||||
chat.read_only_history = false;
|
||||
chat.refresh_status_line();
|
||||
let [resumed] = read_events(&mut rx).try_into().unwrap();
|
||||
chat.handle_statusline_read(finish(token, None), &server);
|
||||
assert_eq!(footer(&chat).as_deref(), Some("Initializing…"));
|
||||
let token = resumed.token;
|
||||
chat.primary_environment_cwd = Some(crate::session_state::EnvironmentCwd {
|
||||
path: LegacyAppPathString::from_path(chat.config.cwd.join("executor-checkout").as_path()),
|
||||
is_server_local: false,
|
||||
});
|
||||
chat.refresh_status_line();
|
||||
assert!(read_events(&mut rx).is_empty());
|
||||
chat.current_cwd = Some(chat.config.cwd.join("another-project").to_path_buf());
|
||||
let (reply, snapshot) = oneshot::channel();
|
||||
chat.handle_statusline_read(
|
||||
StatuslineReadEvent {
|
||||
token,
|
||||
step: ReadStep::Snapshot(server.backend_id(), reply),
|
||||
},
|
||||
&server,
|
||||
);
|
||||
assert!(snapshot.await.is_err());
|
||||
let [replacement] = read_events(&mut rx).try_into().unwrap();
|
||||
assert_eq!(footer(&chat).as_deref(), Some("Initializing…"));
|
||||
let token = replacement.token;
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.refresh_status_line();
|
||||
chat.handle_statusline_read(
|
||||
finish(token, Some(UiNode::String("retired".into()))),
|
||||
&server,
|
||||
);
|
||||
assert_eq!(footer(&chat).as_deref(), Some("Initializing…"));
|
||||
}
|
||||
@@ -176,7 +176,6 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "staged for provider reads"))]
|
||||
pub(crate) fn statusline_state(&self) -> Option<StatuslineState> {
|
||||
if self.read_only_history {
|
||||
return None;
|
||||
|
||||
@@ -396,18 +396,26 @@ impl ChatWidget {
|
||||
)
|
||||
}
|
||||
|
||||
fn thread_usage_is_selected(&self) -> bool {
|
||||
pub(super) fn thread_usage_is_selected(&self) -> bool {
|
||||
let selected = self.selected_thread_usage();
|
||||
selected.credits || selected.estimated_cost
|
||||
}
|
||||
|
||||
fn selected_thread_usage(&self) -> SelectedThreadUsage {
|
||||
if self.selected_statusline_provider().is_some() {
|
||||
return SelectedThreadUsage {
|
||||
credits: self.plan_type != Some(PlanType::Ent26),
|
||||
estimated_cost: true,
|
||||
};
|
||||
}
|
||||
let mut selected = SelectedThreadUsage::default();
|
||||
for item in self.configured_status_line_items() {
|
||||
match item.parse::<StatusLineItem>() {
|
||||
Ok(StatusLineItem::ThreadCredits) => selected.credits = true,
|
||||
Ok(StatusLineItem::EstimatedThreadCost) => selected.estimated_cost = true,
|
||||
Ok(_) | Err(_) => {}
|
||||
if !self.read_only_history {
|
||||
for item in self.configured_status_line_items() {
|
||||
match item.parse::<StatusLineItem>() {
|
||||
Ok(StatusLineItem::ThreadCredits) => selected.credits = true,
|
||||
Ok(StatusLineItem::EstimatedThreadCost) => selected.estimated_cost = true,
|
||||
Ok(_) | Err(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for item in self.configured_terminal_title_items() {
|
||||
|
||||
@@ -65,10 +65,10 @@ pub(crate) struct ProviderId {
|
||||
pub(crate) tool: McpToolName,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "staged provider choice"))]
|
||||
pub(crate) enum ProviderSelection<'a> {
|
||||
Saved(&'a ProviderId),
|
||||
/// A provider advertised during the current picker refresh.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "staged picker selection"))]
|
||||
Discovered(&'a StatuslineProvider),
|
||||
}
|
||||
|
||||
@@ -78,7 +78,6 @@ pub(crate) struct ResolvedStatuslineProvider {
|
||||
provider: StatuslineProvider,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "staged resource reader"))]
|
||||
impl ResolvedStatuslineProvider {
|
||||
pub(crate) async fn lookup(
|
||||
client: &AppServerRequestHandle,
|
||||
|
||||
@@ -14,7 +14,11 @@ mod resize_reflow;
|
||||
mod screen_reader;
|
||||
mod status_indicator;
|
||||
#[cfg(unix)]
|
||||
mod statusline_provider;
|
||||
#[cfg(unix)]
|
||||
mod thread_title;
|
||||
#[cfg(unix)]
|
||||
mod unix_daemon;
|
||||
mod vt100_history;
|
||||
mod vt100_live_commit;
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -6,12 +6,10 @@ use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use app_test_support::create_fake_rollout;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn resume_lists_all_providers_and_fork_keeps_provider_filter() -> Result<()> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let cwd = codex_utils_cargo_bin::repo_root()?;
|
||||
for action in ["resume", "fork"] {
|
||||
for (embedded, last, explicit) in [
|
||||
@@ -45,38 +43,11 @@ async fn resume_lists_all_providers_and_fork_keeps_provider_filter() -> Result<(
|
||||
/*git_info*/ None,
|
||||
)?;
|
||||
}
|
||||
let mut daemon = tokio::process::Command::new(&codex)
|
||||
.args([
|
||||
"app-server",
|
||||
"--listen",
|
||||
"unix://",
|
||||
"-c",
|
||||
"model_provider=\"server-provider\"",
|
||||
])
|
||||
.env("CODEX_HOME", home.path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
let socket = codex_app_server_client::app_server_control_socket_path(home.path())?;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 30), async {
|
||||
loop {
|
||||
if tokio::net::UnixStream::connect(socket.as_path())
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return Ok::<(), anyhow::Error>(());
|
||||
}
|
||||
ensure!(
|
||||
daemon.try_wait()?.is_none(),
|
||||
"app server exited before opening its socket"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(/*millis*/ 20)).await;
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
let remote_endpoint = format!("unix://{}", socket.as_path().display());
|
||||
let (mut daemon, remote_endpoint) = super::unix_daemon::start(
|
||||
home.path(),
|
||||
&["-c", "model_provider=\"server-provider\""],
|
||||
)
|
||||
.await?;
|
||||
let mut args = vec![action, "--all"];
|
||||
if embedded {
|
||||
args.push("--no-daemon");
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
#![cfg(test)]
|
||||
//! A real CLI, app server and stdio MCP provider exercise the selected resource end to end.
|
||||
|
||||
use super::focus_palette::PtyCodex;
|
||||
use super::focus_palette::write_test_config;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn test_home(cwd: &Path) -> Result<TempDir> {
|
||||
let home = tempfile::tempdir_in("/tmp")?;
|
||||
write_test_config(home.path(), cwd)?;
|
||||
let config = home.path().join("config.toml");
|
||||
let existing = fs::read_to_string(&config)?;
|
||||
fs::write(
|
||||
config,
|
||||
format!("features.tui_extensions_statusline = true\n{existing}"),
|
||||
)?;
|
||||
Ok(home)
|
||||
}
|
||||
|
||||
fn register_provider(config: &Path, receipt: &Path, barrier: &Path) -> Result<()> {
|
||||
let registration = json!({"mcp_servers":{"fixture":{
|
||||
"command":core_test_support::stdio_server_bin()?,
|
||||
"env":{"MCP_TEST_STATUSLINE_RECORD":receipt, "MCP_TEST_INITIALIZE_BARRIER_FILE":barrier}
|
||||
}}});
|
||||
writeln!(
|
||||
fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(config)?,
|
||||
"\n{}",
|
||||
toml::to_string(®istration)?
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Setup {
|
||||
Embedded,
|
||||
Remote,
|
||||
ProjectShadow,
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn statusline_reads_the_selected_stdio_resource_on_the_displayed_thread() -> Result<()> {
|
||||
for mode in [Setup::Embedded, Setup::Remote, Setup::ProjectShadow] {
|
||||
let work = tempfile::tempdir_in("/tmp")?;
|
||||
let cwd = work.path().canonicalize()?;
|
||||
fs::create_dir(cwd.join(".git"))?;
|
||||
let client = test_home(&cwd)?;
|
||||
let registration_home = test_home(&cwd)?;
|
||||
let host = if mode == Setup::Remote {
|
||||
registration_home.path()
|
||||
} else {
|
||||
client.path()
|
||||
};
|
||||
let receipt = cwd.join("resource-read.jsonl");
|
||||
let shadow = cwd.join("project-read.jsonl");
|
||||
let barrier = cwd.join("provider-ready");
|
||||
register_provider(&host.join("config.toml"), &receipt, &barrier)?;
|
||||
let preference = "[tui]\ndisable_paste_burst = true\nstatus_line = []\nstatus_line_provider = { server='fixture', tool='sandbox_meta' }";
|
||||
writeln!(
|
||||
fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(client.path().join("config.toml"))?,
|
||||
"\n{preference}"
|
||||
)?;
|
||||
if mode == Setup::ProjectShadow {
|
||||
let project = cwd.join(".codex");
|
||||
fs::create_dir(&project)?;
|
||||
register_provider(&project.join("config.toml"), &shadow, &barrier)?;
|
||||
}
|
||||
let mut daemon = None;
|
||||
let endpoint;
|
||||
let args = if mode == Setup::Remote {
|
||||
let (child, socket) = super::unix_daemon::start(host, &[]).await?;
|
||||
daemon = Some(child);
|
||||
endpoint = socket;
|
||||
vec!["--remote", endpoint.as_str()]
|
||||
} else {
|
||||
vec!["--no-daemon"]
|
||||
};
|
||||
let mut terminal = PtyCodex::start_cli(&cwd, client, &args)?;
|
||||
terminal
|
||||
.wait_for_screen("Initializing…")
|
||||
.with_context(|| format!("{mode:?} initialization"))?;
|
||||
assert!(!receipt.exists());
|
||||
if mode == Setup::Embedded {
|
||||
terminal.write_input(b"/raw on\r")?;
|
||||
terminal.wait_for_screen("Raw output mode on")?;
|
||||
}
|
||||
fs::write(&barrier, "")?;
|
||||
if mode == Setup::ProjectShadow {
|
||||
terminal.wait_for_screen("Error loading statusline contents from sandbox_meta")?;
|
||||
assert!(!receipt.exists());
|
||||
assert!(!shadow.exists());
|
||||
} else {
|
||||
terminal
|
||||
.wait_for_screen("Provider thread ")
|
||||
.with_context(|| format!("{mode:?} resource read"))?;
|
||||
let receipts = fs::read_to_string(&receipt)?;
|
||||
let [line]: [&str; 1] = receipts
|
||||
.lines()
|
||||
.collect::<Vec<_>>()
|
||||
.try_into()
|
||||
.expect("one read");
|
||||
let state: Value = serde_json::from_str(line)?;
|
||||
let thread = state["thread"]["id"]
|
||||
.as_str()
|
||||
.context("missing displayed thread ID")?;
|
||||
terminal.wait_for_screen(&format!("Provider thread {thread}"))?;
|
||||
terminal.write_input(b"/status\r")?;
|
||||
terminal.wait_for_screen("Session:")?;
|
||||
let status = terminal.screen_contents();
|
||||
let session = status
|
||||
.lines()
|
||||
.find(|line| line.contains("Session:"))
|
||||
.context("missing Session row")?;
|
||||
assert!(
|
||||
session.contains(thread),
|
||||
"{session} should identify {thread}"
|
||||
);
|
||||
if mode == Setup::Embedded {
|
||||
assert_eq!(state["app"]["display_mode"], "raw");
|
||||
}
|
||||
assert_eq!(state["thread"]["workspace"], json!({"cwd": cwd}));
|
||||
}
|
||||
drop(terminal);
|
||||
if let Some(mut child) = daemon {
|
||||
child.kill().await?;
|
||||
child.wait().await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Launch a real app server for CLI tests that connect over a Unix socket.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Child;
|
||||
|
||||
pub(super) async fn start(home: &Path, extra_args: &[&str]) -> Result<(Child, String)> {
|
||||
let socket = codex_app_server_client::app_server_control_socket_path(home)?;
|
||||
let mut daemon = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.args(["app-server", "--listen", "unix://"])
|
||||
.args(extra_args)
|
||||
.env("CODEX_HOME", home)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
tokio::time::timeout(Duration::from_secs(30), async {
|
||||
while tokio::net::UnixStream::connect(socket.as_path())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
ensure!(
|
||||
daemon.try_wait()?.is_none(),
|
||||
"app server exited before opening its socket"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await??;
|
||||
Ok((daemon, format!("unix://{}", socket.as_path().display())))
|
||||
}
|
||||
Reference in New Issue
Block a user