Open subagent transcripts from activity links in the TUI (#62159)

## Why

When a transcript mentions a subagent, readers have to find it in the
sidebar chooser to inspect its work.

## What changed

Underline subagent labels in transcript activity when the sidebar is
available. Clicking a label opens that agent's transcript beside the
parent conversation, including when the link is in an unfocused pane.

Use backend ancestry to confirm that the linked agent belongs to the
current conversation. If a click arrives while agent discovery is in
progress after resume, resolve it when discovery finishes.

## Testing

Cover clicks from the parent transcript and a nested-agent link in an
unfocused pane, along with clicks during discovery and inherited
activity from a fork. Snapshot the underline across a wrapped label.

GitOrigin-RevId: 75b343c56eac4a009d644f0cfc135b6d9bfbe3a0
This commit is contained in:
Felipe Coury
2026-11-18 02:04:55 +00:00
committed by copyberry
parent cc3757a99d
commit bedafe7156
27 changed files with 578 additions and 178 deletions
+16 -2
View File
@@ -908,6 +908,9 @@ impl App {
}
_ => self.sidebar_press = None,
}
self.transcript_view.agent_links = self
.side_retention_enabled(tui)
.then(|| app_server.backend_id());
self.transcript_view.document_links = self.document_preview_available(tui, app_server);
crate::markdown_render::preferences::set_document_links(
self.transcript_view.document_links,
@@ -1169,12 +1172,23 @@ impl App {
&& painted.passive.union(painted.focused) == Rect::from(size)
{
let painted_area = painted.passive;
if let Some(url) = self.transcript_link_at(*press) {
if let Some(link) = self.transcript_link_at(*press) {
use crate::terminal_hyperlinks::ReaderLink;
if press.modifiers.is_empty() {
self.passive_link_drag = Some((current.passive_thread, painted.passive));
self.handle_passive_transcript_event(tui, current.passive_thread, &event);
} else {
self.open_url_in_browser(url);
match link {
ReaderLink::Agent(agent) => {
self.app_event_tx.send(AppEvent::OpenSidebarAgent {
backend: app_server.backend_id(),
source: current.passive_thread,
agent,
});
}
ReaderLink::External(url) => self.open_url_in_browser(url),
ReaderLink::Document(link) => self.open_url_in_browser(link.path),
}
}
return Ok(AppRunControl::Continue);
}
+1 -1
View File
@@ -75,7 +75,7 @@ pub(super) enum AgentPickerThreadVisibility {
#[derive(Debug)]
pub(super) struct AgentPickerRefreshState {
root: ThreadId,
pub(super) root: ThreadId,
request_id: Uuid,
pub(super) visibility_changed_threads: HashSet<ThreadId>,
pub(super) follow_up_requested: bool,
+12 -9
View File
@@ -3,6 +3,7 @@
use super::agent_navigation::AgentPickerThreadVisibility;
use super::app_server_event_targets::ServerNotificationThreadTarget;
use super::app_server_event_targets::server_notification_thread_target;
use super::sidebar_subagents::PendingLink;
use super::*;
use crate::app_event::AgentPickerThreadRefresh;
use codex_app_server_protocol::RequestId;
@@ -111,15 +112,16 @@ impl App {
root: ThreadId,
request_id: Uuid,
result: Result<AgentPickerThreadRefresh, String>,
) {
let Some(completion) = self
) -> Option<PendingLink> {
let completion = self
.agent_navigation
.finish_picker_refresh(root, request_id)
else {
return;
};
.finish_picker_refresh(root, request_id)?;
let pending_link = self
.sidebars
.get_mut(&Some(root))
.and_then(|pane| pane.agents.pending_link.take());
if self.primary_thread_id != Some(root) {
return;
return None;
}
let refresh = match result {
Ok(refresh) => refresh,
@@ -129,14 +131,14 @@ impl App {
if completion.follow_up_requested {
self.refresh_agent_picker_threads(app_server, root);
}
return;
return None;
}
};
for thread in refresh.threads {
let Ok(thread_id) = ThreadId::from_string(&thread.id) else {
continue;
};
let sidebar_agent = self.register_sidebar_agent(root, thread_id);
let sidebar_agent = self.confirm_sidebar_agent(root, thread_id);
if !completion.visibility_changed_threads.contains(&thread_id) {
self.update_agent_picker_thread_visibility(
thread_id,
@@ -188,6 +190,7 @@ impl App {
if completion.follow_up_requested {
self.refresh_agent_picker_threads(app_server, root);
}
pending_link.filter(|link| link.backend == app_server.backend_id())
}
pub(super) fn set_agent_picker_thread_visibility(
+20 -2
View File
@@ -101,6 +101,7 @@ impl App {
| AppEvent::SideChatArchived { .. }
| AppEvent::SavedChatPrepared { .. } | AppEvent::SavedChatReleased { .. }
| AppEvent::StartQueuedSavedChat
| AppEvent::OpenSidebarAgent { .. }
| AppEvent::OpenSidebarDocument { .. }
| AppEvent::SidebarDocumentResolved { .. }
| AppEvent::SidebarDocumentLoaded { .. }
@@ -178,6 +179,7 @@ impl App {
event,
AppEvent::OpenAgentPicker
| AppEvent::SelectAgentThread(_)
| AppEvent::OpenSidebarAgent { .. }
| AppEvent::StartSide { .. }
| AppEvent::ForkCurrentSession { .. }
| AppEvent::StartManagedWorktree {
@@ -3592,12 +3594,16 @@ impl App {
request_id,
result,
} => {
self.apply_agent_picker_thread_refresh(
if let Some(link) = self.apply_agent_picker_thread_refresh(
app_server,
primary_thread_id,
request_id,
result,
);
)
&& self.sidebar_agent_link_root(tui, link.source) == Some(primary_thread_id)
{
self.open_sidebar_agent(tui, app_server, link.agent).await?;
}
}
AppEvent::SelectAgentThread(thread_id) => {
self.select_agent_thread(tui, app_server, thread_id)
@@ -3665,6 +3671,18 @@ impl App {
Box::pin(self.open_saved_chat(tui, app_server, target)).await?;
}
}
AppEvent::OpenSidebarAgent { backend, source, agent } => {
if backend == app_server.backend_id()
&& let Some(root) = self.sidebar_agent_link_root(tui, source)
{
if self.is_confirmed_sidebar_agent(root, agent) {
self.open_sidebar_agent(tui, app_server, agent).await?;
} else if self.agent_navigation.picker_refresh.as_ref().is_some_and(|refresh| refresh.root == root) {
// Resume can paint a link before its owning thread list returns.
self.sidebar_mut().agents.pending_link = Some(sidebar_subagents::PendingLink { backend, source, agent });
}
}
}
AppEvent::OpenSidebarDocument { backend_id, source, link } => {
if app_server.backend_id() == backend_id
&& self.current_displayed_thread_id() == Some(source)
+13 -2
View File
@@ -13,13 +13,15 @@ use crossterm::event::MouseEventKind::Up;
use super::App;
use super::side_companion::SideCompanion;
use crate::app_event::AppEvent;
use crate::terminal_hyperlinks::ReaderLink;
use crate::transcript_view::ViewAction;
use crate::tui::PointerShape;
use crate::tui::Tui;
use crate::tui::TuiEvent;
impl App {
pub(super) fn transcript_link_at(&self, mouse: MouseEvent) -> Option<String> {
pub(super) fn transcript_link_at(&self, mouse: MouseEvent) -> Option<ReaderLink> {
if !mouse.modifiers.is_empty()
&& !mouse
.modifiers
@@ -44,7 +46,7 @@ impl App {
} else {
&self.transcript_view
};
view.link_at(mouse.column, mouse.row)
view.reader_link_at(mouse.column, mouse.row)
}
pub(super) fn handle_passive_transcript_event(
@@ -57,6 +59,7 @@ impl App {
return false;
};
let view = &mut companion.view;
view.agent_links = self.transcript_view.agent_links;
view.mouse_scroll_speed = self.transcript_view.mouse_scroll_speed;
view.copy_on_select = self.transcript_view.copy_on_select;
view.copy_on_select_clear_selection = self.transcript_view.copy_on_select_clear_selection;
@@ -80,6 +83,14 @@ impl App {
self.transcript_view.show_copy_feedback(&result, count);
} else if let ViewAction::OpenLink(url) = action {
self.open_url_in_browser(url);
} else if let ViewAction::OpenAgent(agent) = action
&& let Some(backend) = view.agent_links
{
self.app_event_tx.send(AppEvent::OpenSidebarAgent {
backend,
source: id,
agent,
});
}
tui.frame_requester().schedule_frame();
true
+10
View File
@@ -373,6 +373,7 @@ impl App {
id == panes.passive_thread && self.agent_navigation.is_parent_owned(id)
});
if let Some(companion) = self.side_companions.get_mut(&panes.passive_thread) {
companion.view.agent_links = self.transcript_view.agent_links;
companion.view.image_protocol = self.transcript_view.image_protocol;
panes.paint_companion(
companion,
@@ -1480,6 +1481,15 @@ impl App {
}
} else if let ViewAction::OpenLink(url) = action {
self.open_url_in_browser(url);
} else if let ViewAction::OpenAgent(agent) = action
&& let Some(backend) = self.transcript_view.agent_links
&& let Some(source) = self.current_displayed_thread_id()
{
self.app_event_tx.send(AppEvent::OpenSidebarAgent {
backend,
source,
agent,
});
} else if let ViewAction::OpenDocument(link) = action
&& let Some(source) = self.current_displayed_thread_id()
{
+1
View File
@@ -419,6 +419,7 @@ impl App {
*app_event_rx = rx;
for pane in self.sidebars.values_mut() {
pane.focus_document_request = None;
pane.agents.pending_link = None;
for doc in pane.documents.values_mut() {
doc.connection_replaced();
}
+4 -1
View File
@@ -692,6 +692,9 @@ impl App {
if !self.can_select_thread() {
return Ok(());
}
if let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent()) {
pane.agents.pending_link = None;
}
if self.active_thread_id == Some(thread_id) {
// Detach the cached receiver before a successful attachment replaces its channel.
self.store_active_thread_receiver().await;
@@ -1829,7 +1832,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);
self.confirm_sidebar_agent(primary_thread_id, thread.thread_id);
let agent_path = thread.agent_path;
let has_live_channel = self
.thread_event_channels
+3
View File
@@ -916,6 +916,9 @@ impl App {
}
fn focus_current_parent_view(&mut self, tui: &mut tui::Tui) {
if let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent()) {
pane.agents.pending_link = None;
}
self.cancel_transcript_browsing(tui);
clear_transcript_interaction(&mut self.transcript_view, &self.transcript_cells);
self.cancel_pending_key_chord();
+4 -1
View File
@@ -16,6 +16,7 @@ use crate::sidebar_chooser::ChatTabs;
use crate::sidebar_chooser::ChooserScroll;
use crate::sidebar_chooser::Discovery;
use crate::sidebar_tab_strip::SidebarTab;
use crate::terminal_hyperlinks::ReaderLink;
use crate::tui::Tui;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadItemPayload;
@@ -116,7 +117,7 @@ pub(super) struct SidebarPane {
}
impl SidebarPane {
pub(super) fn visible_link_at(&self, column: u16, row: u16) -> Option<String> {
pub(super) fn visible_link_at(&self, column: u16, row: u16) -> Option<ReaderLink> {
let SidebarContent::Document(id) = self.visible_content()? else {
return None;
};
@@ -160,6 +161,7 @@ impl SidebarPane {
self.cancel_hidden_document_primary(/*visible*/ false);
}
self.focus_document_request = None;
self.agents.pending_link = None;
if self.content != content {
self.showing_file_path = false;
}
@@ -492,6 +494,7 @@ impl SidebarPane {
pub(super) fn hide(&mut self) {
self.cancel_hidden_document_primary(/*visible*/ false);
self.focus_document_request = None;
self.agents.pending_link = None;
self.opening = None;
self.showing_file_path = false;
if let Some(files) = &mut self.files {
@@ -5,6 +5,7 @@ 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 crossterm::event::MouseEventKind;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::collections::HashSet;
@@ -272,14 +273,17 @@ async fn active_discovery_supersedes_restored_completion() -> color_eyre::Result
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!(
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(),
}),
)
.is_none()
);
assert_eq!(
rows(&app),
@@ -296,8 +300,6 @@ async fn active_discovery_supersedes_restored_completion() -> color_eyre::Result
#[tokio::test]
async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_eyre::Result<()> {
use crate::app::side_focus::SidebarTarget;
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;
@@ -307,8 +309,9 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use crossterm::event::MouseButton;
use crossterm::event::MouseEventKind;
use crossterm::event::MouseEvent;
use ratatui::layout::Size;
let (mut app, mut rx, _ops) = Box::pin(make_test_app_with_channels()).await;
@@ -326,37 +329,44 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
)
.expect("seed test rollout"),
)?;
let child = ThreadId::from_string(
&app_test_support::create_fake_parented_rollout_with_source(
config.codex_home.as_path(),
"2025-01-05T12-00-01",
"2025-01-05T12:00:01Z",
"Review result",
Some(config.model_provider_id.as_str()),
/*git_info*/ None,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: root,
depth: 1,
agent_path: Some("/root/reviewer".parse().expect("agent path")),
agent_nickname: Some("Reviewer".into()),
agent_role: None,
}),
root.into(),
root,
)
.expect("seed test rollout"),
let seed_agent =
|parent, second: u8, path: &str, reply: &str| -> color_eyre::Result<ThreadId> {
let timestamp = format!("2025-01-05T12-00-{second:02}");
let id = app_test_support::create_fake_parented_rollout_with_source(
config.codex_home.as_path(),
&timestamp,
&format!("2025-01-05T12:00:{second:02}Z"),
reply,
Some(config.model_provider_id.as_str()),
/*git_info*/ None,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: parent,
depth: if parent == root { 1 } else { 2 },
agent_path: Some(path.parse().expect("agent path")),
agent_nickname: Some(path.rsplit('/').next().expect("agent name").into()),
agent_role: None,
}),
root.into(),
parent,
)
.expect("seed agent rollout");
let rollout_path =
app_test_support::rollout_path(config.codex_home.as_path(), &timestamp, &id);
let rollout = std::fs::read_to_string(&rollout_path)?;
let (metadata, messages) = rollout.split_once('\n').expect("seeded child history");
let mut metadata: serde_json::Value = serde_json::from_str(metadata)?;
metadata["payload"]["multi_agent_version"] =
serde_json::to_value(codex_protocol::protocol::MultiAgentVersion::V2)?;
std::fs::write(rollout_path, format!("{metadata}\n{messages}"))?;
Ok(ThreadId::from_string(&id)?)
};
let child = seed_agent(root, /*second*/ 1, "/root/reviewer", "Review result")?;
let nested = seed_agent(
child,
/*second*/ 2,
"/root/reviewer/helper",
"Nested review result",
)?;
let path = app_test_support::rollout_path(
config.codex_home.as_path(),
"2025-01-05T12-00-01",
&child.to_string(),
);
let rollout = std::fs::read_to_string(&path)?;
let (metadata, messages) = rollout.split_once('\n').expect("seeded child history");
let mut metadata: serde_json::Value = serde_json::from_str(metadata)?;
metadata["payload"]["multi_agent_version"] =
serde_json::to_value(codex_protocol::protocol::MultiAgentVersion::V2)?;
std::fs::write(path, format!("{metadata}\n{messages}"))?;
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&config)).await?;
let started = Box::pin(server.resume_thread(
@@ -368,9 +378,11 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
.await?;
app.enqueue_primary_thread_session(started.session, started.turns)
.await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
let mut tui = crate::tui::test_support::make_test_tui_with_size(Size::new(
/*width*/ 140, /*height*/ 20,
))?;
tui.set_owned_screen(/*owned*/ true)?;
// Wait for the real app-server to discover the saved child before opening its row.
// Hold the actual discovery response so the first click races it deterministically.
let discovery = tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
let event = rx.recv().await.expect("app event channel");
@@ -384,21 +396,83 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
}
})
.await??;
Box::pin(app.handle_event(&mut tui, &mut server, discovery)).await?;
let activity = ThreadItemPayload::SubAgentActivity {
id: "started".into(),
agent_thread_id: child.to_string(),
kind: SubAgentActivityKind::Started,
agent_path: "/root/reviewer".into(),
model: None,
reasoning_effort: None,
};
let cell = crate::multi_agents::sub_agent_activity_history_cell(&activity).unwrap();
use crate::history_cell::HistoryCell;
let lines = cell.display_hyperlink_lines(/*width*/ 80);
let link = &lines[0].hyperlinks[0];
assert_eq!(link.terminal_destination(), None);
let agent = link.agent_id().unwrap();
let backend = server.backend_id();
for (source, target) in [(ThreadId::new(), agent), (root, ThreadId::new())] {
Box::pin(app.handle_event(
&mut tui,
&mut server,
crate::app_event::AppEvent::OpenSidebarAgent {
backend,
source,
agent: target,
},
))
.await?;
assert_eq!(app.current_displayed_thread_id(), Some(root));
}
// A thread ID recovered from replay is a candidate, even if it was inherited from a fork.
let inherited = ThreadId::new();
assert!(app.register_sidebar_agent(root, inherited));
Box::pin(app.handle_event(
&mut tui,
&mut server,
crate::app_event::AppEvent::OpenSidebarAgent {
backend,
source: root,
agent: inherited,
},
))
.await?;
assert_eq!(app.current_displayed_thread_id(), Some(root));
let pane = app.sidebar_mut();
assert_eq!(
pane.agents.pending_link.as_ref().map(|link| link.agent),
Some(inherited)
);
pane.show(
crate::app::sidebar::SidebarContent::Chooser,
crate::app::sidebar::PaneFocus::Main,
);
assert!(pane.agents.pending_link.is_none());
// Use the same activity cell as replay and click the link in the parent transcript.
app.transcript_view.agent_links = Some(backend);
app.insert_history_cell(&mut tui, Box::new(cell));
let screen = side_frame(&mut app, &mut tui, Size::new(140, 20))?;
let (row, column) = screen
.lines()
.enumerate()
.find_map(|(row, line)| {
let offset = line.find("/root/reviewer")?;
Some((row as u16, line[..offset].chars().count() as u16))
})
.expect("visible subagent link");
for kind in [
MouseEventKind::Down(MouseButton::Left),
MouseEventKind::Up(MouseButton::Left),
] {
let click = crate::app::owned_transcript::tests::mouse(kind, column, row);
Box::pin(app.handle_tui_event(&mut tui, &mut server, click)).await?;
}
while let Ok(event) = rx.try_recv() {
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
}
app.sidebar_mut()
.show(SidebarContent::Chooser, PaneFocus::Sidebar);
let screen = side_frame(&mut app, &mut tui, Size::new(140, 20))?;
assert!(screen.contains("Subagents 1"), "{screen}");
let pane = app.sidebar_mut();
pane.choice = pane
.chat_tabs()
.agent_index(child)
.expect("child agent row");
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into())))
.await?;
assert_eq!(app.current_displayed_thread_id(), Some(root));
Box::pin(app.handle_event(&mut tui, &mut server, discovery)).await?;
while let Ok(event) = rx.try_recv() {
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
}
@@ -453,7 +527,7 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
assert_eq!(app.current_displayed_thread_id(), Some(root));
assert_eq!(app.docked_agent(), None);
let screen = side_frame(&mut app, &mut tui, Size::new(140, 20))?;
assert!(screen.contains("Subagents 1"), "{screen}");
assert!(screen.contains("Subagents 2"), "{screen}");
let pane = app.sidebar().unwrap();
assert!(
!pane
@@ -472,7 +546,51 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
while let Ok(event) = rx.try_recv() {
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
}
side_frame(&mut app, &mut tui, Size::new(140, 20))?;
let cell = crate::multi_agents::sub_agent_activity_history_cell(
&ThreadItemPayload::SubAgentActivity {
id: "nested-started".into(),
agent_thread_id: nested.to_string(),
kind: SubAgentActivityKind::Started,
agent_path: "/root/reviewer/helper".into(),
model: None,
reasoning_effort: None,
},
)
.unwrap();
app.insert_history_cell(&mut tui, Box::new(cell));
Box::pin(app.select_agent_thread(&mut tui, &mut server, root)).await?;
while let Ok(event) = rx.try_recv() {
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
}
let screen = side_frame(&mut app, &mut tui, Size::new(140, 20))?;
let (row, column) = screen
.lines()
.enumerate()
.find_map(|(row, line)| {
let offset = line.find("/root/reviewer/helper")?;
Some((row as u16, line[..offset].chars().count() as u16))
})
.expect("visible link in passive child");
let click = MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column,
row,
modifiers: KeyModifiers::CONTROL,
};
assert_eq!(app.current_displayed_thread_id(), Some(root));
assert_eq!(app.sidebar_agent_link_root(&tui, child), Some(root));
assert_eq!(
app.transcript_link_at(click),
Some(crate::terminal_hyperlinks::ReaderLink::Agent(nested))
);
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Mouse(click))).await?;
while let Ok(event) = rx.try_recv() {
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
}
assert_eq!(app.current_displayed_thread_id(), Some(nested));
assert_eq!(app.docked_agent(), Some((root, nested)));
let screen = side_frame(&mut app, &mut tui, Size::new(140, 20))?;
assert!(screen.contains("Nested review result"), "{screen}");
let close = app
.conversation_frame
.sidebar_targets
+6 -3
View File
@@ -15,6 +15,7 @@ use crate::sidebar_image::DocumentContent;
use crate::sidebar_image::SidebarImage;
use crate::sidebar_tab_strip::SidebarTab;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::ReaderLink;
use crate::terminal_hyperlinks::visible_lines;
use crate::transcript_view::TranscriptView;
use crate::transcript_view::ViewAction;
@@ -94,9 +95,9 @@ enum State {
}
impl Document {
pub(super) fn link_at(&self, column: u16, row: u16) -> Option<String> {
pub(super) fn link_at(&self, column: u16, row: u16) -> Option<ReaderLink> {
match &self.state {
State::Ready { view, .. } if !view.is_select_mode() => view.link_at(column, row),
State::Ready { view, .. } if !view.is_select_mode() => view.reader_link_at(column, row),
_ => None,
}
}
@@ -452,7 +453,9 @@ impl App {
let backend_id = resolver.backend_id();
let tx = self.app_event_tx.clone();
let request = uuid::Uuid::new_v4();
self.sidebar_mut().focus_document_request = Some(request);
let pane = self.sidebar_mut();
pane.agents.pending_link = None;
pane.focus_document_request = Some(request);
tokio::spawn(async move {
let resolved = resolver
.resolve_thread_file(source, &path)
+3 -1
View File
@@ -129,7 +129,9 @@ impl App {
if !self.can_select_thread() {
return Ok(());
}
self.sidebar_mut().focus_document_request = None;
let pane = self.sidebar_mut();
pane.agents.pending_link = None;
pane.focus_document_request = None;
let child = target.child;
let flight = self.saved_openings.active.get(&target.key());
let state = if let Some(flight) = flight
+61 -2
View File
@@ -2,6 +2,7 @@
use super::sidebar::PaneFocus;
use super::sidebar::SidebarContent;
use super::*;
use crate::backend_id::BackendId;
use crate::keymap::ListAction;
use crate::sidebar_chooser::AgentRow;
use codex_app_server_protocol::CollabAgentStatus;
@@ -18,9 +19,19 @@ pub(super) enum OutcomeReplay {
Reconnect,
}
pub(super) struct PendingLink {
pub(super) backend: BackendId,
pub(super) source: ThreadId,
pub(super) agent: ThreadId,
}
#[derive(Default)]
pub(super) struct Overview {
members: HashSet<ThreadId>,
// Replay can contain activity inherited from another thread. Only backend ancestry
// can authorize navigation from a transcript link.
confirmed_members: HashSet<ThreadId>,
pub(super) pending_link: Option<PendingLink>,
states: HashMap<ThreadId, State>,
restored_outcomes: HashSet<ThreadId>,
pub(super) rows: Vec<AgentRow>,
@@ -139,7 +150,10 @@ impl App {
let Some(parent) = self.primary_thread_id else {
return Ok(());
};
if !self.is_sidebar_agent(agent) || self.sidebar_parent() != Some(parent) {
if self.chat_widget.has_misalignment_policy_violation()
|| !self.is_confirmed_sidebar_agent(parent, agent)
|| self.sidebar_parent() != Some(parent)
{
return Ok(());
}
let pane = self.sidebars.entry(Some(parent)).or_default();
@@ -164,6 +178,51 @@ impl App {
result
}
pub(super) fn sidebar_agent_link_root(
&self,
tui: &tui::Tui,
source: ThreadId,
) -> Option<ThreadId> {
let root = self.primary_thread_id?;
if self.sidebar_parent() != Some(root) || !self.conversation_focus_available(tui) {
return None;
}
let docked = self.docked_agent();
if source != root && docked != Some((root, source)) {
return None;
}
let screen = tui.terminal.last_known_screen_size.into();
(self.current_displayed_thread_id() == Some(source)
|| (docked.is_some()
&& super::side_pane::layout(self, tui, screen)
.is_some_and(|layout| layout.passive_thread == source)))
.then_some(root)
}
pub(super) fn is_confirmed_sidebar_agent(&self, root: ThreadId, agent: ThreadId) -> bool {
self.sidebars
.get(&Some(root))
.is_some_and(|pane| pane.agents.confirmed_members.contains(&agent))
}
pub(super) fn confirm_sidebar_agent(&mut self, parent: ThreadId, agent: ThreadId) -> bool {
let Some(root) = self.primary_thread_id else {
return false;
};
if (parent == root || self.is_confirmed_sidebar_agent(root, parent))
&& self.register_sidebar_agent(parent, agent)
{
self.sidebars
.entry(Some(root))
.or_default()
.agents
.confirmed_members
.insert(agent);
return true;
}
false
}
pub(super) fn is_sidebar_agent(&self, id: ThreadId) -> bool {
self.primary_thread_id
.and_then(|root| self.sidebars.get(&Some(root)))
@@ -252,7 +311,7 @@ impl App {
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.confirm_sidebar_agent(parent, child)
{
self.upsert_agent_picker_thread(
child,
@@ -14,7 +14,7 @@ expression: "screen.replace(&child.to_string(), \"[agent id]\")"
/model - choose what model and reasoning effort to use │
/review - review any changes and find issues │• Agent thread [agent id] could
│not be resumed live. Replaying saved transcript.
│
• Started `/root/reviewer` │
│
│
│
+11 -8
View File
@@ -2398,14 +2398,17 @@ async fn archived_untracked_threads_do_not_appear_in_agent_picker() -> Result<()
.agent_navigation
.begin_picker_refresh(primary_thread_id)
.expect("picker refresh after missed archive");
app.apply_agent_picker_thread_refresh(
&app_server,
primary_thread_id,
request_id,
Ok(crate::app_event::AgentPickerThreadRefresh {
threads: Vec::new(),
archived_thread_ids: std::collections::HashSet::from([archived_thread_id]),
}),
assert!(
app.apply_agent_picker_thread_refresh(
&app_server,
primary_thread_id,
request_id,
Ok(crate::app_event::AgentPickerThreadRefresh {
threads: Vec::new(),
archived_thread_ids: std::collections::HashSet::from([archived_thread_id]),
}),
)
.is_none()
);
assert_eq!(
app.thread_event_channels[&archived_thread_id].attachment(),
+5
View File
@@ -536,6 +536,11 @@ pub(crate) enum AppEvent {
request: uuid::Uuid,
},
StartQueuedSavedChat,
OpenSidebarAgent {
backend: crate::backend_id::BackendId,
source: ThreadId,
agent: ThreadId,
},
OpenSidebarDocument {
backend_id: crate::backend_id::BackendId,
source: ThreadId,
+25 -3
View File
@@ -36,12 +36,12 @@ impl HistoryCell for PlainHistoryCell {
}
#[derive(Debug)]
pub(crate) struct LabeledToolCell {
cell: PlainHistoryCell,
pub(crate) struct LabeledToolCell<C = PlainHistoryCell> {
cell: C,
label: String,
}
impl HistoryCell for LabeledToolCell {
impl<C: HistoryCell> HistoryCell for LabeledToolCell<C> {
fn tool_call_labels(&self) -> Vec<String> {
vec![self.label.clone()]
}
@@ -50,6 +50,14 @@ impl HistoryCell for LabeledToolCell {
self.cell.display_lines(width)
}
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
self.cell.display_hyperlink_lines(width)
}
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
self.cell.transcript_hyperlink_lines(width)
}
fn raw_lines(&self) -> Vec<Line<'static>> {
self.cell.raw_lines()
}
@@ -70,6 +78,20 @@ impl WebHyperlinkHistoryCell {
pub(crate) fn new_hyperlink_lines(lines: Vec<HyperlinkLine>) -> Self {
Self { lines }
}
pub(crate) fn with_tool_header(self, count: usize) -> LabeledToolCell<Self> {
let label = self
.lines
.iter()
.take(count)
.map(|line| &line.line)
.join(" · ");
self.with_tool_label(label)
}
pub(crate) fn with_tool_label(self, label: String) -> LabeledToolCell<Self> {
LabeledToolCell { cell: self, label }
}
}
impl HistoryCell for WebHyperlinkHistoryCell {
+81 -77
View File
@@ -5,9 +5,11 @@
//! deciding which thread becomes active or when a thread closes, stays in [`crate::app::App`].
use crate::history_cell::LabeledToolCell;
use crate::history_cell::PlainHistoryCell;
use crate::render::line_utils::prefix_lines;
use crate::history_cell::WebHyperlinkHistoryCell;
use crate::style::accent_color;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::TerminalHyperlink;
use crate::terminal_hyperlinks::prefix_hyperlink_lines;
use crate::text_formatting::truncate_text;
use codex_app_server_protocol::CollabAgentState;
use codex_app_server_protocol::CollabAgentStatus;
@@ -206,7 +208,7 @@ pub(crate) fn tool_call_history_cell(
item: &ThreadItemPayload,
cached_spawn_request: Option<&SpawnRequestSummary>,
mut agent_metadata: impl FnMut(ThreadId) -> AgentMetadata,
) -> Option<LabeledToolCell> {
) -> Option<LabeledToolCell<WebHyperlinkHistoryCell>> {
let ThreadItemPayload::CollabAgentToolCall {
tool,
status,
@@ -317,30 +319,38 @@ pub(crate) fn sub_agent_activity_display(
pub(crate) fn sub_agent_activity_history_cell(
item: &ThreadItemPayload,
) -> Option<PlainHistoryCell> {
) -> Option<WebHyperlinkHistoryCell> {
let ThreadItemPayload::SubAgentActivity {
kind, agent_path, ..
kind,
agent_path,
agent_thread_id,
..
} = item
else {
return None;
};
Some(collab_event(
sub_agent_activity_title(*kind, agent_path),
Vec::new(),
))
let prefix = match kind {
SubAgentActivityKind::Started => "Started",
SubAgentActivityKind::Interacted => "Interacted with",
SubAgentActivityKind::Interrupted => "Interrupted",
SubAgentActivityKind::Completed => "Completed",
};
let mut title = title_text(format!("{prefix} "));
push_agent_label(
&mut title,
format!("`{agent_path}`").fg(accent_color()),
parse_thread_id(agent_thread_id),
);
Some(collab_event(title, Vec::new()))
}
fn sub_agent_activity_title(kind: SubAgentActivityKind, agent_path: &str) -> Line<'static> {
let (prefix, path) = match kind {
SubAgentActivityKind::Started => ("Started ", agent_path),
SubAgentActivityKind::Interacted => ("Interacted with ", agent_path),
SubAgentActivityKind::Interrupted => ("Interrupted ", agent_path),
SubAgentActivityKind::Completed => ("Completed ", agent_path),
};
title_spans_line(vec![
Span::from(prefix).bold(),
Span::from(format!("`{path}`")).fg(accent_color()),
])
fn push_agent_label(line: &mut HyperlinkLine, span: Span<'static>, id: Option<ThreadId>) {
let start = line.width();
line.line.push_span(span);
if let Some(id) = id {
line.hyperlinks
.push(TerminalHyperlink::agent(start..line.width(), id));
}
}
fn spawn_end(
@@ -348,7 +358,7 @@ fn spawn_end(
prompt: &str,
spawn_request: Option<&SpawnRequestSummary>,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
let title = match new_thread_id {
Some(thread_id) => title_with_agent(
"Spawned",
@@ -360,7 +370,7 @@ fn spawn_end(
let mut details = Vec::new();
if let Some(line) = prompt_line(prompt) {
details.push(line);
details.push(line.into());
}
collab_event(title, details)
}
@@ -369,7 +379,7 @@ fn interaction_end(
receiver_thread_id: ThreadId,
prompt: &str,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
let title = title_with_agent(
"Sent input to",
agent_label(receiver_thread_id, &agent_metadata(receiver_thread_id)),
@@ -378,7 +388,7 @@ fn interaction_end(
let mut details = Vec::new();
if let Some(line) = prompt_line(prompt) {
details.push(line);
details.push(line.into());
}
collab_event(title, details)
}
@@ -386,7 +396,7 @@ fn interaction_end(
fn waiting_begin(
receiver_thread_ids: &[String],
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
let receiver_agents = receiver_thread_ids
.iter()
.filter_map(|thread_id| parse_thread_id(thread_id))
@@ -419,7 +429,7 @@ fn waiting_end(
receiver_thread_ids: &[String],
agents_states: &std::collections::HashMap<String, CollabAgentState>,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
let details = wait_complete_lines(receiver_thread_ids, agents_states, agent_metadata);
collab_event(title_text("Finished waiting"), details)
}
@@ -427,7 +437,7 @@ fn waiting_end(
fn close_end(
receiver_thread_id: ThreadId,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
collab_event(
title_with_agent(
"Closed",
@@ -441,7 +451,7 @@ fn close_end(
fn resume_begin(
receiver_thread_id: ThreadId,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
collab_event(
title_with_agent(
"Resuming",
@@ -457,45 +467,38 @@ fn resume_end(
status: Option<&CollabAgentState>,
fallback_error: &str,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> PlainHistoryCell {
) -> WebHyperlinkHistoryCell {
collab_event(
title_with_agent(
"Resumed",
agent_label(receiver_thread_id, &agent_metadata(receiver_thread_id)),
/*spawn_request*/ None,
),
vec![status_summary_line(status, fallback_error)],
vec![status_summary_line(status, fallback_error).into()],
)
}
fn collab_event(title: Line<'static>, details: Vec<Line<'static>>) -> PlainHistoryCell {
let mut lines: Vec<Line<'static>> = vec![title];
fn collab_event(title: HyperlinkLine, details: Vec<HyperlinkLine>) -> WebHyperlinkHistoryCell {
let mut lines = vec![title];
if !details.is_empty() {
lines.extend(prefix_lines(details, " └ ".dim(), " ".into()));
lines.extend(prefix_hyperlink_lines(details, " └ ".dim(), " ".into()));
}
PlainHistoryCell::new(lines)
WebHyperlinkHistoryCell::new_hyperlink_lines(lines)
}
fn title_text(title: impl Into<String>) -> Line<'static> {
title_spans_line(vec![Span::from(title.into()).bold()])
fn title_text(title: impl Into<String>) -> HyperlinkLine {
Line::from(vec!["• ".dim(), title.into().bold()]).into()
}
fn title_with_agent(
prefix: &str,
agent: AgentLabel<'_>,
spawn_request: Option<&SpawnRequestSummary>,
) -> Line<'static> {
let mut spans = vec![Span::from(format!("{prefix} ")).bold()];
spans.extend(agent_label_spans(agent));
spans.extend(spawn_request_spans(spawn_request));
title_spans_line(spans)
}
fn title_spans_line(mut spans: Vec<Span<'static>>) -> Line<'static> {
let mut title = Vec::with_capacity(spans.len() + 1);
title.push(Span::from("• ").dim());
title.append(&mut spans);
title.into()
) -> HyperlinkLine {
let mut title = title_text(format!("{prefix} "));
append_agent(&mut title, agent);
title.line.spans.extend(spawn_request_spans(spawn_request));
title
}
fn parse_thread_id(thread_id: &str) -> Option<ThreadId> {
@@ -510,32 +513,26 @@ fn agent_label(thread_id: ThreadId, metadata: &AgentMetadata) -> AgentLabel<'_>
}
}
fn agent_label_line(agent: AgentLabel<'_>) -> Line<'static> {
agent_label_spans(agent).into()
fn agent_label_line(agent: AgentLabel<'_>) -> HyperlinkLine {
let mut line = HyperlinkLine::new(Line::default());
append_agent(&mut line, agent);
line
}
fn agent_label_spans(agent: AgentLabel<'_>) -> Vec<Span<'static>> {
let mut spans = Vec::new();
let nickname = agent
.nickname
.map(str::trim)
.filter(|nickname| !nickname.is_empty());
let role = agent.role.map(str::trim).filter(|role| !role.is_empty());
if let Some(nickname) = nickname {
spans.push(Span::from(nickname.to_string()).fg(accent_color()).bold());
} else if let Some(thread_id) = agent.thread_id {
spans.push(Span::from(thread_id.to_string()).fg(accent_color()));
fn append_agent(line: &mut HyperlinkLine, agent: AgentLabel<'_>) {
let nickname = agent.nickname.map(str::trim).filter(|n| !n.is_empty());
let name = if let Some(nickname) = nickname {
nickname.to_string().bold()
} else if let Some(id) = agent.thread_id {
Span::from(id.to_string())
} else {
spans.push(Span::from("agent").fg(accent_color()));
Span::from("agent")
};
push_agent_label(line, name.fg(accent_color()), agent.thread_id);
if let Some(role) = agent.role.map(str::trim).filter(|r| !r.is_empty()) {
line.line.push_span(" ".dim());
line.line.push_span(format!("[{role}]"));
}
if let Some(role) = role {
spans.push(Span::from(" ").dim());
spans.push(Span::from(format!("[{role}]")));
}
spans
}
fn spawn_request_spans(spawn_request: Option<&SpawnRequestSummary>) -> Vec<Span<'static>> {
@@ -573,7 +570,7 @@ fn wait_complete_lines(
receiver_thread_ids: &[String],
agents_states: &std::collections::HashMap<String, CollabAgentState>,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> Vec<Line<'static>> {
) -> Vec<HyperlinkLine> {
let mut seen = HashSet::new();
let mut entries = receiver_thread_ids
.iter()
@@ -597,15 +594,15 @@ fn wait_complete_lines(
entries.extend(extras);
if entries.is_empty() {
vec![Line::from(Span::from("No agents completed yet"))]
vec!["No agents completed yet".into()]
} else {
entries
.into_iter()
.map(|(thread_id, metadata, status)| {
let mut spans = agent_label_spans(agent_label(thread_id, &metadata));
spans.push(Span::from(": ").dim());
spans.extend(status_summary_spans(status));
spans.into()
let mut line = agent_label_line(agent_label(thread_id, &metadata));
line.line.push_span(": ".dim());
line.line.spans.extend(status_summary_spans(status));
line
})
.collect()
}
@@ -817,6 +814,13 @@ mod tests {
)
.expect("wait end item renders");
let targets: Vec<_> = finished
.transcript_hyperlink_lines(/*width*/ 200)
.into_iter()
.flat_map(|row| row.hyperlinks)
.map(|link| (link.agent_id(), link.terminal_destination()))
.collect();
assert_eq!(targets, vec![(Some(robie_id), None), (Some(bob_id), None)]);
let close = tool_call_history_cell(
&ThreadItemPayload::CollabAgentToolCall {
id: "call-close".to_string(),
@@ -946,7 +950,7 @@ mod tests {
fn resume_cell(
status: CollabAgentToolCallStatus,
agent_status: CollabAgentStatus,
) -> LabeledToolCell {
) -> LabeledToolCell<WebHyperlinkHistoryCell> {
let sender_thread_id = ThreadId::from_string("00000000-0000-0000-0000-000000000001")
.expect("valid sender thread id");
let robie_id = ThreadId::from_string("00000000-0000-0000-0000-000000000002")
+22 -2
View File
@@ -74,6 +74,7 @@ impl std::fmt::Debug for TerminalHyperlink {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DestinationKind {
Agent(codex_protocol::ThreadId),
Web,
/// A generated visualization, validated workspace artifact, or locally viewed image.
TrustedFile,
@@ -83,13 +84,16 @@ enum DestinationKind {
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum ReaderLink {
Agent(codex_protocol::ThreadId),
External(String),
Document(FileLink),
}
#[cfg(test)]
impl ReaderLink {
pub(crate) fn into_destination(self) -> String {
match self {
Self::Agent(id) => format!("codex-agent:{id}"),
Self::External(url) => url,
Self::Document(link) => link.path,
}
@@ -202,6 +206,22 @@ impl TerminalHyperlink {
}
}
pub(crate) fn agent(columns: Range<usize>, id: codex_protocol::ThreadId) -> Self {
Self {
columns,
destination: id.to_string(),
destination_kind: DestinationKind::Agent(id),
markdown_source: None,
}
}
pub(crate) fn agent_id(&self) -> Option<codex_protocol::ThreadId> {
match self.destination_kind {
DestinationKind::Agent(id) => Some(id),
_ => None,
}
}
pub(crate) fn document(columns: Range<usize>, link: FileLink) -> Self {
Self {
columns,
@@ -237,7 +257,7 @@ impl TerminalHyperlink {
pub(crate) fn sidebar_destination(&self) -> Option<ReaderLink> {
match self.destination_kind {
DestinationKind::TrustedFile => None,
DestinationKind::TrustedFile | DestinationKind::Agent(_) => None,
DestinationKind::Document(_) | DestinationKind::Web => {
self.reader_destination(/*documents*/ true)
}
@@ -246,7 +266,7 @@ impl TerminalHyperlink {
pub(crate) fn terminal_destination(&self) -> Option<String> {
match self.destination_kind {
DestinationKind::Document(_) => None,
DestinationKind::Document(_) | DestinationKind::Agent(_) => None,
DestinationKind::Web => web_destination(&self.destination),
DestinationKind::TrustedFile => trusted_file_destination(&self.destination),
}
+5
View File
@@ -94,6 +94,7 @@ struct VisibleRow {
/// Shared scrolling and interaction state for compact and detailed transcript presentations.
pub(crate) struct TranscriptView {
pub(crate) image_protocol: Option<crate::pets::ImageProtocol>,
pub(crate) agent_links: Option<crate::backend_id::BackendId>,
pub(crate) document_links: bool,
pub(crate) mouse_scroll_speed: f64,
pending_mouse_scroll: f64,
@@ -137,6 +138,7 @@ impl Default for TranscriptView {
fn default() -> Self {
Self {
image_protocol: None,
agent_links: None,
document_links: false,
mouse_scroll_speed: 1.0,
pending_mouse_scroll: 0.0,
@@ -325,6 +327,9 @@ impl TranscriptView {
};
let row_area = Rect::new(area.x, y, area.width, /*height*/ 1);
layout.render(row_area, buf, row);
if self.agent_links.is_some() {
layout.underline_agent_links(row_area, buf, row);
}
self.render_disclosure(&activity_ids, &layout, row, row_area, buf);
if self.highlight == Some(index) && self.selection.is_none() && !self.search.is_active()
{
+11 -2
View File
@@ -28,6 +28,7 @@ pub(crate) enum ViewAction {
CopyOnSelect(String),
PrimarySelection(String),
CopyAndFollow(String),
OpenAgent(ThreadId),
OpenLink(String),
OpenDocument(FileLink),
}
@@ -35,6 +36,7 @@ pub(crate) enum ViewAction {
impl From<ReaderLink> for ViewAction {
fn from(link: ReaderLink) -> Self {
match link {
ReaderLink::Agent(id) => Self::OpenAgent(id),
ReaderLink::External(url) => Self::OpenLink(url),
ReaderLink::Document(link) => Self::OpenDocument(link),
}
@@ -118,19 +120,26 @@ impl TranscriptView {
| ViewAction::ExitSelectMode
| ViewAction::Copy(_)
| ViewAction::CopyAndFollow(_)
| ViewAction::OpenAgent(_)
| ViewAction::OpenDocument(_)
| ViewAction::OpenLink(_) => SelectionCopy::EXPLICIT,
}
}
/// Resolve links in the last rendered transcript, sharing geometry with click activation.
#[cfg(test)]
pub(crate) fn link_at(&self, column: u16, row: u16) -> Option<String> {
self.reader_link_at(column, row)
.map(ReaderLink::into_destination)
}
fn reader_link_at(&self, column: u16, row: u16) -> Option<ReaderLink> {
/// Resolve links in the last rendered transcript, sharing geometry with click activation.
pub(crate) fn reader_link_at(&self, column: u16, row: u16) -> Option<ReaderLink> {
let (_, link) = self.raw_link_at(ScreenPosition::new(column, row))?;
if self.agent_links.is_some()
&& let Some(agent) = link.agent_id()
{
return Some(ReaderLink::Agent(agent));
}
link.reader_destination(self.document_links)
}
@@ -174,6 +174,55 @@ fn hover_links_match_wrapped_click_targets_and_refresh_after_scrolling() {
);
}
#[test]
fn agent_activity_underlines_the_full_wrapped_label() {
use codex_app_server_protocol::SubAgentActivityKind;
use codex_app_server_protocol::ThreadItemPayload;
use ratatui::style::Modifier;
let cell = crate::multi_agents::sub_agent_activity_history_cell(
&ThreadItemPayload::SubAgentActivity {
id: "spawn".into(),
kind: SubAgentActivityKind::Started,
agent_thread_id: codex_protocol::ThreadId::new().to_string(),
agent_path: "/root/reviewer/verify_the_sidebar_layout".into(),
model: None,
reasoning_effort: None,
},
)
.expect("agent activity");
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(cell)];
let mut view = TranscriptView {
agent_links: Some(crate::backend_id::BackendId::new()),
..Default::default()
};
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 22, /*height*/ 5,
);
let mut buffer = Buffer::empty(area);
view.render(area, &mut buffer, &cells);
let picture = buffer
.content
.chunks(usize::from(area.width))
.filter_map(|row| {
let text: String = row.iter().map(ratatui::buffer::Cell::symbol).collect();
let marks: String = row
.iter()
.map(|cell| {
if cell.modifier.contains(Modifier::UNDERLINED) {
'^'
} else {
' '
}
})
.collect();
(!text.trim().is_empty()).then(|| format!("{}\n{}", text.trim_end(), marks.trim_end()))
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(picture);
}
#[test]
fn workspace_file_links_show_the_title_with_subtle_hover_and_open_the_same_location() {
use crate::markdown_render::FileLink;
@@ -663,6 +663,7 @@ impl TranscriptView {
| ViewAction::CopyAndFollow(text) => text.as_str(),
ViewAction::Changed
| ViewAction::ExitSelectMode
| ViewAction::OpenAgent(_)
| ViewAction::OpenLink(_)
| ViewAction::OpenDocument(_) => {
return None;
@@ -0,0 +1,12 @@
---
source: tui/src/transcript_view/input_tests.rs
expression: picture
---
• Started `/root/
^^^^^^^
reviewer/
^^^^^^^^^
verify_the_sidebar_lay
^^^^^^^^^^^^^^^^^^^^^^
out`
^^^^
+21
View File
@@ -851,6 +851,27 @@ impl TextLayout {
}
}
pub(super) fn underline_agent_links(&self, area: Rect, buf: &mut Buffer, row: usize) {
let Some((inset, links)) = self.row_links(row) else {
return;
};
for link in links.iter().filter(|link| link.agent_id().is_some()) {
let columns = (inset + link.columns.start)
..(inset + link.columns.end).min(usize::from(area.width));
if !columns.is_empty() {
buf.set_style(
Rect::new(
area.x + columns.start as u16,
area.y,
columns.len() as u16,
1,
),
Style::default().underlined(),
);
}
}
}
pub(super) fn document_links(&self) -> Vec<(Range<usize>, ReaderLink)> {
let mut stops: Vec<(Range<usize>, ReaderLink)> = Vec::new();
let mut previous_source = None;
+5 -4
View File
@@ -18,13 +18,14 @@ pub(crate) fn record_frame_requests(
}
pub(crate) fn make_test_tui() -> io::Result<Tui> {
make_test_tui_with_size(Size::new(/*width*/ 80, /*height*/ 24))
}
pub(crate) fn make_test_tui_with_size(size: Size) -> io::Result<Tui> {
let backend = CrosstermBackend::new(stdout());
let terminal = Terminal::with_screen_size_and_cursor_position_for_test(
backend,
Size {
width: 80,
height: 24,
},
size,
Position { x: 0, y: 0 },
);
let stderr_guard = TerminalStderrGuard::install()?;