diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index eea1030474..bb13706ec6 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -291,6 +291,7 @@ mod sidebar_close; mod sidebar_document; mod sidebar_files; pub(crate) mod sidebar_loading; +mod sidebar_subagents; mod startup; pub(crate) mod startup_bootstrap; mod startup_prompts; diff --git a/codex-rs/tui/src/app/agent_picker.rs b/codex-rs/tui/src/app/agent_picker.rs index 2b70239d28..ed127bb54d 100644 --- a/codex-rs/tui/src/app/agent_picker.rs +++ b/codex-rs/tui/src/app/agent_picker.rs @@ -136,6 +136,7 @@ impl App { let Ok(thread_id) = ThreadId::from_string(&thread.id) else { continue; }; + let sidebar_agent = self.register_sidebar_agent(root, thread_id); if !completion.visibility_changed_threads.contains(&thread_id) { self.update_agent_picker_thread_visibility( thread_id, @@ -168,6 +169,10 @@ impl App { if !live && update_liveness { self.agent_navigation.set_running(thread_id, is_running); } + if sidebar_agent && !live && (is_running || thread.status == ThreadStatus::SystemError) + { + self.seed_discovered_sidebar_agent(root, thread_id, &thread.status); + } } for thread_id in refresh.archived_thread_ids { if !completion.visibility_changed_threads.contains(&thread_id) { diff --git a/codex-rs/tui/src/app/app_server_events.rs b/codex-rs/tui/src/app/app_server_events.rs index 7f592f1eba..a23c09a1c0 100644 --- a/codex-rs/tui/src/app/app_server_events.rs +++ b/codex-rs/tui/src/app/app_server_events.rs @@ -262,6 +262,7 @@ impl App { } } + self.observe_sidebar_agent_event(¬ification); if let ServerNotification::ThreadStatusChanged(status) = ¬ification { let _ = self.dynamic_tool_status_updates.send(status.clone()); } diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index ff9d40f423..ba9367ff99 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -3579,6 +3579,11 @@ impl App { AppEvent::OpenAgentPicker => { self.open_agent_picker(app_server).await; } + AppEvent::DiscoverSidebarAgents(root) => { + if self.primary_thread_id == Some(root) && !self.reconnect.offline { + self.refresh_agent_picker_threads(app_server, root); + } + } AppEvent::AgentPickerThreadsLoaded { primary_thread_id, request_id, diff --git a/codex-rs/tui/src/app/loaded_threads.rs b/codex-rs/tui/src/app/loaded_threads.rs index 75d3ed5ba5..25ad6a72fd 100644 --- a/codex-rs/tui/src/app/loaded_threads.rs +++ b/codex-rs/tui/src/app/loaded_threads.rs @@ -112,7 +112,7 @@ fn thread_spawn_agent_path(source: &SessionSource) -> Option { } } -fn thread_spawn_parent_thread_id(source: &SessionSource) -> Option { +pub(super) fn thread_spawn_parent_thread_id(source: &SessionSource) -> Option { match source { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, .. diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index f1957423bf..c0cf01c2e6 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -263,6 +263,11 @@ impl App { { pane.close = None; } + if let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent()) + && pane.visible_content().is_some() + { + pane.sync_agent_rows(&self.agent_navigation); + } let layout = sidebar::paint_layout(self, tui, screen_size.into()); let displayed = self.current_displayed_thread_id(); let chat = match displayed.and_then(|id| self.side_pair_key(id)) { diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index 39fec4f651..33c1b96732 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -565,6 +565,11 @@ impl App { self.agent_navigation.mark_stopped(id); } if self.primary_thread_id == Some(id) { + self.restore_sidebar_agent_outcomes( + id, + &started.turns, + super::sidebar_subagents::OutcomeReplay::Reconnect, + ); self.primary_session_configured = Some(started.session.clone()); } if started.blocks_direct_input { diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index c42b4abd9b..9b7151c2e4 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -1822,6 +1822,7 @@ impl App { let mut refreshed_thread_ids = HashSet::new(); for thread in find_loaded_subagent_threads_for_primary(threads, primary_thread_id) { + self.register_sidebar_agent(primary_thread_id, thread.thread_id); let agent_path = thread.agent_path; let has_live_channel = self .thread_event_channels diff --git a/codex-rs/tui/src/app/side_focus.rs b/codex-rs/tui/src/app/side_focus.rs index 218792a810..0eae0a7064 100644 --- a/codex-rs/tui/src/app/side_focus.rs +++ b/codex-rs/tui/src/app/side_focus.rs @@ -403,6 +403,7 @@ impl App { && list_action != ListAction::Cancel && pane.creation.is_none() && pane.chat_tabs().files.is_empty() + && pane.chat_tabs().agents.is_empty() { return true; } @@ -451,7 +452,9 @@ impl App { if let ChooserAction::Open(index) = action && new_chat == sidebar_chooser::NewChatState::WaitingForMainMessage && self.sidebar().is_some_and(|pane| { - pane.creation.is_none() && pane.chat_tabs().file(index).is_none() + pane.creation.is_none() + && pane.chat_tabs().file(index).is_none() + && pane.chat_tabs().agent(index).is_none() }) { return true; @@ -486,6 +489,23 @@ impl App { return true; } let pane = self.sidebar_mut(); + if let ChooserAction::Open(index) = action + && pane.creation.is_none() + && let Some(agent) = pane.chat_tabs().agent(index).map(|agent| agent.id) + { + pane.choice = index; + if self + .agent_navigation + .visible_threads() + .iter() + .any(|(id, _)| *id == agent) + && let Err(error) = Box::pin(self.select_agent_thread(tui, server, agent)).await + { + self.chat_widget.add_error_message(error.to_string()); + } + self.guard_chooser_key(activation); + return true; + } if let ChooserAction::Open(index) = action && pane.creation.is_none() && pane.chat_tabs().retry_row(index) diff --git a/codex-rs/tui/src/app/sidebar.rs b/codex-rs/tui/src/app/sidebar.rs index 1e3640d37e..3fe70e76a0 100644 --- a/codex-rs/tui/src/app/sidebar.rs +++ b/codex-rs/tui/src/app/sidebar.rs @@ -2,6 +2,7 @@ //! can paint the closing frames and reverse direction if reopened mid-slide. use super::App; +use super::agent_navigation::AgentNavigationState; use super::pane_motion::PaneMotion; use super::side_pane; use super::side_pane::SidePaneLayout; @@ -65,6 +66,7 @@ impl SideCreation { #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum ChooserSelection { + Agent(ThreadId), New, Chat(ThreadId), Retry, @@ -92,6 +94,7 @@ pub(super) struct SidebarPane { pub(super) focus_document_request: Option, content: SidebarContent, tabs: Vec, + pub(super) agents: super::sidebar_subagents::Overview, // The chooser keeps the same order when an attached chat becomes a live tab. choices: Vec, // A snapshot of the visible rows at the last explicit chooser refresh. @@ -204,6 +207,7 @@ impl SidebarPane { opening: self.opening.as_ref(), ids: &self.tabs, choices: &self.choices, + agents: &self.agents.rows, latest_prompts: &self.latest_prompts, selected: self.visits.last().copied(), files: self @@ -219,23 +223,59 @@ impl SidebarPane { } } + pub(super) fn sync_agent_rows(&mut self, nav: &AgentNavigationState) { + let rows = self.agents.chooser_rows(nav); + let reordered = self + .agents + .rows + .iter() + .map(|agent| agent.id) + .ne(rows.iter().map(|agent| agent.id)); + let selection = self.input_state().choice; + self.agents.rows = rows; + if reordered { + self.restore_choice(selection); + self.tabs_revision += 1; + } + } + + fn restore_choice(&mut self, selection: ChooserSelection) { + let tabs = self.chat_tabs(); + let index = match selection { + ChooserSelection::New => Some(0), + ChooserSelection::Chat(id) => tabs.choice_index(id), + ChooserSelection::Agent(id) => tabs.agent_index(id), + ChooserSelection::File(offset) => { + Some(tabs.file_start() + offset).filter(|&index| tabs.file(index).is_some()) + } + ChooserSelection::Retry => { + Some(tabs.choices.len() + 1).filter(|&index| tabs.retry_row(index)) + } + }; + if let Some(index) = index { + self.choice = index; + } else { + self.reset_choice(); + } + } + pub(super) fn set_discovery(&mut self, discovery: Discovery) { - let file = self.chat_tabs().file_offset(self.choice); - if matches!(discovery, Discovery::Failed(_)) && self.choices.is_empty() { - self.choice = 1; - } + let selection = self.input_state().choice; self.discovery = discovery; - if let Some(offset) = file { - self.choice = self.chat_tabs().file_start() + offset; + if self.choices.is_empty() + && matches!(self.discovery, Discovery::Failed(_)) + && selection == ChooserSelection::New + { + self.choice = 1; + } else { + self.restore_choice(selection); } - self.choice = self.choice.min(self.chat_tabs().choice_count() - 1); self.tabs_revision += 1; } pub(super) fn update_saved_chats(&mut self, mut chats: Vec) { - let file = self.chat_tabs().file_offset(self.choice); - let selection = self.chat_tabs().choice(self.choice); - let keep_new = self.choice == 0 && !self.choices.is_empty(); + let selection = self.input_state().choice; + let was_empty = self.choices.is_empty(); for chat in &mut self.choices { if !self.tabs.contains(&SidebarTab::Chat(chat.id)) { continue; @@ -254,12 +294,10 @@ impl SidebarPane { self.choices = chats; if reordered { self.tabs_revision += 1; - if let Some(offset) = file { - self.choice = self.chat_tabs().file_start() + offset; - } else if let Some(index) = selection.and_then(|id| self.chat_tabs().choice_index(id)) { - self.choice = index; - } else if !keep_new { + if selection == ChooserSelection::New && was_empty { self.reset_choice(); + } else { + self.restore_choice(selection); } } } @@ -386,6 +424,8 @@ impl SidebarPane { ChooserSelection::Retry } else if let Some(offset) = tabs.file_offset(self.choice) { ChooserSelection::File(offset) + } else if let Some(agent) = tabs.agent(self.choice) { + ChooserSelection::Agent(agent.id) } else { ChooserSelection::New }; @@ -403,10 +443,9 @@ impl SidebarPane { fn add_tab(&mut self, id: ThreadId) { if !self.tabs.contains(&SidebarTab::Chat(id)) { if self.chat_tabs().choice_index(id).is_none() { - if self.chat_tabs().file_offset(self.choice).is_some() { - self.choice += 1; - } + let selection = self.input_state().choice; self.choices.push(id.into()); + self.restore_choice(selection); } self.tabs.push(SidebarTab::Chat(id)); self.tabs_revision += 1; @@ -455,8 +494,9 @@ impl SidebarPane { self.remove_choice(id); } if self.content == SidebarContent::Chat(id) { - self.content = match self.selected_chat() { - Some(child) => SidebarContent::Chat(child), + self.content = match self.recent_tab(/*excluding*/ None) { + Some(SidebarTab::Chat(child)) => SidebarContent::Chat(child), + Some(SidebarTab::Document(doc)) => SidebarContent::Document(doc), None => { self.hide(); self.motion = PaneMotion::default(); @@ -475,16 +515,13 @@ impl SidebarPane { self.opening = None; } if let Some(index) = self.chat_tabs().choice_index(id) { + let selection = self.input_state().choice; self.choices.remove(index - 1); - if index < self.choice { - self.choice -= 1; - } - let last = if self.files.is_some() { - self.chat_tabs().choice_count() - 1 + if selection == ChooserSelection::Chat(id) { + self.choice = index.min(self.chat_tabs().choice_count() - 1); } else { - self.choices.len() - }; - self.choice = self.choice.min(last); + self.restore_choice(selection); + } self.tabs_revision += 1; } } @@ -631,10 +668,8 @@ impl App { pub(super) fn panel_focus(&self) -> Option { let pane = self.sidebar()?; - match pane.content { - SidebarContent::Chooser | SidebarContent::Document(_) => pane.focus, - SidebarContent::Chat(_) => None, - } + pane.focus + .filter(|_| !matches!(pane.content, SidebarContent::Chat(_))) } pub(super) fn sidebar_has_focus(&self) -> bool { diff --git a/codex-rs/tui/src/app/sidebar_agent_status.rs b/codex-rs/tui/src/app/sidebar_agent_status.rs new file mode 100644 index 0000000000..d0cc564df3 --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_agent_status.rs @@ -0,0 +1,178 @@ +//! Retain observed subagent outcomes across later idle/unloaded notifications. +//! Only explicit work starts clear an outcome; idle alone never implies completion. + +use super::Overview; +use codex_app_server_protocol::CollabAgentStatus; +use codex_app_server_protocol::CollabAgentTool; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::SubAgentActivityKind; +use codex_app_server_protocol::ThreadItemPayload; +use codex_app_server_protocol::ThreadStatus; +use codex_app_server_protocol::TurnStatus; +use codex_protocol::ThreadId; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum State { + Starting, + Running, + Waiting, + Idle, + Completed, + Stopped, + Failed, + Closed, + Unavailable, +} + +impl State { + pub(super) fn active(self) -> bool { + matches!(self, Self::Starting | Self::Running | Self::Waiting) + } + + pub(super) fn supersedes(self, previous: Option, start_hint: bool) -> bool { + // Spawn activity can arrive after the child's own completion notification. + !(previous.is_some_and(Self::done) + && (matches!(self, Self::Idle | Self::Unavailable) || start_hint && !self.done())) + } + + pub(super) fn done(self) -> bool { + matches!( + self, + Self::Completed | Self::Stopped | Self::Failed | Self::Closed + ) + } + + pub(super) fn label(self) -> (&'static str, &'static str) { + match self { + Self::Starting => ("●", "Starting"), + Self::Running => ("●", "Running"), + Self::Waiting => ("●", "Waiting"), + Self::Idle => ("○", "Idle"), + Self::Completed => ("○", "Completed"), + Self::Stopped => ("○", "Stopped"), + Self::Failed => ("!", "Failed"), + Self::Closed => ("○", "Closed"), + Self::Unavailable => ("○", "Unavailable"), + } + } +} + +pub(super) fn thread_status(status: &ThreadStatus) -> State { + match status { + ThreadStatus::Active { active_flags } if !active_flags.is_empty() => State::Waiting, + ThreadStatus::Active { .. } => State::Running, + ThreadStatus::Idle => State::Idle, + ThreadStatus::SystemError => State::Failed, + ThreadStatus::NotLoaded => State::Unavailable, + } +} + +pub(super) fn observe(event: &ServerNotification, overview: &mut Overview) -> bool { + let Overview { + members, + states, + restored_outcomes, + .. + } = overview; + let item = match event { + ServerNotification::ItemStarted(e) => Some(&e.item.payload), + ServerNotification::ItemCompleted(e) => Some(&e.item.payload), + _ => None, + }; + let mut changed = false; + let mut update = |raw: &str, state: State, start_hint| { + let Ok(id) = ThreadId::from_string(raw) else { + return; + }; + if !members.contains(&id) || !state.supersedes(states.get(&id).copied(), start_hint) { + return; + } + restored_outcomes.remove(&id); + changed |= states.insert(id, state) != Some(state); + }; + match event { + ServerNotification::ThreadStarted(e) => { + update( + &e.thread.id, + thread_status(&e.thread.status), + /*start_hint*/ false, + ) + } + ServerNotification::ThreadStatusChanged(e) => { + update( + &e.thread_id, + thread_status(&e.status), + /*start_hint*/ false, + ) + } + ServerNotification::ThreadClosed(e) => { + update(&e.thread_id, State::Unavailable, /*start_hint*/ false) + } + ServerNotification::TurnStarted(e) => { + update(&e.thread_id, State::Running, /*start_hint*/ false) + } + ServerNotification::TurnCompleted(e) => update( + &e.thread_id, + match e.turn.status { + TurnStatus::Completed => State::Completed, + TurnStatus::Interrupted => State::Stopped, + TurnStatus::Failed => State::Failed, + TurnStatus::InProgress => State::Running, + }, + /*start_hint*/ false, + ), + _ => {} + } + if let Some(item) = item { + visit_item(item, update); + } + changed +} + +pub(super) fn visit_item(item: &ThreadItemPayload, mut update: impl FnMut(&str, State, bool)) { + match item { + ThreadItemPayload::SubAgentActivity { + agent_thread_id, + kind, + .. + } => match kind { + SubAgentActivityKind::Started => { + update(agent_thread_id, State::Running, /*start_hint*/ true) + } + SubAgentActivityKind::Completed => { + update(agent_thread_id, State::Completed, /*start_hint*/ false) + } + SubAgentActivityKind::Interrupted => { + update(agent_thread_id, State::Stopped, /*start_hint*/ false) + } + // Ordinary mailbox delivery emits this too; it need not start a turn. + SubAgentActivityKind::Interacted => {} + }, + ThreadItemPayload::CollabAgentToolCall { + agents_states, + tool, + .. + } => { + for (id, state) in agents_states { + update( + id, + match state.status { + CollabAgentStatus::PendingInit => State::Starting, + CollabAgentStatus::Running => State::Running, + CollabAgentStatus::Interrupted => State::Stopped, + CollabAgentStatus::Completed => State::Completed, + CollabAgentStatus::Errored => State::Failed, + CollabAgentStatus::Shutdown => State::Closed, + CollabAgentStatus::NotFound => State::Unavailable, + }, + *tool == CollabAgentTool::SpawnAgent, + ); + } + } + _ => {} + } +} + +#[cfg(test)] +#[path = "sidebar_agent_status_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/app/sidebar_agent_status_tests.rs b/codex-rs/tui/src/app/sidebar_agent_status_tests.rs new file mode 100644 index 0000000000..879d68f6b3 --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_agent_status_tests.rs @@ -0,0 +1,294 @@ +#![cfg(test)] + +use super::*; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::ThreadClosedNotification; +use codex_app_server_protocol::ThreadStatusChangedNotification; +use codex_app_server_protocol::TurnCompletedNotification; +use pretty_assertions::assert_eq; +use std::collections::HashMap; +use std::collections::HashSet; + +#[test] +fn idle_preserves_explicit_outcome_until_new_work() { + let id = ThreadId::new(); + let mut overview = Overview { + members: HashSet::from([id]), + ..Default::default() + }; + let thread_status = |status| { + ServerNotification::ThreadStatusChanged(ThreadStatusChangedNotification { + thread_id: id.to_string(), + status, + }) + }; + let completed = |status| { + ServerNotification::TurnCompleted(TurnCompletedNotification { + thread_id: id.to_string(), + turn: crate::app::tests::test_turn("turn", status, Vec::new()), + }) + }; + let completed_item = |item| { + ServerNotification::ItemCompleted(ItemCompletedNotification::new( + ThreadId::new().to_string(), + "parent-turn".into(), + item, + /*started_at_ms*/ None, + /*completed_at_ms*/ 0, + )) + }; + let activity = |kind| { + completed_item(ThreadItemPayload::SubAgentActivity { + model: None, + reasoning_effort: None, + id: "activity".into(), + kind, + agent_thread_id: id.to_string(), + agent_path: "/root/worker".into(), + }) + }; + observe(&thread_status(ThreadStatus::Idle), &mut overview); + assert_eq!(overview.states, HashMap::from([(id, State::Idle)])); + observe(&completed(TurnStatus::Completed), &mut overview); + observe(&thread_status(ThreadStatus::Idle), &mut overview); + observe(&activity(SubAgentActivityKind::Interacted), &mut overview); + observe(&activity(SubAgentActivityKind::Started), &mut overview); + observe( + &completed_item(ThreadItemPayload::CollabAgentToolCall { + id: "spawn".into(), + tool: CollabAgentTool::SpawnAgent, + status: codex_app_server_protocol::CollabAgentToolCallStatus::Completed, + sender_thread_id: ThreadId::new().to_string(), + receiver_thread_ids: vec![id.to_string()], + prompt: None, + model: None, + reasoning_effort: None, + agents_states: HashMap::from([( + id.to_string(), + codex_app_server_protocol::CollabAgentState { + status: CollabAgentStatus::Running, + message: None, + }, + )]), + }), + &mut overview, + ); + assert_eq!(overview.states, HashMap::from([(id, State::Completed)])); + observe( + &thread_status(ThreadStatus::Active { + active_flags: Vec::new(), + }), + &mut overview, + ); + assert_eq!(overview.states, HashMap::from([(id, State::Running)])); + observe(&completed(TurnStatus::Failed), &mut overview); + observe(&thread_status(ThreadStatus::Idle), &mut overview); + observe(&thread_status(ThreadStatus::NotLoaded), &mut overview); + observe( + &ServerNotification::ThreadClosed(ThreadClosedNotification { + thread_id: id.to_string(), + }), + &mut overview, + ); + assert_eq!(overview.states, HashMap::from([(id, State::Failed)])); + // Parent activity may be our only evidence of a later successful turn. + observe(&activity(SubAgentActivityKind::Completed), &mut overview); + assert_eq!(overview.states, HashMap::from([(id, State::Completed)])); +} + +#[tokio::test] +async fn chooser_lists_subagents_by_observed_outcome() -> color_eyre::Result<()> { + use crate::app::owned_transcript::tests::attach_thread; + use crate::app::sidebar::PaneFocus; + use crate::app::sidebar::SidebarContent; + use crate::app::test_support::enable_side_retention; + use crate::app::test_support::side_frame; + use crate::app::tests::make_test_app_with_channels; + let (mut app, _events, _ops) = make_test_app_with_channels().await; + enable_side_retention(&mut app)?; + let root = ThreadId::new(); + attach_thread(&mut app, root); + app.primary_thread_id = Some(root); + app.local_settings.tui.animations = false; + let first = ThreadId::new(); + let second = ThreadId::new(); + for (id, name) in [ + (first, "Source navigation reviewer with a long name"), + (second, "Builder"), + ] { + assert!(app.register_sidebar_agent(root, id)); + app.upsert_agent_picker_thread( + id, + Some(name.into()), + /*agent_role*/ None, + /*is_closed*/ false, + ); + } + app.agent_navigation.mark_parent_owned(first); + app.observe_sidebar_agent_event(&ServerNotification::TurnCompleted( + TurnCompletedNotification { + thread_id: second.to_string(), + turn: crate::app::tests::test_turn("done", TurnStatus::Completed, vec![]), + }, + )); + app.sidebar_mut() + .show(SidebarContent::Chooser, PaneFocus::Sidebar); + let mut tui = crate::tui::test_support::make_test_tui()?; + tui.set_owned_screen(/*owned*/ true)?; + for (name, width) in [("subagent_chooser", 210), ("subagent_chooser_narrow", 120)] { + let screen = side_frame(&mut app, &mut tui, ratatui::layout::Size::new(width, 25))?; + let rows = screen + .lines() + .filter_map(|line| line.split_once('│').map(|(_, row)| row.trim_end())) + .filter(|row| !row.trim().is_empty()) + .collect::>() + .join("\n"); + insta::assert_snapshot!(name, rows); + } + + let pane = app.sidebar_mut(); + let old_index = pane.chat_tabs().agent_index(second).expect("second agent"); + pane.choice = old_index; + app.observe_sidebar_agent_event(&ServerNotification::TurnCompleted( + TurnCompletedNotification { + thread_id: first.to_string(), + turn: crate::app::tests::test_turn("done", TurnStatus::Completed, vec![]), + }, + )); + app.observe_sidebar_agent_event(&ServerNotification::ThreadStatusChanged( + ThreadStatusChangedNotification { + thread_id: second.to_string(), + status: ThreadStatus::Active { + active_flags: Vec::new(), + }, + }, + )); + side_frame(&mut app, &mut tui, ratatui::layout::Size::new(120, 25))?; + let pane = app.sidebar().unwrap(); + assert_eq!(pane.choice, old_index - 1); + assert_eq!( + pane.chat_tabs().agent(pane.choice).map(|agent| agent.id), + Some(second) + ); + Ok(()) +} + +#[tokio::test] +async fn active_discovery_supersedes_restored_completion() -> color_eyre::Result<()> { + use crate::app::owned_transcript::tests::attach_thread; + use crate::app::test_support::enable_side_retention; + use crate::app::tests::make_test_app_with_channels; + + let (mut app, _events, _ops) = Box::pin(make_test_app_with_channels()).await; + enable_side_retention(&mut app)?; + let config = app.chat_widget.config_ref(); + let mut server = Box::pin(crate::start_embedded_app_server_for_picker(config)).await?; + let root = ThreadId::new(); + let child = ThreadId::from_string( + &app_test_support::create_fake_paginated_rollout( + config.codex_home.as_path(), + "2025-01-05T12-00-00", + "2025-01-05T12:00:00Z", + "Child conversation", + Some(config.model_provider_id.as_str()), + /*git_info*/ None, + ) + .expect("seed child history"), + )?; + let mut thread = Box::pin(server.thread_read(child, /*include_turns*/ false)).await?; + thread.status = ThreadStatus::Active { + active_flags: Vec::new(), + }; + + let completed = ThreadId::new(); + let mut completed_thread = thread.clone(); + completed_thread.id = completed.to_string(); + attach_thread(&mut app, root); + app.primary_thread_id = Some(root); + let failed = ThreadId::new(); + let mut failed_thread = thread.clone(); + failed_thread.id = failed.to_string(); + failed_thread.status = ThreadStatus::SystemError; + let outcomes = [child, completed] + .into_iter() + .flat_map(|id| { + [ + SubAgentActivityKind::Completed, + SubAgentActivityKind::Started, + ] + .into_iter() + .map(move |kind| ThreadItemPayload::SubAgentActivity { + id: format!("completed-{id}"), + kind, + agent_thread_id: id.to_string(), + agent_path: "/root/worker".into(), + model: None, + reasoning_effort: None, + }) + }) + .collect(); + app.register_sidebar_agent(root, child); + app.observe_sidebar_agent_event(&ServerNotification::ThreadStatusChanged( + ThreadStatusChangedNotification { + thread_id: child.to_string(), + status: thread.status.clone(), + }, + )); + app.restore_sidebar_agent_outcomes( + root, + &[crate::app::tests::test_turn( + "saved-turn", + TurnStatus::Completed, + outcomes, + )], + super::super::OutcomeReplay::Reconnect, + ); + for id in [child, completed] { + app.upsert_agent_picker_thread( + id, + Some("worker".into()), + /*agent_role*/ None, + /*is_closed*/ false, + ); + } + let rows = |app: &crate::app::App| { + app.sidebar() + .unwrap() + .agents + .chooser_rows(&app.agent_navigation) + .into_iter() + .map(|row| (row.id, row.status)) + .collect::>() + }; + assert!(rows(&app).iter().all(|(_, state)| *state == "Completed")); + let request = app + .agent_navigation + .begin_picker_refresh(root) + .expect("start discovery"); + // A completion arriving while the refresh is in flight wins over the active snapshot. + app.observe_sidebar_agent_event(&ServerNotification::TurnCompleted( + TurnCompletedNotification { + thread_id: completed.to_string(), + turn: crate::app::tests::test_turn("fresh-turn", TurnStatus::Completed, Vec::new()), + }, + )); + app.apply_agent_picker_thread_refresh( + &server, + root, + request, + Ok(crate::app_event::AgentPickerThreadRefresh { + threads: vec![thread, completed_thread, failed_thread], + archived_thread_ids: HashSet::new(), + }), + ); + assert_eq!( + rows(&app), + vec![ + (child, "Running"), + (completed, "Completed"), + (failed, "Failed") + ] + ); + server.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/tui/src/app/sidebar_files_tests.rs b/codex-rs/tui/src/app/sidebar_files_tests.rs index 4147451e6d..e8dfec4035 100644 --- a/codex-rs/tui/src/app/sidebar_files_tests.rs +++ b/codex-rs/tui/src/app/sidebar_files_tests.rs @@ -57,11 +57,17 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr files.promote(entries.into_iter().rev()); let mut pane = super::super::sidebar::SidebarPane::default(); pane.files = Some(files); + pane.agents.rows.push(sidebar_chooser::AgentRow { + id: ThreadId::new(), + name: "Reviewer".into(), + symbol: "○", + status: "Completed", + }); pane.choice = pane.chat_tabs().file_start(); pane.update_saved_chats(vec![ThreadId::new().into()]); assert_eq!(pane.chat_tabs().file_offset(pane.choice), Some(0)); let area = Rect::new( - /*x*/ 0, /*y*/ 0, /*width*/ 50, /*height*/ 23, + /*x*/ 0, /*y*/ 0, /*width*/ 50, /*height*/ 30, ); let mut buffer = Buffer::empty(area); sidebar_chooser::paint( @@ -98,6 +104,11 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr ○ Side chat + Subagents 1 + + ○ Reviewer + Completed + Files 4 › · Makefile @@ -119,7 +130,7 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr location: None, }]); let wide = Rect::new( - /*x*/ 0, /*y*/ 0, /*width*/ 75, /*height*/ 20, + /*x*/ 0, /*y*/ 0, /*width*/ 75, /*height*/ 24, ); let mut wide_buffer = Buffer::empty(wide); let frames = tui::FrameRequester::test_dummy(); @@ -152,8 +163,9 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr insta::assert_snapshot!(file_rows, @" › · Makefile Project root · guide.md notes - · guide.md /Users/example/workspaces/re…ect-name/codex-rs/tui/src/app + · guide.md /Users/example/workspaces/re…ct-name/codex-rs/tui/src/app "); + let right_padding = usize::from(sidebar_chooser::body_row(wide, wide.y).right() - 1); let [selected, hovered]: [_; 2] = wide_buffer .content .chunks(usize::from(wide.width)) @@ -161,7 +173,13 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr let text = cells.iter().map(Cell::symbol).collect::(); text.contains("Makefile") || text.contains("/Users/example") }) - .map(|row| (row[2].bg, row[2].modifier)) + .map(|row| { + assert_eq!( + (row[right_padding].symbol(), row[right_padding].bg), + (" ", row[2].bg) + ); + (row[2].bg, row[2].modifier) + }) .collect::>() .try_into() .expect("selected and hovered files"); @@ -228,7 +246,7 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr let tabs = pane.chat_tabs(); let targets: Vec<_> = sidebar_chooser::row_targets(area, tabs, pane.choice, NewChatState::Available).collect(); - for row in 10..=12 { + for row in (10..=12).chain(15..=17) { assert!( targets .iter() @@ -239,6 +257,14 @@ fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyr targets .iter() .find(|(_, area)| area.contains((1, 13).into())) + .and_then(|(index, _)| tabs.agent(*index)) + .map(|agent| agent.name.as_str()), + Some("Reviewer"), + ); + assert_eq!( + targets + .iter() + .find(|(_, area)| area.contains((1, 18).into())) .and_then(|(index, _)| tabs.file(*index)), tabs.file(pane.choice), ); diff --git a/codex-rs/tui/src/app/sidebar_subagents.rs b/codex-rs/tui/src/app/sidebar_subagents.rs new file mode 100644 index 0000000000..a6bf9cc894 --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_subagents.rs @@ -0,0 +1,253 @@ +//! Sidebar subagents follow the primary conversation's spawn tree and retain observed outcomes. +use super::*; +use crate::sidebar_chooser::AgentRow; +use codex_app_server_protocol::CollabAgentStatus; +use codex_app_server_protocol::CollabAgentTool; +use codex_app_server_protocol::ThreadStatus; +use std::collections::HashSet; + +#[path = "sidebar_agent_status.rs"] +mod status; +use status::State; + +pub(super) enum OutcomeReplay { + History, + Reconnect, +} + +#[derive(Default)] +pub(super) struct Overview { + members: HashSet, + states: HashMap, + restored_outcomes: HashSet, + pub(super) rows: Vec, +} + +impl Overview { + pub(super) fn chooser_rows(&self, nav: &AgentNavigationState) -> Vec { + let mut rows: Vec<_> = nav + .visible_threads() + .into_iter() + .filter(|(id, _)| self.members.contains(id)) + .map(|(id, entry)| { + let state = self.states.get(&id).copied().unwrap_or(if entry.is_closed { + State::Unavailable + } else if entry.is_running { + State::Running + } else { + State::Idle + }); + (id, entry, state) + }) + .collect(); + rows.sort_by_key(|(_, _, state)| (!state.active(), state.done())); + rows.into_iter() + .map(|(id, entry, state)| { + let name = entry + .agent_path + .as_deref() + .map(|path| path.strip_prefix("/root/").unwrap_or(path).to_owned()) + .unwrap_or_else(|| { + if entry.agent_nickname.is_none() && entry.agent_role.is_none() { + id.to_string() + } else { + format_agent_picker_item_name( + entry.agent_nickname.as_deref(), + entry.agent_role.as_deref(), + /*is_primary*/ false, + ) + } + }); + let (symbol, status) = state.label(); + AgentRow { + id, + name, + symbol, + status, + } + }) + .collect() + } +} + +impl App { + pub(super) fn is_sidebar_agent(&self, id: ThreadId) -> bool { + self.primary_thread_id + .and_then(|root| self.sidebars.get(&Some(root))) + .is_some_and(|pane| pane.agents.members.contains(&id)) + } + pub(in crate::app) fn restore_sidebar_agent_outcomes( + &mut self, + root: ThreadId, + turns: &[codex_app_server_protocol::Turn], + source: OutcomeReplay, + ) { + let mut restored = HashMap::new(); + for item in turns.iter().flat_map(|turn| &turn.items) { + status::visit_item(&item.payload, |raw, state, start_hint| { + if let Ok(id) = ThreadId::from_string(raw) + && state.supersedes(restored.get(&id).copied(), start_hint) + { + restored.insert(id, state); + } + }); + } + for (id, state) in restored { + if state.done() + && self.register_sidebar_agent(root, id) + && let Some(tabs) = self.sidebars.get_mut(&Some(root)) + && tabs.agents.states.get(&id).is_none_or(|previous| { + matches!(source, OutcomeReplay::Reconnect) && previous.active() + }) + { + tabs.agents.states.insert(id, state); + tabs.agents.restored_outcomes.insert(id); + } + } + } + + // Active or failed discovery supersedes saved history. Live notifications can arrive during + // discovery and take precedence over its response. + pub(super) fn seed_discovered_sidebar_agent( + &mut self, + root: ThreadId, + child: ThreadId, + status: &ThreadStatus, + ) { + if let Some(pane) = self.sidebars.get_mut(&Some(root)) + && (pane.agents.restored_outcomes.remove(&child) + || !pane.agents.states.contains_key(&child)) + { + pane.agents + .states + .insert(child, status::thread_status(status)); + } + } + + pub(in crate::app) fn register_sidebar_agent( + &mut self, + parent: ThreadId, + child: ThreadId, + ) -> bool { + let Some(root) = self.primary_thread_id else { + return false; + }; + if !self.local_settings.workspace_enabled(&self.config) || root == child { + return false; + } + let parents = &mut self.sidebars; + if parent != root + && !parents + .get(&Some(root)) + .is_some_and(|t| t.agents.members.contains(&parent)) + { + return false; + } + let tabs = parents.entry(Some(root)).or_default(); + if tabs.agents.members.insert(child) { + self.chat_widget.request_redraw(); + } + true + } + + pub(in crate::app) fn observe_sidebar_agent_event(&mut self, event: &ServerNotification) { + if !self.local_settings.workspace_enabled(&self.config) { + return; + } + match event { + ServerNotification::ThreadStarted(e) => { + if let Some(parent) = + super::loaded_threads::thread_spawn_parent_thread_id(&e.thread.source) + && let Ok(child) = ThreadId::from_string(&e.thread.id) + && self.register_sidebar_agent(parent, child) + { + self.upsert_agent_picker_thread( + child, + e.thread.agent_nickname.clone(), + e.thread.agent_role.clone(), + /*is_closed*/ false, + ); + self.agent_navigation.set_agent_path( + child, + crate::app_server_session::source_agent_path(&e.thread.source), + ); + self.agent_navigation.set_running( + child, + matches!(e.thread.status, ThreadStatus::Active { .. }), + ); + if crate::app_server_session::thread_blocks_direct_input(&e.thread) { + self.agent_navigation.mark_parent_owned(child); + } + } + } + ServerNotification::ThreadStatusChanged(e) => { + if let Ok(id) = ThreadId::from_string(&e.thread_id) + && self.is_sidebar_agent(id) + { + self.agent_navigation + .set_running(id, matches!(e.status, ThreadStatus::Active { .. })); + self.chat_widget.request_redraw(); + } + } + ServerNotification::ItemStarted(_) | ServerNotification::ItemCompleted(_) => { + let (sender, item) = match event { + ServerNotification::ItemStarted(e) => (&e.thread_id, &e.item.payload), + ServerNotification::ItemCompleted(e) => (&e.thread_id, &e.item.payload), + _ => return, + }; + let Ok(parent) = ThreadId::from_string(sender) else { + return; + }; + if let Some(activity) = sub_agent_activity_display(item) { + if self.register_sidebar_agent(parent, activity.thread_id) { + self.agent_navigation.record_sub_agent_activity(activity); + self.chat_widget.request_redraw(); + } + } else if let ThreadItemPayload::CollabAgentToolCall { + tool, + receiver_thread_ids, + agents_states, + .. + } = item + { + for id in receiver_thread_ids { + let Ok(child) = ThreadId::from_string(id) else { + continue; + }; + let state = agents_states.get(id); + if state.is_some_and(|s| s.status == CollabAgentStatus::NotFound) { + continue; + } + if *tool == CollabAgentTool::SpawnAgent + && self.register_sidebar_agent(parent, child) + && self.agent_navigation.get(&child).is_none() + { + self.upsert_agent_picker_thread( + child, /*agent_nickname*/ None, /*agent_role*/ None, + /*is_closed*/ false, + ); + } + if let Some(state) = state + && self.is_sidebar_agent(child) + { + let running = matches!( + state.status, + CollabAgentStatus::PendingInit | CollabAgentStatus::Running + ); + self.agent_navigation.set_running(child, running); + self.chat_widget.request_redraw(); + } + } + } + } + _ => {} + } + let mut changed = false; + for tabs in self.sidebars.values_mut() { + changed |= status::observe(event, &mut tabs.agents); + } + if changed { + self.chat_widget.request_redraw(); + } + } +} diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_subagents__status__tests__subagent_chooser.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_subagents__status__tests__subagent_chooser.snap new file mode 100644 index 0000000000..8949d5ea92 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_subagents__status__tests__subagent_chooser.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/app/sidebar_agent_status_tests.rs +expression: rows +--- + + + Open in sidebar + › + New side chat Available after first message + Subagents 2 + ○ Source navigation reviewer with a long name Idle + ○ Builder Completed + esc back · ↑/↓ move · ⌃x - hide pane diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_subagents__status__tests__subagent_chooser_narrow.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_subagents__status__tests__subagent_chooser_narrow.snap new file mode 100644 index 0000000000..f2aaf11ea5 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_subagents__status__tests__subagent_chooser_narrow.snap @@ -0,0 +1,14 @@ +--- +source: tui/src/app/sidebar_agent_status_tests.rs +expression: rows +--- + + + Open in sidebar + › + New side chat + Available after first message + Subagents 2 + ○ Source navigation reviewer with… + Idle + ○ Builder + Completed + esc back · ↑/↓ move · ⌃x - hide pane diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap index bba158f96e..2779d4733b 100644 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap @@ -1,6 +1,5 @@ --- source: tui/src/app/tests.rs -assertion_line: 3679 expression: "states.join(\"\\n\\n\")" --- Loading @@ -69,7 +68,7 @@ Refreshed chats Side chats 2 › ○ Named sibling - Latest request with 界 界 界 a… + Latest request with 界 界 界 … ○ Child-only prompt Readable reply @@ -82,6 +81,6 @@ Readable reply Side chats 2 › ○ Named sibling - > Which branch? Keep ## My r… + > Which branch? Keep ## My … ○ Child-only prompt ↓ diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 57c4f2435a..5cae6251f3 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -10393,7 +10393,7 @@ async fn resizing_empty_transcript_schedules_settled_size_recheck() { ); } -fn test_turn(turn_id: &str, status: TurnStatus, items: Vec) -> Turn { +pub(super) fn test_turn(turn_id: &str, status: TurnStatus, items: Vec) -> Turn { Turn { id: turn_id.to_string(), root_turn_id: None, diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 8983a86c38..3891ae0356 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -1621,6 +1621,21 @@ impl App { self.recap.reset_for_new_thread(Instant::now()); } self.primary_thread_id = Some(thread_id); + if self.local_settings.workspace_enabled(&self.config) + && matches!( + presentation, + ThreadAttachPresentation::SessionLineage + | ThreadAttachPresentation::SessionLineageAfterClear + ) + { + self.restore_sidebar_agent_outcomes( + thread_id, + &turns, + super::sidebar_subagents::OutcomeReplay::History, + ); + self.app_event_tx + .send(AppEvent::DiscoverSidebarAgents(thread_id)); + } self.agents_overview.hidden_threads.remove(&thread_id); self.agents_overview.threads.entry(thread_id).or_default(); self.primary_session_configured = Some(session.clone()); @@ -1891,6 +1906,18 @@ impl App { mut snapshot: ThreadEventSnapshot, resume_restored_queue: bool, ) { + if let Some(root) = self.primary_thread_id + && snapshot + .session + .as_ref() + .is_some_and(|s| s.thread_id == root) + { + self.restore_sidebar_agent_outcomes( + root, + &snapshot.turns, + super::sidebar_subagents::OutcomeReplay::History, + ); + } let mut reasoning_replay = reasoning_replay::ReasoningReplay::new(&mut snapshot); let replayed_final_items = realtime_delivery::completed_agent_items(&snapshot); let replayed_voice_texts = realtime_delivery::replayed_voice_texts(&snapshot); diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index ebc48ef459..f47a152d82 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -489,6 +489,8 @@ pub(crate) enum AppEvent { }, /// Open the agent picker for switching active threads. OpenAgentPicker, + /// Discover saved subagents on the owning backend after attaching a primary thread. + DiscoverSidebarAgents(ThreadId), /// Merge a completed root-scoped agent-picker refresh without blocking terminal input. AgentPickerThreadsLoaded { primary_thread_id: ThreadId, diff --git a/codex-rs/tui/src/sidebar_chooser.rs b/codex-rs/tui/src/sidebar_chooser.rs index 2b8bdc0ab2..51c90265e6 100644 --- a/codex-rs/tui/src/sidebar_chooser.rs +++ b/codex-rs/tui/src/sidebar_chooser.rs @@ -106,7 +106,9 @@ pub(crate) fn footer( let visible = choice_is_visible(area, tabs, choice); let movement = [ListAction::MoveUp, ListAction::MoveDown] .into_iter() - .filter(|_| new_chat == NewChatState::Available || !tabs.files.is_empty()) + .filter(|_| { + new_chat == NewChatState::Available || !tabs.files.is_empty() || !tabs.agents.is_empty() + }) .filter_map(hint) .collect::>() .join("/"); @@ -117,7 +119,10 @@ pub(crate) fn footer( ( hint(ListAction::Accept) .filter(|_| { - visible && (new_chat == NewChatState::Available || selected_file.is_some()) + visible + && (new_chat == NewChatState::Available + || selected_file.is_some() + || tabs.agent(choice).is_some()) }) .filter(|_| selected_file.is_none() || tabs.file_preview_unavailable.is_none()), if tabs.retry_row(choice) @@ -195,6 +200,14 @@ pub(crate) enum OpenState { Failed(String), } +/// An agent displayed in the shared sidebar chooser. +pub(crate) struct AgentRow { + pub(crate) id: ThreadId, + pub(crate) name: String, + pub(crate) symbol: &'static str, + pub(crate) status: &'static str, +} + #[derive(Clone, Copy)] pub(crate) struct ChatTabs<'a> { pub(crate) label_style: ThreadLabelStyle, @@ -203,6 +216,7 @@ pub(crate) struct ChatTabs<'a> { pub(crate) ids: &'a [SidebarTab], // Chooser index zero is reserved for New side chat. pub(crate) choices: &'a [SideChat], + pub(crate) agents: &'a [AgentRow], pub(crate) latest_prompts: &'a HashMap, pub(crate) selected: Option, pub(crate) files: &'a [FileLink], @@ -224,8 +238,24 @@ impl<'a> ChatTabs<'a> { self.file_start() + self.files.len() } + pub(crate) fn agent(self, index: usize) -> Option<&'a AgentRow> { + self.agents.get(index.checked_sub(self.first_agent())?) + } + + pub(crate) fn agent_index(self, id: ThreadId) -> Option { + self.agents + .iter() + .position(|agent| agent.id == id) + .map(|offset| self.first_agent() + offset) + } + + fn first_agent(self) -> usize { + let end = self.choices.len() + 1; + end + usize::from(self.retry_row(end)) + } + pub(crate) fn file_start(self) -> usize { - self.choices.len() + 1 + usize::from(self.retry_row(self.choices.len() + 1)) + self.first_agent() + self.agents.len() } pub(crate) fn file_offset(self, index: usize) -> Option { @@ -283,11 +313,14 @@ pub(crate) fn tab_strip( SidebarTab::Document(id) => Line::from(document_title(id, width)), SidebarTab::Chat(id) => { let name = match tabs.choice_index(id) { - Some(number) => match side_chat_label(&tabs.choices[number - 1]) { - Some(name) => name.to_owned(), - None if tabs.choices.len() > 1 => format!("Side {number}"), - None => "Side chat".to_owned(), - }, + Some(index) => { + let ordinal = index - 1; + match side_chat_label(&tabs.choices[ordinal]) { + Some(name) => name.to_owned(), + None if tabs.choices.len() > 1 => format!("Side {}", ordinal + 1), + None => "Side chat".to_owned(), + } + } None => "Side chat".to_owned(), }; tabs.label_style.render(Line::from(name), width) @@ -320,17 +353,20 @@ struct ChoiceRows { wide: bool, height: usize, chats_header: Option, + agents_header: Option, files_header: Option, choices: Vec>, } impl ChoiceRows { fn new(area: Rect, tabs: ChatTabs<'_>) -> Self { - let wide = body_row(area, area.y).width >= WIDE_WIDTH; + let width = body_row(area, area.y).width; + let wide = width >= WIDE_WIDTH; let height = usize::from(area.height.saturating_sub(3)); let mut row = FIRST_CHOICE_ROW; let file_start = tabs.file_start(); let mut chats_header = None; + let mut agents_header = None; let mut files_header = None; let choices = (0..tabs.choice_count()) .map(|index| { @@ -340,13 +376,18 @@ impl ChoiceRows { } else if index == 1 && tabs.retry_row(index) { row += 2; } - let file = index >= file_start; - if index == file_start { + let file = tabs.file_offset(index).is_some(); + let agent = tabs.agent(index).is_some(); + if agent && index == tabs.first_agent() { + agents_header = Some(row + 1); + row += 3; + } + if file && index == file_start { files_header = Some(row + 1); row += 3; } let start = row; - let subtitle = if index == 0 || file { + let subtitle = if index == 0 || file || agent { !wide } else { tabs.prompt(index).is_some() @@ -359,6 +400,7 @@ impl ChoiceRows { wide, height, chats_header, + agents_header, files_header, choices, } @@ -497,7 +539,7 @@ pub(crate) fn row_targets( (first < last && match tabs.file(index) { Some(_) => tabs.file_preview_unavailable.is_none(), - None => new_chat == NewChatState::Available, + None => new_chat == NewChatState::Available || tabs.agent(index).is_some(), }) .then(|| Rect { height: (last - first) as u16, @@ -590,6 +632,7 @@ pub(crate) fn paint( crate::style::quiet_workspace_style() }; let row = |y| body_row(area, y); + let width = usize::from(row(area.y).width.saturating_sub(1)); let footer_y = area.bottom() - 1; if let Some(path) = sidebar_style.full_path { let mut body = body_row(area, area.y + u16::from(area.height > 2) * 2); @@ -610,8 +653,9 @@ pub(crate) fn paint( return; } let rows = ChoiceRows::new(area, tabs); - let waiting = - sidebar_style.new_chat == NewChatState::WaitingForMainMessage && tabs.files.is_empty(); + let waiting = sidebar_style.new_chat == NewChatState::WaitingForMainMessage + && tabs.files.is_empty() + && tabs.agents.is_empty(); let top = if waiting { 0 } else { @@ -621,14 +665,27 @@ pub(crate) fn paint( if let Some(y) = offset.checked_sub(top) && (CHOOSER_BODY_START..CHOOSER_BODY_START + rows.height).contains(&y) { - line.render(row(area.y + y as u16), buf); + let mut content = row(area.y + y as u16); + if content.width > 0 { + content.width -= 1; + buf.set_style( + Rect::new( + content.right(), + content.y, + /*width*/ 1, + /*height*/ 1, + ), + line.style, + ); + } + line.render(content, buf); } }; paint(2, Line::from("Open in sidebar").bold()); if waiting { for (offset, text) in (FIRST_CHOICE_ROW..).zip(textwrap::wrap( "You can start a side chat after your first message in the main chat.", - usize::from(row(area.y).width.max(1)), + width.max(1), )) { paint(offset, Line::from(text).dim()); } @@ -674,11 +731,11 @@ pub(crate) fn paint( let title = format!("{marker} + New side chat"); let detail = match sidebar_style.new_chat { NewChatState::Available => "Start from this conversation", - NewChatState::WaitingForMainMessage => "Available after your first message", + NewChatState::WaitingForMainMessage => "Available after first message", }; let detail = Span::styled(detail, subtitle); if rows.wide { - let pad = usize::from(row(area.y).width - 1) - detail.width(); + let pad = width - detail.width(); paint( y, Line::from(vec![format!("{title: "Opening…".dim(), OpenState::Failed(error) => format!("Retry · {error}").red(), }; - let width = usize::from(row(area.y).width.saturating_sub(6)); + let width = width.saturating_sub(6); let title = label_style.render( Line::from(title), width.saturating_sub(status.width()).max(width / 3),