Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

agent_ui: Add in-thread search bar (#57231)

Dan Dascalescu10628c3d2caf
diff --git a/assets/keymaps/default-linux.json b/assets/keymaps/default-linux.json
index e8db12b6fbb..2220068078d 100644
--- a/assets/keymaps/default-linux.json
+++ b/assets/keymaps/default-linux.json
@@ -290,6 +290,29 @@
"ctrl-alt-down": "agent::ScrollOutputLineDown",
"ctrl-alt-shift-pageup": "agent::ScrollOutputToPreviousMessage",
"ctrl-alt-shift-pagedown": "agent::ScrollOutputToNextMessage",
+ "ctrl-f": "agent::ToggleSearch",
+ "f3": "agent::SelectNextThreadMatch",
+ "shift-f3": "agent::SelectPreviousThreadMatch",
+ "alt-c": "search::ToggleCaseSensitive",
+ "alt-w": "search::ToggleWholeWord",
+ "alt-r": "search::ToggleRegex",
+ },
+ },
+ {
+ "context": "AcpThreadSearchBar",
+ "use_key_equivalents": true,
+ "bindings": {
+ "escape": "agent::DismissThreadSearch",
+ "enter": "agent::SelectNextThreadMatch",
+ "shift-enter": "agent::SelectPreviousThreadMatch",
+ "ctrl-f": "search::FocusSearch",
+ },
+ },
+ {
+ "context": "AcpThreadSearchBar > Editor",
+ "use_key_equivalents": true,
+ "bindings": {
+ "shift-enter": "agent::SelectPreviousThreadMatch",
},
},
{
diff --git a/assets/keymaps/default-macos.json b/assets/keymaps/default-macos.json
index b9999625891..9310fce0725 100644
--- a/assets/keymaps/default-macos.json
+++ b/assets/keymaps/default-macos.json
@@ -334,6 +334,29 @@
"ctrl-alt-down": "agent::ScrollOutputLineDown",
"ctrl-alt-pageup": "agent::ScrollOutputToPreviousMessage",
"ctrl-alt-pagedown": "agent::ScrollOutputToNextMessage",
+ "cmd-f": "agent::ToggleSearch",
+ "cmd-g": "agent::SelectNextThreadMatch",
+ "cmd-shift-g": "agent::SelectPreviousThreadMatch",
+ "alt-cmd-c": "search::ToggleCaseSensitive",
+ "alt-cmd-w": "search::ToggleWholeWord",
+ "alt-cmd-x": "search::ToggleRegex",
+ },
+ },
+ {
+ "context": "AcpThreadSearchBar",
+ "use_key_equivalents": true,
+ "bindings": {
+ "escape": "agent::DismissThreadSearch",
+ "enter": "agent::SelectNextThreadMatch",
+ "shift-enter": "agent::SelectPreviousThreadMatch",
+ "cmd-f": "search::FocusSearch",
+ },
+ },
+ {
+ "context": "AcpThreadSearchBar > Editor",
+ "use_key_equivalents": true,
+ "bindings": {
+ "shift-enter": "agent::SelectPreviousThreadMatch",
},
},
{
diff --git a/assets/keymaps/default-windows.json b/assets/keymaps/default-windows.json
index a4d75c8da1d..1833efec322 100644
--- a/assets/keymaps/default-windows.json
+++ b/assets/keymaps/default-windows.json
@@ -291,6 +291,29 @@
"ctrl-alt-down": "agent::ScrollOutputLineDown",
"ctrl-alt-shift-pageup": "agent::ScrollOutputToPreviousMessage",
"ctrl-alt-shift-pagedown": "agent::ScrollOutputToNextMessage",
+ "ctrl-f": "agent::ToggleSearch",
+ "f3": "agent::SelectNextThreadMatch",
+ "shift-f3": "agent::SelectPreviousThreadMatch",
+ "alt-c": "search::ToggleCaseSensitive",
+ "alt-w": "search::ToggleWholeWord",
+ "alt-r": "search::ToggleRegex",
+ },
+ },
+ {
+ "context": "AcpThreadSearchBar",
+ "use_key_equivalents": true,
+ "bindings": {
+ "escape": "agent::DismissThreadSearch",
+ "enter": "agent::SelectNextThreadMatch",
+ "shift-enter": "agent::SelectPreviousThreadMatch",
+ "ctrl-f": "search::FocusSearch",
+ },
+ },
+ {
+ "context": "AcpThreadSearchBar > Editor",
+ "use_key_equivalents": true,
+ "bindings": {
+ "shift-enter": "agent::SelectPreviousThreadMatch",
},
},
{
diff --git a/assets/keymaps/linux/jetbrains.json b/assets/keymaps/linux/jetbrains.json
index 98d5cf93106..de4d538d40d 100644
--- a/assets/keymaps/linux/jetbrains.json
+++ b/assets/keymaps/linux/jetbrains.json
@@ -94,6 +94,12 @@
"shift-enter": "search::SelectPreviousMatch",
},
},
+ {
+ "context": "AcpThreadSearchBar > Editor",
+ "bindings": {
+ "shift-enter": "agent::SelectPreviousThreadMatch",
+ },
+ },
{
"context": "BufferSearchBar || ProjectSearchBar",
"bindings": {
diff --git a/assets/keymaps/macos/jetbrains.json b/assets/keymaps/macos/jetbrains.json
index 304ffb86e8c..291d7d5e7a8 100644
--- a/assets/keymaps/macos/jetbrains.json
+++ b/assets/keymaps/macos/jetbrains.json
@@ -93,6 +93,12 @@
"shift-enter": "search::SelectPreviousMatch",
},
},
+ {
+ "context": "AcpThreadSearchBar > Editor",
+ "bindings": {
+ "shift-enter": "agent::SelectPreviousThreadMatch",
+ },
+ },
{
"context": "BufferSearchBar || ProjectSearchBar",
"bindings": {
diff --git a/crates/agent_ui/Cargo.toml b/crates/agent_ui/Cargo.toml
index 0d7c076a1a5..48fee9ffa34 100644
--- a/crates/agent_ui/Cargo.toml
+++ b/crates/agent_ui/Cargo.toml
@@ -91,6 +91,7 @@ remote.workspace = true
remote_connection.workspace = true
rope.workspace = true
schemars.workspace = true
+search.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_json_lenient.workspace = true
diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rs
index 7ce480896ed..91379386052 100644
--- a/crates/agent_ui/src/agent_ui.rs
+++ b/crates/agent_ui/src/agent_ui.rs
@@ -290,6 +290,8 @@ actions!(
ScrollOutputToPreviousMessage,
/// Scroll the output to the next user message.
ScrollOutputToNextMessage,
+ /// Toggles in-thread search over the current agent thread's contents.
+ ToggleSearch,
/// Import agent threads from other Zed release channels (e.g. Preview, Nightly).
ImportThreadsFromOtherChannels,
/// Starts a new terminal thread.
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 2d8eabbee02..1654ff0d02f 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -47,7 +47,7 @@ use crate::message_editor::SessionCapabilities;
use crate::{AgentThreadSource, DEFAULT_THREAD_TITLE, resolve_agent_image};
use lru::LruCache;
use rope::Point;
-use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore, ThinkingBlockDisplay};
+use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -106,6 +106,7 @@ const TOKEN_THRESHOLD: u64 = 250;
pub(crate) const DRAFT_PROMPT_PERSIST_DEBOUNCE: Duration = Duration::from_millis(250);
+mod thread_search_bar;
mod thread_view;
pub use thread_view::*;
@@ -1593,7 +1594,7 @@ impl ConversationView {
active.update(cx, |active, cx| {
if !is_generating {
active.thread_retry_status.take();
- active.clear_auto_expand_tracking();
+ active.clear_auto_expand_tracking(cx);
if active.list_state.is_following_tail() {
active.list_state.scroll_to_end();
}
@@ -3115,8 +3116,10 @@ impl ConversationView {
/// This is primarily useful for visual testing.
pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
if let Some(active) = self.active_thread() {
- active.update(cx, |active, _cx| {
- active.expanded_tool_calls.insert(tool_call_id);
+ active.update(cx, |active, cx| {
+ active.entry_view_state.update(cx, |state, _cx| {
+ state.expand_tool_call(tool_call_id);
+ });
});
cx.notify();
}
@@ -6073,6 +6076,999 @@ pub(crate) mod tests {
});
}
+ #[gpui::test]
+ async fn test_thread_search_finds_matches_across_entries(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new(
+ "Yes, you can substitute banana for plantain in this recipe.".into(),
+ ),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.send_raw("Can I use banana here?", cx)
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new(
+ "Banana yogurt also works as a topping; whisk the banana smooth first.".into(),
+ ),
+ )]);
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.send_raw("What about as a topping?", cx)
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("banana", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let (match_count, active_text) =
+ bar.read_with(cx, |bar, cx| (bar.match_count(), bar.active_match_text(cx)));
+ assert_eq!(
+ match_count, 4,
+ "expected 4 matches for case-insensitive 'banana'"
+ );
+ assert_eq!(active_text.as_deref(), Some("1/4"));
+
+ thread_view.read_with(cx, |view, _| {
+ assert_eq!(view.list_state.logical_scroll_top().item_ix, 0);
+ });
+
+ bar.update_in(cx, |bar, window, cx| {
+ bar.select_next_match(&super::thread_search_bar::SelectNextThreadMatch, window, cx);
+ });
+ cx.run_until_parked();
+ let active_text_2 = bar.read_with(cx, |bar, cx| bar.active_match_text(cx));
+ assert_eq!(active_text_2.as_deref(), Some("2/4"));
+
+ bar.update_in(cx, |bar, window, cx| {
+ bar.select_prev_match(
+ &super::thread_search_bar::SelectPreviousThreadMatch,
+ window,
+ cx,
+ );
+ });
+ let active_text_3 = bar.read_with(cx, |bar, cx| bar.active_match_text(cx));
+ assert_eq!(active_text_3.as_deref(), Some("1/4"));
+
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("apple", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+ let (match_count_apple, active_text_apple) =
+ bar.read_with(cx, |bar, cx| (bar.match_count(), bar.active_match_text(cx)));
+ assert_eq!(match_count_apple, 0);
+ assert_eq!(active_text_apple.as_deref(), Some("0/0"));
+ }
+
+ #[gpui::test]
+ async fn test_thread_search_includes_expanded_thinking_blocks(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![
+ acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
+ "Hidden papaya reasoning.".into(),
+ )),
+ acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ "Final answer without that fruit.".into(),
+ )),
+ ]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Think this through", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let (assistant_entry_ix, thought_chunk_ix) = thread.read_with(cx, |thread, _| {
+ thread
+ .entries()
+ .iter()
+ .enumerate()
+ .find_map(|(entry_ix, entry)| match entry {
+ AgentThreadEntry::AssistantMessage(message) => message
+ .chunks
+ .iter()
+ .position(|chunk| matches!(chunk, AssistantMessageChunk::Thought { .. }))
+ .map(|chunk_ix| (entry_ix, chunk_ix)),
+ _ => None,
+ })
+ .expect("assistant thought chunk should exist")
+ });
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("papaya", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.match_count()),
+ 0,
+ "collapsed thinking content should not be searched",
+ );
+
+ thread_view.update(cx, |view, cx| {
+ view.entry_view_state.update(cx, |state, cx| {
+ state.toggle_thinking_block_expansion((assistant_entry_ix, thought_chunk_ix), cx);
+ });
+ });
+ bar.update_in(cx, |bar, window, cx| {
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.match_count()),
+ 1,
+ "expanded thinking content should be searchable",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_thread_search_includes_expanded_tool_call_content(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let tool_call_id = acp::ToolCallId::new("search-tool-content");
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
+ acp::ToolCall::new(tool_call_id.clone(), "Inspect output")
+ .kind(acp::ToolKind::Other)
+ .status(acp::ToolCallStatus::Completed)
+ .content(vec!["Tool output mentions papaya once.".into()]),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Run the tool", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("papaya", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.match_count()),
+ 0,
+ "collapsed tool-call content should not be searched",
+ );
+
+ thread_view.update(cx, |view, cx| {
+ view.entry_view_state.update(cx, |state, _cx| {
+ state.expand_tool_call(tool_call_id);
+ });
+ });
+ bar.update_in(cx, |bar, window, cx| {
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.match_count()),
+ 1,
+ "expanded tool-call content should be searchable",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_thread_search_scrolls_to_later_user_message_match(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("First reply, no fruit here.".into()),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("First question", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Second reply, still no fruit.".into()),
+ )]);
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Where is the papaya?", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ let papaya_entry_ix = thread.read_with(cx, |thread, _| {
+ thread
+ .entries()
+ .iter()
+ .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
+ .expect("a user message entry should exist")
+ });
+
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("papaya", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ bar.read_with(cx, |bar, _| {
+ assert_eq!(
+ bar.match_count(),
+ 1,
+ "only the second user message matches 'papaya'"
+ );
+ });
+
+ thread_view.read_with(cx, |view, _| {
+ assert_eq!(
+ view.list_state.logical_scroll_top().item_ix,
+ papaya_entry_ix,
+ "list should scroll to the user-message entry that owns the match",
+ );
+ });
+ }
+
+ /// Passive rescans (streaming updates, unrelated expansion toggles, query
+ /// refinement) must not yank the list back to the active match.
+ #[gpui::test]
+ async fn test_thread_search_passive_rescan_preserves_scroll(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("First reply, no fruit here.".into()),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("First question", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Second reply, still no fruit.".into()),
+ )]);
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Where is the papaya?", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ let papaya_entry_ix = thread.read_with(cx, |thread, _| {
+ thread
+ .entries()
+ .iter()
+ .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
+ .expect("a user message entry should exist")
+ });
+
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("papaya", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ // The initial query activates (and scrolls to) the only match.
+ thread_view.read_with(cx, |view, _| {
+ assert_eq!(
+ view.list_state.logical_scroll_top().item_ix,
+ papaya_entry_ix,
+ );
+ });
+
+ // Simulate the user scrolling elsewhere, then a passive rescan re-running
+ // the matcher while the same hit stays active.
+ thread_view.update(cx, |view, _| {
+ view.list_state.scroll_to(gpui::ListOffset {
+ item_ix: 0,
+ offset_in_item: gpui::px(0.),
+ });
+ });
+ bar.update_in(cx, |bar, window, cx| {
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ thread_view.read_with(cx, |view, _| {
+ assert_eq!(
+ view.list_state.logical_scroll_top().item_ix,
+ 0,
+ "a passive rescan must not scroll back to the active match",
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_thread_search_dismiss_clears_highlights(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Mango is a tropical fruit.".into()),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Tell me about mango", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .unwrap();
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("mango", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let entries = thread.read_with(cx, |thread, _| thread.entries().len());
+ assert!(entries > 0);
+
+ bar.update(cx, |bar, cx| bar.clear_highlights(cx));
+ cx.run_until_parked();
+
+ bar.read_with(cx, |bar, _| {
+ assert_eq!(bar.match_count(), 0);
+ assert!(bar.active_match_index().is_none());
+ });
+ }
+
+ #[gpui::test]
+ async fn test_thread_search_release_clears_markdown_highlights(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Mango is a tropical fruit.".into()),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Tell me about mango", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let assistant_markdown = thread.read_with(cx, |thread, _| {
+ thread
+ .entries()
+ .iter()
+ .find_map(|entry| match entry {
+ AgentThreadEntry::AssistantMessage(message) => {
+ message.chunks.iter().find_map(|chunk| match chunk {
+ AssistantMessageChunk::Message { block } => block.markdown().cloned(),
+ AssistantMessageChunk::Thought { .. } => None,
+ })
+ }
+ _ => None,
+ })
+ .expect("assistant message should have markdown")
+ });
+
+ let entry_view_state = active_thread(&conversation_view, cx)
+ .read_with(cx, |view, _| view.entry_view_state.clone());
+ let on_activate_match: Arc<dyn Fn(usize, &mut Window, &mut App)> = Arc::new(|_, _, _| {});
+ let bar = cx.update(|window, cx| {
+ cx.new(|cx| {
+ super::thread_search_bar::ThreadSearchBar::new(
+ thread.clone(),
+ entry_view_state,
+ on_activate_match,
+ window,
+ cx,
+ )
+ })
+ });
+
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("mango", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ assert!(
+ assistant_markdown
+ .read_with(cx, |markdown, _| !markdown.search_highlights().is_empty()),
+ "search should have highlighted the assistant markdown before release",
+ );
+
+ drop(bar);
+ cx.update(|_, _| {});
+ cx.run_until_parked();
+
+ assert!(
+ assistant_markdown.read_with(cx, |markdown, _| markdown.search_highlights().is_empty()),
+ "releasing the search bar should clear retained markdown highlights",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_thread_search_refreshes_on_new_thread_entry(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("First reply mentions banana once.".into()),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Tell me about banana", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("banana", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let count_before = bar.read_with(cx, |bar, _| bar.match_count());
+ assert!(
+ count_before >= 2,
+ "expected at least two initial matches, got {count_before}",
+ );
+
+ bar.update_in(cx, |bar, window, cx| {
+ bar.select_next_match(&super::thread_search_bar::SelectNextThreadMatch, window, cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.active_match_index()),
+ Some(1),
+ "setup precondition: second match should be active before the refresh",
+ );
+
+ // Advance past the debounced thread-update rescan.
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Banana banana: two more banana hits here.".into()),
+ )]);
+ thread
+ .update(cx, |thread, cx| thread.send_raw("More banana please", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+ cx.executor()
+ .advance_clock(super::thread_search_bar::SEARCH_UPDATE_DEBOUNCE * 2);
+ cx.run_until_parked();
+
+ let (count_after, active_after) =
+ bar.read_with(cx, |bar, _| (bar.match_count(), bar.active_match_index()));
+ assert!(
+ count_after > count_before,
+ "thread subscription should refresh matches after new content \
+ streamed in: before={count_before}, after={count_after}",
+ );
+ assert_eq!(
+ active_after,
+ Some(1),
+ "refreshing matches should preserve the active result when it still exists",
+ );
+ }
+
+ /// Regression test for re-entering `ThreadView` during search navigation.
+ #[gpui::test]
+ async fn test_thread_search_select_next_from_thread_view_update_does_not_panic(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new(
+ "Banana banana banana, the banana fits the banana bread.".into(),
+ ),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Need banana help", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("banana", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let initial_match_count = bar.read_with(cx, |bar, _| bar.match_count());
+ assert!(
+ initial_match_count >= 2,
+ "setup precondition: expected at least 2 matches, got {}",
+ initial_match_count,
+ );
+
+ thread_view.update_in(cx, |view, window, cx| {
+ let bar = view
+ .thread_search_bar
+ .clone()
+ .expect("bar should still be set");
+ bar.update(cx, |bar, cx| {
+ bar.select_next_match(&super::thread_search_bar::SelectNextThreadMatch, window, cx);
+ });
+ });
+ cx.run_until_parked();
+
+ let active_after = bar.read_with(cx, |bar, _| bar.active_match_index());
+ assert_eq!(
+ active_after,
+ Some(1),
+ "select_next_match should have advanced from match 0 to match 1",
+ );
+ }
+
+ /// Past user-message hits must be painted on the inner `Editor`.
+ #[gpui::test]
+ async fn test_thread_search_highlights_user_message_editor(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Sure, I can help with that.".into()),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| {
+ thread.send_raw("Where do I find a kumquat?", cx)
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("kumquat", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let match_count = bar.read_with(cx, |bar, _| bar.match_count());
+ assert_eq!(
+ match_count, 1,
+ "expected exactly one match for 'kumquat' (in the user message)",
+ );
+
+ let user_message_editor = thread_view.read_with(cx, |view, cx| {
+ view.entry_view_state
+ .read(cx)
+ .entry(0)
+ .and_then(|entry| entry.message_editor())
+ .map(|message_editor| message_editor.read(cx).editor().clone())
+ .expect("entry 0 should be a user message with a message editor")
+ });
+ let has_highlight = user_message_editor.read_with(cx, |editor, _cx| {
+ editor.has_background_highlights(editor::HighlightKey::BufferSearchHighlights)
+ });
+ assert!(
+ has_highlight,
+ "user message editor should carry BufferSearchHighlights after the bar's matcher ran",
+ );
+
+ bar.update(cx, |bar, cx| bar.clear_highlights(cx));
+ cx.run_until_parked();
+ let has_highlight_after_clear = user_message_editor.read_with(cx, |editor, _cx| {
+ editor.has_background_highlights(editor::HighlightKey::BufferSearchHighlights)
+ });
+ assert!(
+ !has_highlight_after_clear,
+ "clear_highlights should remove the editor-backed highlights",
+ );
+ }
+
+ /// `editor::Cancel` should dismiss thread search before reaching workspace handlers.
+ #[gpui::test]
+ async fn test_thread_search_editor_cancel_dismisses_bar(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let visible_before = thread_view.read_with(cx, |view, _| view.thread_search_visible);
+ assert!(
+ visible_before,
+ "search bar should be visible after toggle_search"
+ );
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("bar should be set");
+ let query_focus = bar.read_with(cx, |bar, cx| bar.query_editor.focus_handle(cx));
+ cx.update(|window, cx| {
+ window.focus(&query_focus, cx);
+ });
+ cx.run_until_parked();
+
+ conversation_view.update_in(cx, |_, window, cx| {
+ window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
+ });
+ cx.run_until_parked();
+
+ let visible_after = thread_view.read_with(cx, |view, _| view.thread_search_visible);
+ assert!(
+ !visible_after,
+ "editor::Cancel should have dismissed the bar before reaching the workspace",
+ );
+ }
+
+ /// JetBrains keymaps route Shift+Enter through `editor::NewlineBelow`.
+ #[gpui::test]
+ async fn test_thread_search_shift_enter_navigates_with_jetbrains_keymap(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ cx.update(|cx| {
+ // Load both the default binding and the conflicting base keymap.
+ search::init(cx);
+
+ let mut default_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
+ "keymaps/default-linux.json",
+ cx,
+ )
+ .unwrap();
+ for binding in &mut default_bindings {
+ binding.set_meta(settings::KeybindSource::Default.meta());
+ }
+ cx.bind_keys(default_bindings);
+
+ let mut jetbrains_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
+ "keymaps/linux/jetbrains.json",
+ cx,
+ )
+ .unwrap();
+ for binding in &mut jetbrains_bindings {
+ binding.set_meta(settings::KeybindSource::Base.meta());
+ }
+ cx.bind_keys(jetbrains_bindings);
+ });
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new(
+ "Banana banana banana, multiple banana mentions in this reply.".into(),
+ ),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Need banana help", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("banana", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let initial_count = bar.read_with(cx, |bar, _| bar.match_count());
+ assert!(
+ initial_count >= 2,
+ "test precondition: need ≥2 matches across the thread, got {}",
+ initial_count,
+ );
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.active_match_index()),
+ Some(0),
+ "first match should be active after the bar populates its match list",
+ );
+
+ let query_focus = bar.read_with(cx, |bar, cx| bar.query_editor.focus_handle(cx));
+ cx.update(|window, cx| {
+ window.focus(&query_focus, cx);
+ });
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(
+ query_focus.contains_focused(window, cx),
+ "query editor must be focused before simulating shift-enter",
+ );
+ });
+
+ cx.simulate_keystrokes("shift-enter");
+ cx.run_until_parked();
+
+ let query_text_after = bar.read_with(cx, |bar, cx| bar.query_editor.read(cx).text(cx));
+ assert!(
+ !query_text_after.contains('\n'),
+ "shift-enter must not insert a newline into the query buffer; got {:?}",
+ query_text_after,
+ );
+
+ let active_after = bar.read_with(cx, |bar, _| bar.active_match_index());
+ assert_eq!(
+ active_after,
+ Some(initial_count - 1),
+ "shift-enter should have wrapped active match from 0 to {} (got {:?})",
+ initial_count - 1,
+ active_after,
+ );
+ }
+
+ /// `f3`/`shift-f3` are bound in the broad `AcpThread` context (like buffer
+ /// search's pane-level `cmd-g`), so they must navigate matches even when
+ /// focus is outside the search bar.
+ #[gpui::test]
+ async fn test_thread_search_navigates_from_outside_search_bar(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ search::init(cx);
+ let mut default_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
+ "keymaps/default-linux.json",
+ cx,
+ )
+ .unwrap();
+ for binding in &mut default_bindings {
+ binding.set_meta(settings::KeybindSource::Default.meta());
+ }
+ cx.bind_keys(default_bindings);
+ });
+
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new(
+ "Banana banana banana, multiple banana mentions in this reply.".into(),
+ ),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread =
+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("Need banana help", cx))
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("thread_search_bar should be set after toggle_search");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("banana", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+
+ let initial_count = bar.read_with(cx, |bar, _| bar.match_count());
+ assert!(
+ initial_count >= 2,
+ "test precondition: need ≥ 2 matches, got {}",
+ initial_count,
+ );
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.active_match_index()),
+ Some(0)
+ );
+
+ // Move focus out of the search bar, back into the thread view itself.
+ let thread_focus = thread_view.read_with(cx, |view, cx| view.focus_handle(cx));
+ cx.update(|window, cx| window.focus(&thread_focus, cx));
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ let bar_focused = bar.read_with(cx, |bar, cx| {
+ bar.query_editor
+ .focus_handle(cx)
+ .contains_focused(window, cx)
+ });
+ assert!(!bar_focused, "search bar must not be focused for this test");
+ });
+
+ cx.simulate_keystrokes("f3");
+ cx.run_until_parked();
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.active_match_index()),
+ Some(1),
+ "f3 from outside the bar should advance to the next match",
+ );
+
+ cx.simulate_keystrokes("shift-f3");
+ cx.run_until_parked();
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.active_match_index()),
+ Some(0),
+ "shift-f3 from outside the bar should return to the previous match",
+ );
+ }
+
#[gpui::test]
async fn test_message_editing_cancel(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
new file mode 100644
index 00000000000..b1c15cca174
--- /dev/null
+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
@@ -0,0 +1,962 @@
+use std::ops::Range;
+use std::sync::Arc;
+use std::time::Duration;
+
+use acp_thread::{
+ AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessageChunk, ContentBlock,
+ ToolCallContent,
+};
+use collections::HashMap;
+use editor::{
+ Editor, EditorElement, EditorEvent, EditorStyle, HighlightKey, SelectionEffects,
+ scroll::Autoscroll,
+};
+use gpui::{
+ Action, App, Context, Entity, EntityId, EventEmitter, FocusHandle, Focusable, Hsla, KeyContext,
+ SharedString, Subscription, Task, TextStyle, WeakEntity, Window, actions, relative, rems,
+};
+use markdown::Markdown;
+use multi_buffer::{Anchor, MultiBufferOffset, MultiBufferSnapshot};
+use project::search::SearchQuery;
+use search::{SearchOption, SearchOptions, SearchSource};
+use settings::Settings as _;
+use theme_settings::ThemeSettings;
+use ui::{
+ ActiveTheme, ButtonStyle, Color, IconButton, IconButtonShape, IconName, IntoElement, Label,
+ LabelSize, Tooltip, div, h_flex, prelude::*, v_flex,
+};
+use util::paths::PathMatcher;
+
+use crate::entry_view_state::EntryViewState;
+
+actions!(
+ agent,
+ [
+ /// Closes the thread search bar.
+ DismissThreadSearch,
+ /// Selects the next thread search match.
+ SelectNextThreadMatch,
+ /// Selects the previous thread search match.
+ SelectPreviousThreadMatch,
+ ]
+);
+
+/// Debounce for streaming thread updates, which can fire once per streamed
+/// chunk. Query edits are handled immediately instead (see the query editor
+/// subscription in `ThreadSearchBar::new`).
+pub(super) const SEARCH_UPDATE_DEBOUNCE: Duration = Duration::from_millis(150);
+
+/// Search hits can be painted on either markdown or past-message editors.
+#[derive(Clone)]
+enum MatchTarget {
+ Markdown {
+ markdown: WeakEntity<Markdown>,
+ markdown_match_ix: usize,
+ },
+ Editor {
+ editor: WeakEntity<Editor>,
+ anchor_range: Range<Anchor>,
+ editor_match_ix: usize,
+ },
+}
+
+impl MatchTarget {
+ fn entity_id(&self) -> EntityId {
+ match self {
+ MatchTarget::Markdown { markdown, .. } => markdown.entity_id(),
+ MatchTarget::Editor { editor, .. } => editor.entity_id(),
+ }
+ }
+
+ /// Index of this hit within its painted entity (markdown- or editor-local).
+ fn match_ix(&self) -> usize {
+ match self {
+ MatchTarget::Markdown {
+ markdown_match_ix, ..
+ } => *markdown_match_ix,
+ MatchTarget::Editor {
+ editor_match_ix, ..
+ } => *editor_match_ix,
+ }
+ }
+}
+
+struct ThreadMatch {
+ entry_ix: usize,
+ target: MatchTarget,
+ source_range: Range<usize>,
+}
+
+impl ThreadMatch {
+ /// Stable identity used to re-locate the active match across a rescan.
+ fn key(&self) -> MatchKey {
+ MatchKey {
+ entry_ix: self.entry_ix,
+ entity_id: self.target.entity_id(),
+ source_range: self.source_range.clone(),
+ }
+ }
+}
+
+#[derive(PartialEq)]
+struct MatchKey {
+ entry_ix: usize,
+ entity_id: EntityId,
+ source_range: Range<usize>,
+}
+
+enum SearchTarget {
+ Editor {
+ entry_ix: usize,
+ editor: Entity<Editor>,
+ snapshot: MultiBufferSnapshot,
+ },
+ Markdown {
+ entry_ix: usize,
+ markdown: Entity<Markdown>,
+ source: SharedString,
+ },
+}
+
+enum ScannedTarget {
+ Editor {
+ entry_ix: usize,
+ editor: Entity<Editor>,
+ ranges: Vec<Range<usize>>,
+ anchor_ranges: Vec<Range<Anchor>>,
+ },
+ Markdown {
+ entry_ix: usize,
+ markdown: Entity<Markdown>,
+ ranges: Vec<Range<usize>>,
+ },
+}
+
+pub struct ThreadSearchBar {
+ pub(super) query_editor: Entity<Editor>,
+ options: SearchOptions,
+ matches: Vec<ThreadMatch>,
+ active_match: Option<usize>,
+ query_error: bool,
+ query_error_message: Option<SharedString>,
+ highlighted_markdowns: Vec<WeakEntity<Markdown>>,
+ highlighted_editors: Vec<WeakEntity<Editor>>,
+ thread: Entity<AcpThread>,
+ entry_view_state: Entity<EntryViewState>,
+ on_activate_match: Arc<dyn Fn(usize, &mut Window, &mut App)>,
+ is_active: bool,
+ _update_matches_task: Option<Task<()>>,
+ _search_task: Option<Task<()>>,
+ _subscriptions: Vec<Subscription>,
+}
+
+pub enum ThreadSearchBarEvent {
+ Dismissed,
+}
+
+impl EventEmitter<ThreadSearchBarEvent> for ThreadSearchBar {}
+
+impl Focusable for ThreadSearchBar {
+ fn focus_handle(&self, cx: &App) -> FocusHandle {
+ self.query_editor.focus_handle(cx)
+ }
+}
+
+impl ThreadSearchBar {
+ pub fn new(
+ thread: Entity<AcpThread>,
+ entry_view_state: Entity<EntryViewState>,
+ on_activate_match: Arc<dyn Fn(usize, &mut Window, &mut App)>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ let query_editor = cx.new(|cx| {
+ let mut editor = Editor::single_line(window, cx);
+ editor.set_placeholder_text("Search this thread…", window, cx);
+ editor
+ });
+ let editor_subscription = cx.subscribe_in(
+ &query_editor,
+ window,
+ |this, _editor, event: &EditorEvent, window, cx| {
+ if matches!(
+ event,
+ EditorEvent::Edited { .. } | EditorEvent::BufferEdited
+ ) {
+ // Re-scan immediately so typing feels responsive
+ this._update_matches_task = None;
+ this.update_matches(window, cx);
+ }
+ },
+ );
+ let thread_subscription = cx.subscribe_in(
+ &thread,
+ window,
+ |this, _thread, event: &AcpThreadEvent, window, cx| {
+ if this.is_active
+ && matches!(
+ event,
+ AcpThreadEvent::NewEntry
+ | AcpThreadEvent::EntryUpdated(_)
+ | AcpThreadEvent::EntriesRemoved(_)
+ )
+ {
+ this.schedule_update_matches(window, cx);
+ }
+ },
+ );
+ cx.on_release(|this, cx| {
+ this.clear_highlights_impl(cx);
+ })
+ .detach();
+ Self {
+ query_editor,
+ options: SearchOptions::NONE,
+ matches: Vec::new(),
+ active_match: None,
+ query_error: false,
+ query_error_message: None,
+ highlighted_markdowns: Vec::new(),
+ highlighted_editors: Vec::new(),
+ thread,
+ entry_view_state,
+ on_activate_match,
+ is_active: false,
+ _update_matches_task: None,
+ _search_task: None,
+ _subscriptions: vec![editor_subscription, thread_subscription],
+ }
+ }
+
+ pub fn focus_and_refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.is_active = true;
+ self.focus_query_and_select_all(window, cx);
+ self.update_matches(window, cx);
+ }
+
+ fn focus_query_and_select_all(&self, window: &mut Window, cx: &mut Context<Self>) {
+ let focus_handle = self.query_editor.focus_handle(cx);
+ focus_handle.focus(window, cx);
+ self.query_editor.update(cx, |editor, cx| {
+ editor.select_all(&editor::actions::SelectAll, window, cx);
+ });
+ }
+
+ fn schedule_update_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self._update_matches_task = Some(cx.spawn_in(window, async move |this, cx| {
+ cx.background_executor().timer(SEARCH_UPDATE_DEBOUNCE).await;
+ this.update_in(cx, |this, window, cx| this.update_matches(window, cx))
+ .ok();
+ }));
+ }
+
+ #[cfg(test)]
+ pub(super) fn match_count(&self) -> usize {
+ self.matches.len()
+ }
+
+ #[cfg(test)]
+ pub(super) fn active_match_index(&self) -> Option<usize> {
+ self.active_match
+ }
+
+ pub fn active_match_text(&self, cx: &App) -> Option<String> {
+ if self.query_editor.read(cx).text(cx).is_empty() {
+ return None;
+ }
+ match self.active_match {
+ Some(ix) => Some(format!("{}/{}", ix + 1, self.matches.len())),
+ None => Some(format!("0/{}", self.matches.len())),
+ }
+ }
+
+ fn current_query(&self, cx: &App) -> String {
+ self.query_editor.read(cx).text(cx)
+ }
+
+ fn build_query(&self, cx: &App) -> (Option<Arc<SearchQuery>>, Option<SharedString>) {
+ let text = self.current_query(cx);
+ if text.is_empty() {
+ return (None, None);
+ }
+ let whole_word = self.options.contains(SearchOptions::WHOLE_WORD);
+ let case_sensitive = self.options.contains(SearchOptions::CASE_SENSITIVE);
+ let result = if self.options.contains(SearchOptions::REGEX) {
+ SearchQuery::regex(
+ text,
+ whole_word,
+ case_sensitive,
+ false,
+ false,
+ PathMatcher::default(),
+ PathMatcher::default(),
+ false,
+ None,
+ )
+ } else {
+ SearchQuery::text(
+ text,
+ whole_word,
+ case_sensitive,
+ false,
+ PathMatcher::default(),
+ PathMatcher::default(),
+ false,
+ None,
+ )
+ };
+ match result {
+ Ok(q) => (Some(Arc::new(q)), None),
+ Err(err) => (None, Some(SharedString::from(err.to_string()))),
+ }
+ }
+
+ pub(super) fn update_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let previous_active_match_ix = self.active_match;
+ let previous_active_key = previous_active_match_ix
+ .and_then(|ix| self.matches.get(ix))
+ .map(ThreadMatch::key);
+
+ let (query, err_msg) = self.build_query(cx);
+ self.query_error = !self.current_query(cx).is_empty() && query.is_none();
+ self.query_error_message = err_msg;
+
+ let Some(query) = query else {
+ self.clear_results(cx);
+ cx.notify();
+ return;
+ };
+
+ let mut targets: Vec<SearchTarget> = Vec::new();
+ let thread = self.thread.read(cx);
+ let entry_view_state = self.entry_view_state.read(cx);
+ for (entry_ix, entry) in thread.entries().iter().enumerate() {
+ match entry {
+ // Past user messages render through `MessageEditor`, not markdown.
+ AgentThreadEntry::UserMessage(_) => {
+ let editor = entry_view_state
+ .entry(entry_ix)
+ .and_then(|view_entry| view_entry.message_editor())
+ .map(|message_editor| message_editor.read(cx).editor().clone());
+ let Some(editor) = editor else {
+ continue;
+ };
+ let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
+ targets.push(SearchTarget::Editor {
+ entry_ix,
+ editor,
+ snapshot,
+ });
+ }
+ _ => {
+ for markdown in collect_markdowns(entry_ix, entry, &entry_view_state, cx) {
+ let source = markdown.read(cx).source().clone();
+ targets.push(SearchTarget::Markdown {
+ entry_ix,
+ markdown,
+ source,
+ });
+ }
+ }
+ }
+ }
+
+ if targets.is_empty() {
+ self.clear_results(cx);
+ cx.notify();
+ return;
+ }
+
+ self._search_task = Some(cx.spawn_in(window, async move |this, cx| {
+ let scanned = cx
+ .background_spawn(async move {
+ targets
+ .into_iter()
+ .filter_map(|target| match target {
+ SearchTarget::Editor {
+ entry_ix,
+ editor,
+ snapshot,
+ } => {
+ let ranges = query.search_str(&snapshot.text());
+ if ranges.is_empty() {
+ return None;
+ }
+ let anchor_ranges = ranges
+ .iter()
+ .map(|range| {
+ snapshot.anchor_before(MultiBufferOffset(range.start))
+ ..snapshot.anchor_after(MultiBufferOffset(range.end))
+ })
+ .collect();
+ Some(ScannedTarget::Editor {
+ entry_ix,
+ editor,
+ ranges,
+ anchor_ranges,
+ })
+ }
+ SearchTarget::Markdown {
+ entry_ix,
+ markdown,
+ source,
+ } => {
+ let ranges = query.search_str(&source);
+ if ranges.is_empty() {
+ return None;
+ }
+ Some(ScannedTarget::Markdown {
+ entry_ix,
+ markdown,
+ ranges,
+ })
+ }
+ })
+ .collect::<Vec<_>>()
+ })
+ .await;
+ this.update_in(cx, |this, window, cx| {
+ this.apply_search_results(
+ scanned,
+ previous_active_key,
+ previous_active_match_ix,
+ window,
+ cx,
+ );
+ })
+ .ok();
+ }));
+ }
+
+ fn apply_search_results(
+ &mut self,
+ scanned: Vec<ScannedTarget>,
+ previous_active_key: Option<MatchKey>,
+ previous_active_match_ix: Option<usize>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.clear_match_highlights(cx);
+ self.matches.clear();
+ self.active_match = None;
+
+ for target in scanned {
+ match target {
+ ScannedTarget::Editor {
+ entry_ix,
+ editor,
+ ranges,
+ anchor_ranges,
+ } => {
+ let weak_editor = editor.downgrade();
+ for (ix, (range, anchor_range)) in ranges.iter().zip(&anchor_ranges).enumerate()
+ {
+ self.matches.push(ThreadMatch {
+ entry_ix,
+ target: MatchTarget::Editor {
+ editor: weak_editor.clone(),
+ anchor_range: anchor_range.clone(),
+ editor_match_ix: ix,
+ },
+ source_range: range.clone(),
+ });
+ }
+ self.highlighted_editors.push(weak_editor);
+ }
+ ScannedTarget::Markdown {
+ entry_ix,
+ markdown,
+ ranges,
+ } => {
+ let weak = markdown.downgrade();
+ for (ix, range) in ranges.iter().enumerate() {
+ self.matches.push(ThreadMatch {
+ entry_ix,
+ target: MatchTarget::Markdown {
+ markdown: weak.clone(),
+ markdown_match_ix: ix,
+ },
+ source_range: range.clone(),
+ });
+ }
+ self.highlighted_markdowns.push(weak);
+ markdown.update(cx, |md, cx| {
+ md.set_search_highlights(ranges, None, cx);
+ });
+ }
+ }
+ }
+
+ if !self.matches.is_empty() {
+ let preserved_ix = previous_active_key
+ .as_ref()
+ .and_then(|key| self.matches.iter().position(|m| &m.key() == key));
+ let active_match_ix = preserved_ix
+ .or_else(|| previous_active_match_ix.filter(|ix| *ix < self.matches.len()))
+ .unwrap_or(0);
+ let scroll_to_match = preserved_ix.is_none();
+ self.activate_match(active_match_ix, scroll_to_match, window, cx);
+ } else {
+ cx.notify();
+ }
+ }
+
+ fn activate_match(
+ &mut self,
+ ix: usize,
+ scroll_to_match: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(m) = self.matches.get(ix) else {
+ return;
+ };
+ let entry_ix = m.entry_ix;
+ let source_index = m.source_range.start;
+ let target = m.target.clone();
+ // Markdown and editor entity ids never collide, so the active hit is
+ // simply the painted entity whose id equals the target's.
+ let target_entity_id = target.entity_id();
+ let target_match_ix = target.match_ix();
+
+ for weak in &self.highlighted_markdowns {
+ if let Some(markdown) = weak.upgrade() {
+ let active = (weak.entity_id() == target_entity_id).then_some(target_match_ix);
+ markdown.update(cx, |markdown, cx| {
+ markdown.set_active_search_highlight(active, cx);
+ if active.is_some() && scroll_to_match {
+ markdown.request_autoscroll_to_source_index(source_index, cx);
+ }
+ });
+ }
+ }
+
+ // Editor highlight colors are computed by index, so repaint on navigation.
+ let mut per_editor: HashMap<EntityId, (WeakEntity<Editor>, Vec<Range<Anchor>>)> =
+ HashMap::default();
+ for mat in &self.matches {
+ if let MatchTarget::Editor {
+ editor,
+ anchor_range,
+ ..
+ } = &mat.target
+ {
+ let entry = per_editor
+ .entry(editor.entity_id())
+ .or_insert_with(|| (editor.clone(), Vec::new()));
+ entry.1.push(anchor_range.clone());
+ }
+ }
+ for (editor_id, (weak_editor, ranges)) in per_editor {
+ let Some(editor) = weak_editor.upgrade() else {
+ continue;
+ };
+ let active_ix = (editor_id == target_entity_id).then_some(target_match_ix);
+ editor.update(cx, |editor, cx| {
+ editor.highlight_background(
+ HighlightKey::BufferSearchHighlights,
+ &ranges,
+ move |index, theme| {
+ if active_ix == Some(*index) {
+ theme.colors().search_active_match_background
+ } else {
+ theme.colors().search_match_background
+ }
+ },
+ cx,
+ );
+ });
+ }
+
+ if scroll_to_match
+ && let MatchTarget::Editor {
+ editor,
+ anchor_range,
+ ..
+ } = &target
+ && let Some(editor) = editor.upgrade()
+ {
+ let anchor_range = anchor_range.clone();
+ editor.update(cx, |editor, cx| {
+ editor.change_selections(
+ SelectionEffects::scroll(Autoscroll::fit()).from_search(true),
+ window,
+ cx,
+ |selections| selections.select_anchor_ranges([anchor_range]),
+ );
+ });
+ }
+
+ self.active_match = Some(ix);
+ if scroll_to_match {
+ (self.on_activate_match)(entry_ix, window, cx);
+ }
+ cx.notify();
+ }
+
+ pub(super) fn select_next_match(
+ &mut self,
+ _: &SelectNextThreadMatch,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.matches.is_empty() {
+ return;
+ }
+ let next = match self.active_match {
+ Some(ix) => (ix + 1) % self.matches.len(),
+ None => 0,
+ };
+ self.activate_match(next, true, window, cx);
+ }
+
+ pub(super) fn select_prev_match(
+ &mut self,
+ _: &SelectPreviousThreadMatch,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.matches.is_empty() {
+ return;
+ }
+ let prev = match self.active_match {
+ Some(ix) => {
+ if ix == 0 {
+ self.matches.len() - 1
+ } else {
+ ix - 1
+ }
+ }
+ None => self.matches.len() - 1,
+ };
+ self.activate_match(prev, true, window, cx);
+ }
+
+ fn dismiss(&mut self, _: &DismissThreadSearch, _window: &mut Window, cx: &mut Context<Self>) {
+ self.clear_highlights(cx);
+ cx.emit(ThreadSearchBarEvent::Dismissed);
+ }
+
+ pub fn clear_highlights(&mut self, cx: &mut Context<Self>) {
+ self.clear_highlights_impl(cx);
+ cx.notify();
+ }
+
+ fn clear_highlights_impl(&mut self, cx: &mut App) {
+ self.clear_results(cx);
+ self.is_active = false;
+ self._update_matches_task = None;
+ }
+
+ /// Drops all painted highlights, recorded matches, and any in-flight scan.
+ fn clear_results(&mut self, cx: &mut App) {
+ self.clear_match_highlights(cx);
+ self.matches.clear();
+ self.active_match = None;
+ self._search_task = None;
+ }
+
+ fn clear_match_highlights(&mut self, cx: &mut App) {
+ for weak in self.highlighted_markdowns.drain(..) {
+ if let Some(md) = weak.upgrade() {
+ md.update(cx, |md, cx| md.clear_search_highlights(cx));
+ }
+ }
+ for weak in self.highlighted_editors.drain(..) {
+ if let Some(editor) = weak.upgrade() {
+ editor.update(cx, |editor, cx| {
+ editor.clear_background_highlights(HighlightKey::BufferSearchHighlights, cx);
+ });
+ }
+ }
+ }
+
+ pub(super) fn toggle_case_sensitive(
+ &mut self,
+ _: &search::ToggleCaseSensitive,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.options.toggle(SearchOptions::CASE_SENSITIVE);
+ self.update_matches(window, cx);
+ }
+
+ pub(super) fn toggle_whole_word(
+ &mut self,
+ _: &search::ToggleWholeWord,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.options.toggle(SearchOptions::WHOLE_WORD);
+ self.update_matches(window, cx);
+ }
+
+ pub(super) fn toggle_regex(
+ &mut self,
+ _: &search::ToggleRegex,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.options.toggle(SearchOptions::REGEX);
+ self.update_matches(window, cx);
+ }
+
+ pub(super) fn focus_search(
+ &mut self,
+ _: &search::FocusSearch,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.focus_query_and_select_all(window, cx);
+ }
+}
+
+impl Render for ThreadSearchBar {
+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let focus_handle = self.query_editor.focus_handle(cx);
+ let theme = cx.theme().colors();
+ let has_matches = !self.matches.is_empty();
+ let query_empty = self.query_editor.read(cx).text(cx).is_empty();
+ let in_error_state = self.query_error || (!query_empty && !has_matches);
+ let border_color = theme.border;
+
+ let mut key_context = KeyContext::new_with_defaults();
+ key_context.add("AcpThreadSearchBar");
+
+ let counter_text = self.active_match_text(cx).unwrap_or_default();
+ let counter_color = if has_matches {
+ Color::Default
+ } else {
+ Color::Muted
+ };
+
+ let bar_row = h_flex()
+ .track_focus(&focus_handle)
+ .key_context(key_context)
+ .on_action(cx.listener(Self::dismiss))
+ .on_action(cx.listener(Self::select_next_match))
+ .on_action(cx.listener(Self::select_prev_match))
+ .on_action(cx.listener(Self::toggle_case_sensitive))
+ .on_action(cx.listener(Self::toggle_whole_word))
+ .on_action(cx.listener(Self::toggle_regex))
+ .on_action(cx.listener(Self::focus_search))
+ .w_full()
+ .gap_2()
+ .px_2()
+ .py_1()
+ .border_b_1()
+ .border_color(theme.border)
+ .bg(theme.toolbar_background)
+ .child(
+ input_box(border_color)
+ .flex_1()
+ .min_w_32()
+ .child(div().flex_1().min_w_0().py_1().child(render_query_input(
+ &self.query_editor,
+ in_error_state,
+ cx,
+ )))
+ .child(
+ h_flex()
+ .flex_none()
+ .gap_1()
+ .child(SearchOption::CaseSensitive.as_button(
+ self.options,
+ SearchSource::Buffer,
+ focus_handle.clone(),
+ ))
+ .child(SearchOption::WholeWord.as_button(
+ self.options,
+ SearchSource::Buffer,
+ focus_handle.clone(),
+ ))
+ .child(SearchOption::Regex.as_button(
+ self.options,
+ SearchSource::Buffer,
+ focus_handle.clone(),
+ )),
+ ),
+ )
+ .child(
+ h_flex()
+ .flex_none()
+ .gap_1()
+ .child(nav_button(
+ "thread-search-prev",
+ IconName::ChevronLeft,
+ !has_matches,
+ "Previous Match",
+ &SelectPreviousThreadMatch,
+ focus_handle.clone(),
+ ))
+ .child(nav_button(
+ "thread-search-next",
+ IconName::ChevronRight,
+ !has_matches,
+ "Next Match",
+ &SelectNextThreadMatch,
+ focus_handle.clone(),
+ ))
+ .child(
+ div().ml_1().min_w(rems(2.5)).child(
+ Label::new(counter_text)
+ .size(LabelSize::Small)
+ .color(counter_color),
+ ),
+ )
+ .child(nav_button(
+ "thread-search-dismiss",
+ IconName::Close,
+ false,
+ "Close Search",
+ &DismissThreadSearch,
+ focus_handle,
+ )),
+ );
+
+ let error_row = self.query_error_message.clone().map(|msg| {
+ div()
+ .w_full()
+ .px_2()
+ .py_0p5()
+ .border_b_1()
+ .border_color(theme.border)
+ .bg(theme.toolbar_background)
+ .child(Label::new(msg).size(LabelSize::Small).color(Color::Error))
+ });
+
+ v_flex().w_full().child(bar_row).children(error_row)
+ }
+}
+
+fn input_box(border_color: Hsla) -> gpui::Div {
+ h_flex()
+ .min_h_8()
+ .pl_2()
+ .pr_1()
+ .border_1()
+ .border_color(border_color)
+ .rounded_md()
+}
+
+fn render_query_input(editor: &Entity<Editor>, has_error: bool, app: &App) -> impl IntoElement {
+ let theme = app.theme().colors();
+ let (color, use_syntax) = if has_error {
+ (ui::Color::Error.color(app), false)
+ } else {
+ (theme.text, true)
+ };
+ let settings = ThemeSettings::get_global(app);
+ let text_style = TextStyle {
+ color,
+ font_family: settings.buffer_font.family.clone(),
+ font_features: settings.buffer_font.features.clone(),
+ font_fallbacks: settings.buffer_font.fallbacks.clone(),
+ font_size: rems(0.875).into(),
+ font_weight: settings.buffer_font.weight,
+ line_height: relative(1.3),
+ ..TextStyle::default()
+ };
+ let mut style = EditorStyle {
+ background: theme.toolbar_background,
+ local_player: app.theme().players().local(),
+ text: text_style,
+ ..EditorStyle::default()
+ };
+ if use_syntax {
+ style.syntax = app.theme().syntax().clone();
+ }
+ EditorElement::new(editor, style)
+}
+
+fn nav_button(
+ id: &'static str,
+ icon: IconName,
+ disabled: bool,
+ tooltip: &'static str,
+ action: &'static dyn Action,
+ focus_handle: FocusHandle,
+) -> IconButton {
+ let action_for_dispatch = action;
+ IconButton::new(id, icon)
+ .style(ButtonStyle::Subtle)
+ .shape(IconButtonShape::Square)
+ .disabled(disabled)
+ .on_click({
+ let focus_handle = focus_handle.clone();
+ move |_, window, cx| {
+ if !focus_handle.is_focused(window) {
+ window.focus(&focus_handle, cx);
+ }
+ window.dispatch_action(action_for_dispatch.boxed_clone(), cx);
+ }
+ })
+ .tooltip(move |_window, cx| Tooltip::for_action_in(tooltip, action, &focus_handle, cx))
+}
+
+fn collect_markdowns(
+ entry_ix: usize,
+ entry: &AgentThreadEntry,
+ entry_view_state: &EntryViewState,
+ cx: &App,
+) -> Vec<Entity<Markdown>> {
+ let mut out = Vec::new();
+ match entry {
+ AgentThreadEntry::UserMessage(_) => {}
+ AgentThreadEntry::AssistantMessage(message) => {
+ for (chunk_ix, chunk) in message.chunks.iter().enumerate() {
+ match chunk {
+ AssistantMessageChunk::Message { block } => {
+ if let Some(md) = block.markdown() {
+ out.push(md.clone());
+ }
+ }
+ AssistantMessageChunk::Thought { block }
+ if entry_view_state
+ .thinking_block_state((entry_ix, chunk_ix), cx)
+ .0 =>
+ {
+ if let Some(md) = block.markdown() {
+ out.push(md.clone());
+ }
+ }
+ AssistantMessageChunk::Thought { .. } => {}
+ }
+ }
+ }
+ AgentThreadEntry::ToolCall(tool_call) => {
+ out.push(tool_call.label.clone());
+ if entry_view_state.is_tool_call_expanded(&tool_call.id) {
+ out.extend(
+ tool_call
+ .content
+ .iter()
+ .filter_map(|content| match content {
+ ToolCallContent::ContentBlock(ContentBlock::Markdown { markdown }) => {
+ Some(markdown.clone())
+ }
+ ToolCallContent::ContentBlock(
+ ContentBlock::Empty
+ | ContentBlock::ResourceLink { .. }
+ | ContentBlock::Image { .. },
+ )
+ | ToolCallContent::Diff(_)
+ | ToolCallContent::Terminal(_) => None,
+ }),
+ );
+ }
+ }
+ AgentThreadEntry::CompletedPlan(entries) => {
+ out.extend(entries.iter().map(|e| e.content.clone()))
+ }
+ AgentThreadEntry::ContextCompaction(compaction)
+ if entry_view_state.is_compaction_expanded(entry_ix) =>
+ {
+ if let Some(summary) = &compaction.summary {
+ out.push(summary.clone());
+ }
+ }
+ AgentThreadEntry::ContextCompaction(_) => {}
+ }
+ out
+}
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 03fedd13557..8028b9bde3a 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -1,6 +1,7 @@
use crate::{
DEFAULT_THREAD_TITLE, SelectPermissionGranularity,
agent_configuration::configure_context_server_modal::default_markdown_style,
+ conversation_view::thread_search_bar::{ThreadSearchBar, ThreadSearchBarEvent},
open_abs_path_at_point,
thread_metadata_store::{ThreadId, ThreadMetadataStore},
};
@@ -576,18 +577,9 @@ pub struct ThreadView {
thread_feedback: ThreadFeedbackState,
pub list_state: ListState,
pub session_capabilities: SharedSessionCapabilities,
- /// Tracks which tool calls have their content/output expanded.
- /// Used for showing/hiding tool call results, terminal output, etc.
- pub expanded_tool_calls: HashSet<acp::ToolCallId>,
pub expanded_tool_call_raw_inputs: HashSet<acp::ToolCallId>,
collapsed_sandbox_authorization_details: HashSet<acp::ToolCallId>,
collapsed_sandbox_network_details: HashSet<acp::ToolCallId>,
- pub expanded_thinking_blocks: HashSet<(usize, usize)>,
- auto_expanded_thinking_block: Option<(usize, usize)>,
- user_toggled_thinking_blocks: HashSet<(usize, usize)>,
- /// Tracks which context compaction entries (by entry index) have their
- /// summary expanded.
- expanded_compactions: HashSet<usize>,
pub subagent_scroll_handles: RefCell<HashMap<acp::SessionId, ScrollHandle>>,
pub edits_expanded: bool,
pub plan_expanded: bool,
@@ -634,6 +626,8 @@ pub struct ThreadView {
/// dropped from this set so a future regression of the same kind would
/// re-show.
dismissed_skill_loading_issues: HashSet<SkillLoadingIssue>,
+ pub(crate) thread_search_bar: Option<Entity<super::thread_search_bar::ThreadSearchBar>>,
+ pub(crate) thread_search_visible: bool,
}
impl Focusable for ThreadView {
fn focus_handle(&self, cx: &App) -> FocusHandle {
@@ -964,14 +958,9 @@ impl ThreadView {
token_limit_callout_dismissed: false,
last_token_limit_telemetry: None,
thread_feedback: Default::default(),
- expanded_tool_calls: HashSet::default(),
expanded_tool_call_raw_inputs: HashSet::default(),
collapsed_sandbox_authorization_details: HashSet::default(),
collapsed_sandbox_network_details: HashSet::default(),
- expanded_thinking_blocks: HashSet::default(),
- auto_expanded_thinking_block: None,
- user_toggled_thinking_blocks: HashSet::default(),
- expanded_compactions: HashSet::default(),
subagent_scroll_handles: RefCell::new(HashMap::default()),
edits_expanded: false,
plan_expanded: false,
@@ -1008,6 +997,8 @@ impl ThreadView {
generating_indicator_in_list: false,
skill_loading_issues: Vec::new(),
dismissed_skill_loading_issues: HashSet::default(),
+ thread_search_bar: None,
+ thread_search_visible: false,
};
this.sync_generating_indicator(cx);
@@ -1190,16 +1181,22 @@ impl ThreadView {
match &event.view_event {
ViewEvent::NewDiff(tool_call_id) => {
if AgentSettings::get_global(cx).expand_edit_card {
- self.expanded_tool_calls.insert(tool_call_id.clone());
+ self.entry_view_state.update(cx, |state, _cx| {
+ state.expand_tool_call(tool_call_id.clone());
+ });
}
}
ViewEvent::NewTerminal(tool_call_id) => {
if AgentSettings::get_global(cx).expand_terminal_card {
- self.expanded_tool_calls.insert(tool_call_id.clone());
+ self.entry_view_state.update(cx, |state, _cx| {
+ state.expand_tool_call(tool_call_id.clone());
+ });
}
}
ViewEvent::TerminalMovedToBackground(tool_call_id) => {
- self.expanded_tool_calls.remove(tool_call_id);
+ self.entry_view_state.update(cx, |state, _cx| {
+ state.collapse_tool_call(tool_call_id);
+ });
}
ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
if let Some(AgentThreadEntry::UserMessage(user_message)) =
@@ -3681,7 +3678,10 @@ impl ThreadView {
) -> AnyElement {
let is_compacting = compaction.is_in_progress();
let summary = compaction.summary.clone();
- let is_expanded = self.expanded_compactions.contains(&entry_ix);
+ let is_expanded = self
+ .entry_view_state
+ .read(cx)
+ .is_compaction_expanded(entry_ix);
let id = format!("context-compaction-{entry_ix}");
let header_label = match compaction.status {
@@ -3715,8 +3715,8 @@ impl ThreadView {
.color(Color::Muted),
)
.on_click(cx.listener(
- move |this, _event: &ClickEvent, _window, cx| {
- this.toggle_compaction_expansion(entry_ix, cx);
+ move |this, _event: &ClickEvent, window, cx| {
+ this.toggle_compaction_expansion(entry_ix, window, cx);
},
))
}),
@@ -3761,8 +3761,14 @@ impl ThreadView {
.full_width()
.on_click(
cx.listener(
- move |this, _event: &ClickEvent, _window, cx| {
- this.expanded_compactions.remove(&entry_ix);
+ move |this, _event: &ClickEvent, window, cx| {
+ this.entry_view_state.update(
+ cx,
+ |state, _cx| {
+ state.collapse_compaction(entry_ix);
+ },
+ );
+ this.refresh_thread_search(window, cx);
cx.notify();
},
),
@@ -3774,10 +3780,16 @@ impl ThreadView {
.into_any()
}
- fn toggle_compaction_expansion(&mut self, entry_ix: usize, cx: &mut Context<Self>) {
- if !self.expanded_compactions.remove(&entry_ix) {
- self.expanded_compactions.insert(entry_ix);
- }
+ fn toggle_compaction_expansion(
+ &mut self,
+ entry_ix: usize,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.entry_view_state.update(cx, |state, _cx| {
+ state.toggle_compaction_expansion(entry_ix);
+ });
+ self.refresh_thread_search(window, cx);
cx.notify();
}
@@ -6300,6 +6312,85 @@ impl ThreadView {
}
}
+ fn refresh_thread_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if !self.thread_search_visible {
+ return;
+ }
+ if let Some(bar) = self.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.update_matches(window, cx));
+ }
+ }
+
+ pub(crate) fn toggle_search(
+ &mut self,
+ _: &crate::ToggleSearch,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.thread_search_bar.is_none() {
+ let thread = self.thread.clone();
+ let view = cx.entity().downgrade();
+ let on_activate =
+ Arc::new(move |entry_ix: usize, _window: &mut Window, cx: &mut App| {
+ // Avoid re-entering `ThreadView` when search navigation is forwarded
+ // from a `ThreadView` action handler.
+ let view = view.clone();
+ cx.defer(move |cx| {
+ view.update(cx, |this, cx| {
+ this.list_state.scroll_to(gpui::ListOffset {
+ item_ix: entry_ix,
+ offset_in_item: gpui::px(0.),
+ });
+ cx.notify();
+ })
+ .ok();
+ });
+ });
+ let search_bar = cx.new(|cx| {
+ ThreadSearchBar::new(
+ thread,
+ self.entry_view_state.clone(),
+ on_activate,
+ window,
+ cx,
+ )
+ });
+ self._subscriptions.push(cx.subscribe_in(
+ &search_bar,
+ window,
+ |this, _bar, event, window, cx| {
+ if matches!(event, ThreadSearchBarEvent::Dismissed) {
+ this.thread_search_visible = false;
+ this.message_editor.focus_handle(cx).focus(window, cx);
+ cx.notify();
+ }
+ },
+ ));
+ self.thread_search_bar = Some(search_bar);
+ }
+
+ // Re-focus an open bar unless it already owns focus.
+ let search_bar_focused = self
+ .thread_search_bar
+ .as_ref()
+ .is_some_and(|bar| bar.focus_handle(cx).contains_focused(window, cx));
+
+ if self.thread_search_visible && search_bar_focused {
+ if let Some(bar) = &self.thread_search_bar {
+ bar.update(cx, |bar, cx| bar.clear_highlights(cx));
+ }
+ self.thread_search_visible = false;
+ self.message_editor.focus_handle(cx).focus(window, cx);
+ cx.notify();
+ } else {
+ self.thread_search_visible = true;
+ if let Some(bar) = self.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.focus_and_refresh(window, cx));
+ }
+ cx.notify();
+ }
+ }
+
pub fn open_thread_as_markdown(
&self,
workspace: Entity<Workspace>,
@@ -6444,104 +6535,35 @@ impl ThreadView {
}
pub(crate) fn auto_expand_streaming_thought(&mut self, cx: &mut Context<Self>) {
- let thinking_display = AgentSettings::get_global(cx).thinking_display;
-
- if !matches!(
- thinking_display,
- ThinkingBlockDisplay::Auto | ThinkingBlockDisplay::Preview
- ) {
- return;
- }
-
- let key = {
- let thread = self.thread.read(cx);
+ let thread = self.thread.clone();
+ let changed = self.entry_view_state.update(cx, |state, cx| {
+ let thread = thread.read(cx);
if thread.status() != ThreadStatus::Generating {
- return;
+ return false;
}
- let entries = thread.entries();
- let last_ix = entries.len().saturating_sub(1);
- match entries.get(last_ix) {
- Some(AgentThreadEntry::AssistantMessage(msg)) => match msg.chunks.last() {
- Some(AssistantMessageChunk::Thought { .. }) => {
- Some((last_ix, msg.chunks.len() - 1))
- }
- _ => None,
- },
- _ => None,
- }
- };
-
- if let Some(key) = key {
- if self.auto_expanded_thinking_block != Some(key) {
- self.auto_expanded_thinking_block = Some(key);
- self.expanded_thinking_blocks.insert(key);
- cx.notify();
- }
- } else if self.auto_expanded_thinking_block.is_some() {
- if thinking_display == ThinkingBlockDisplay::Auto {
- if let Some(key) = self.auto_expanded_thinking_block {
- if !self.user_toggled_thinking_blocks.contains(&key) {
- self.expanded_thinking_blocks.remove(&key);
- }
- }
- }
- self.auto_expanded_thinking_block = None;
+ state.auto_expand_streaming_thought(thread, cx)
+ });
+ if changed {
cx.notify();
}
}
- pub(crate) fn clear_auto_expand_tracking(&mut self) {
- self.auto_expanded_thinking_block = None;
+ pub(crate) fn clear_auto_expand_tracking(&mut self, cx: &mut Context<Self>) {
+ self.entry_view_state.update(cx, |state, _cx| {
+ state.clear_auto_expand_tracking();
+ });
}
- fn toggle_thinking_block_expansion(&mut self, key: (usize, usize), cx: &mut Context<Self>) {
- let thinking_display = AgentSettings::get_global(cx).thinking_display;
-
- match thinking_display {
- ThinkingBlockDisplay::Auto => {
- let is_open = self.expanded_thinking_blocks.contains(&key)
- || self.user_toggled_thinking_blocks.contains(&key);
-
- if is_open {
- self.expanded_thinking_blocks.remove(&key);
- self.user_toggled_thinking_blocks.remove(&key);
- } else {
- self.expanded_thinking_blocks.insert(key);
- self.user_toggled_thinking_blocks.insert(key);
- }
- }
- ThinkingBlockDisplay::Preview => {
- let is_user_expanded = self.user_toggled_thinking_blocks.contains(&key);
- let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
-
- if is_user_expanded {
- self.user_toggled_thinking_blocks.remove(&key);
- self.expanded_thinking_blocks.remove(&key);
- } else if is_in_expanded_set {
- self.user_toggled_thinking_blocks.insert(key);
- } else {
- self.expanded_thinking_blocks.insert(key);
- self.user_toggled_thinking_blocks.insert(key);
- }
- }
- ThinkingBlockDisplay::AlwaysExpanded => {
- if self.user_toggled_thinking_blocks.contains(&key) {
- self.user_toggled_thinking_blocks.remove(&key);
- } else {
- self.user_toggled_thinking_blocks.insert(key);
- }
- }
- ThinkingBlockDisplay::AlwaysCollapsed => {
- if self.user_toggled_thinking_blocks.contains(&key) {
- self.user_toggled_thinking_blocks.remove(&key);
- self.expanded_thinking_blocks.remove(&key);
- } else {
- self.expanded_thinking_blocks.insert(key);
- self.user_toggled_thinking_blocks.insert(key);
- }
- }
- }
-
+ fn toggle_thinking_block_expansion(
+ &mut self,
+ key: (usize, usize),
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.entry_view_state.update(cx, |state, cx| {
+ state.toggle_thinking_block_expansion(key, cx);
+ });
+ self.refresh_thread_search(window, cx);
cx.notify();
}
@@ -6558,29 +6580,10 @@ impl ThreadView {
let key = (entry_ix, chunk_ix);
- let thinking_display = AgentSettings::get_global(cx).thinking_display;
- let is_user_toggled = self.user_toggled_thinking_blocks.contains(&key);
- let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
-
- let (is_open, is_constrained) = match thinking_display {
- ThinkingBlockDisplay::Auto => {
- let is_open = is_user_toggled || is_in_expanded_set;
- (is_open, false)
- }
- ThinkingBlockDisplay::Preview => {
- let is_open = is_user_toggled || is_in_expanded_set;
- let is_constrained = is_in_expanded_set && !is_user_toggled;
- (is_open, is_constrained)
- }
- ThinkingBlockDisplay::AlwaysExpanded => (!is_user_toggled, false),
- ThinkingBlockDisplay::AlwaysCollapsed => (is_user_toggled, false),
- };
-
- let should_auto_scroll = self.auto_expanded_thinking_block == Some(key);
-
- let scroll_handle = self
- .entry_view_state
- .read(cx)
+ let entry_view_state = self.entry_view_state.read(cx);
+ let (is_open, is_constrained) = entry_view_state.thinking_block_state(key, cx);
+ let should_auto_scroll = entry_view_state.is_auto_expanded_thinking_block(key);
+ let scroll_handle = entry_view_state
.entry(entry_ix)
.and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
@@ -6624,14 +6627,12 @@ impl ThreadView {
.opened_icon(IconName::ChevronUp)
.closed_icon(IconName::ChevronDown)
.visible_on_hover(&card_header_id)
- .on_click(cx.listener(
- move |this, _event: &ClickEvent, _window, cx| {
- this.toggle_thinking_block_expansion(key, cx);
- },
- )),
+ .on_click(cx.listener(move |this, _event: &ClickEvent, window, cx| {
+ this.toggle_thinking_block_expansion(key, window, cx);
+ })),
)
- .on_click(cx.listener(move |this, _event: &ClickEvent, _window, cx| {
- this.toggle_thinking_block_expansion(key, cx);
+ .on_click(cx.listener(move |this, _event: &ClickEvent, window, cx| {
+ this.toggle_thinking_block_expansion(key, window, cx);
})),
)
.when(is_open, |this| {
@@ -7012,7 +7013,10 @@ impl ThreadView {
cx,
);
- let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
+ let is_expanded = self
+ .entry_view_state
+ .read(cx)
+ .is_tool_call_expanded(&tool_call.id);
let header = h_flex()
.id(header_id)
@@ -7049,12 +7053,11 @@ impl ThreadView {
.visible_on_hover(&header_group)
.on_click(cx.listener({
let id = tool_call.id.clone();
- move |this, _event, _window, cx| {
- if is_expanded {
- this.expanded_tool_calls.remove(&id);
- } else {
- this.expanded_tool_calls.insert(id.clone());
- }
+ move |this, _event, window, cx| {
+ this.entry_view_state.update(cx, |state, _cx| {
+ state.toggle_tool_call_expansion(&id);
+ });
+ this.refresh_thread_search(window, cx);
cx.notify();
}
})),
@@ -7463,7 +7466,10 @@ impl ThreadView {
let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
- let mut is_open = self.expanded_tool_calls.contains(&tool_call.id);
+ let mut is_open = self
+ .entry_view_state
+ .read(cx)
+ .is_tool_call_expanded(&tool_call.id);
is_open |= needs_confirmation;
@@ -7692,8 +7698,14 @@ impl ThreadView {
.style(ButtonStyle::Outlined)
.icon_color(Color::Muted)
.on_click(cx.listener({
- move |this: &mut Self, _, _, cx: &mut Context<Self>| {
- this.expanded_tool_calls.remove(&tool_call_id);
+ move |this: &mut Self,
+ _,
+ window,
+ cx: &mut Context<Self>| {
+ this.entry_view_state.update(cx, |state, _cx| {
+ state.collapse_tool_call(&tool_call_id);
+ });
+ this.refresh_thread_search(window, cx);
cx.notify();
}
})),
@@ -7796,15 +7808,18 @@ impl ThreadView {
let id = tool_call.id.clone();
move |this: &mut Self,
_,
- _,
+ window,
cx: &mut Context<Self>| {
- if is_open {
- this.expanded_tool_calls
- .remove(&id);
- } else {
- this.expanded_tool_calls
- .insert(id.clone());
- }
+ this.entry_view_state.update(
+ cx,
+ |state, _cx| {
+ state
+ .toggle_tool_call_expansion(
+ &id,
+ );
+ },
+ );
+ this.refresh_thread_search(window, cx);
cx.notify();
}
})),
@@ -9494,7 +9509,10 @@ impl ThreadView {
})
.is_some();
- let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
+ let is_expanded = self
+ .entry_view_state
+ .read(cx)
+ .is_tool_call_expanded(&tool_call.id);
let files_changed = changed_buffers.len();
let diff_stats = DiffStats::all_files(changed_buffers, cx);
@@ -9675,15 +9693,13 @@ impl ThreadView {
)
.on_click(cx.listener({
let tool_call_id = tool_call.id.clone();
- move |this, _, _, cx| {
- if this.expanded_tool_calls.contains(&tool_call_id) {
- this.expanded_tool_calls.remove(&tool_call_id);
- } else {
- this.expanded_tool_calls
- .insert(tool_call_id.clone());
- }
+ move |this, _, window, cx| {
let expanded =
- this.expanded_tool_calls.contains(&tool_call_id);
+ this.entry_view_state.update(cx, |state, _cx| {
+ state.toggle_tool_call_expansion(&tool_call_id);
+ state.is_tool_call_expanded(&tool_call_id)
+ });
+ this.refresh_thread_search(window, cx);
telemetry::event!("Subagent Toggled", expanded);
cx.notify();
}
@@ -10966,6 +10982,101 @@ impl Render for ThreadView {
this.cancel_generation(cx);
}
}))
+ .on_action(cx.listener(
+ |this, _: &super::thread_search_bar::DismissThreadSearch, window, cx| {
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.clear_highlights(cx));
+ }
+ this.thread_search_visible = false;
+ this.message_editor.focus_handle(cx).focus(window, cx);
+ cx.notify();
+ },
+ ))
+ // Esc can arrive as `editor::Cancel` from the query editor.
+ .on_action(
+ cx.listener(|this, _: &editor::actions::Cancel, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.clear_highlights(cx));
+ }
+ this.thread_search_visible = false;
+ this.message_editor.focus_handle(cx).focus(window, cx);
+ cx.notify();
+ }),
+ )
+ .on_action(cx.listener(
+ |this, action: &super::thread_search_bar::SelectNextThreadMatch, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.select_next_match(action, window, cx));
+ }
+ },
+ ))
+ .on_action(cx.listener(
+ |this, action: &super::thread_search_bar::SelectPreviousThreadMatch, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.select_prev_match(action, window, cx));
+ }
+ },
+ ))
+ .on_action(
+ cx.listener(|this, _: &search::ToggleCaseSensitive, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| {
+ bar.toggle_case_sensitive(&search::ToggleCaseSensitive, window, cx)
+ });
+ }
+ }),
+ )
+ .on_action(
+ cx.listener(|this, _: &search::ToggleWholeWord, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| {
+ bar.toggle_whole_word(&search::ToggleWholeWord, window, cx)
+ });
+ }
+ }),
+ )
+ .on_action(cx.listener(|this, _: &search::ToggleRegex, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| {
+ bar.toggle_regex(&search::ToggleRegex, window, cx)
+ });
+ }
+ }))
+ .on_action(
+ cx.listener(|this, action: &search::FocusSearch, window, cx| {
+ if !this.thread_search_visible {
+ cx.propagate();
+ return;
+ }
+ if let Some(bar) = this.thread_search_bar.clone() {
+ bar.update(cx, |bar, cx| bar.focus_search(action, window, cx));
+ }
+ }),
+ )
.on_action(cx.listener(|this, _: &workspace::GoBack, window, cx| {
if let Some(parent_session_id) = this.thread.read(cx).parent_session_id().cloned() {
this.server_view
@@ -10994,6 +11105,7 @@ impl Render for ThreadView {
.on_action(cx.listener(Self::scroll_output_to_bottom))
.on_action(cx.listener(Self::scroll_output_to_previous_message))
.on_action(cx.listener(Self::scroll_output_to_next_message))
+ .on_action(cx.listener(Self::toggle_search))
.on_action(cx.listener(|this, _: &ToggleFastMode, window, cx| {
this.toggle_fast_mode(window, cx);
}))
@@ -11163,6 +11275,12 @@ impl Render for ThreadView {
}))
.size_full()
.children(self.render_subagent_titlebar(cx))
+ .when_some(
+ self.thread_search_visible
+ .then(|| self.thread_search_bar.clone())
+ .flatten(),
+ |this, bar| this.child(bar),
+ )
.child(conversation)
.children(self.render_multi_root_callout(cx))
.children(self.render_activity_bar(window, cx))
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index 68627d1ec87..f77baba6470 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -1,9 +1,10 @@
use std::ops::Range;
-use acp_thread::{AcpThread, AgentThreadEntry};
+use acp_thread::{AcpThread, AgentThreadEntry, AssistantMessageChunk};
use agent::ThreadStore;
use agent_client_protocol::schema as acp;
-use collections::HashMap;
+use agent_settings::AgentSettings;
+use collections::{HashMap, HashSet};
use editor::{Editor, EditorEvent, EditorMode, MinimapVisibility, SizingBehavior};
use gpui::{
AnyEntity, App, AppContext as _, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
@@ -12,7 +13,7 @@ use gpui::{
use language::language_settings::SoftWrap;
use project::{AgentId, Project, project_settings::DiagnosticSeverity};
use rope::Point;
-use settings::Settings as _;
+use settings::{Settings as _, ThinkingBlockDisplay};
use terminal_view::TerminalView;
use theme_settings::ThemeSettings;
use ui::{Context, TextSize};
@@ -20,6 +21,18 @@ use workspace::Workspace;
use crate::message_editor::{MessageEditor, MessageEditorEvent, SharedSessionCapabilities};
+/// Maps an entry index through the removal of `removed` (a contiguous range of
+/// entries), returning `None` if the index referred to a removed entry.
+fn reindex_after_removal(index: usize, removed: &Range<usize>) -> Option<usize> {
+ if index < removed.start {
+ Some(index)
+ } else if index < removed.end {
+ None
+ } else {
+ Some(index - removed.len())
+ }
+}
+
pub struct EntryViewState {
workspace: WeakEntity<Workspace>,
project: WeakEntity<Project>,
@@ -27,6 +40,11 @@ pub struct EntryViewState {
entries: Vec<Entry>,
session_capabilities: SharedSessionCapabilities,
agent_id: AgentId,
+ expanded_thinking_blocks: HashSet<(usize, usize)>,
+ auto_expanded_thinking_block: Option<(usize, usize)>,
+ user_toggled_thinking_blocks: HashSet<(usize, usize)>,
+ expanded_compactions: HashSet<usize>,
+ expanded_tool_calls: HashSet<acp::ToolCallId>,
}
impl EntryViewState {
@@ -44,6 +62,158 @@ impl EntryViewState {
entries: Vec::new(),
session_capabilities,
agent_id,
+ expanded_thinking_blocks: HashSet::default(),
+ auto_expanded_thinking_block: None,
+ user_toggled_thinking_blocks: HashSet::default(),
+ expanded_compactions: HashSet::default(),
+ expanded_tool_calls: HashSet::default(),
+ }
+ }
+
+ pub(crate) fn is_tool_call_expanded(&self, tool_call_id: &acp::ToolCallId) -> bool {
+ self.expanded_tool_calls.contains(tool_call_id)
+ }
+
+ pub(crate) fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId) {
+ self.expanded_tool_calls.insert(tool_call_id);
+ }
+
+ pub(crate) fn collapse_tool_call(&mut self, tool_call_id: &acp::ToolCallId) {
+ self.expanded_tool_calls.remove(tool_call_id);
+ }
+
+ pub(crate) fn toggle_tool_call_expansion(&mut self, tool_call_id: &acp::ToolCallId) {
+ if !self.expanded_tool_calls.remove(tool_call_id) {
+ self.expanded_tool_calls.insert(tool_call_id.clone());
+ }
+ }
+
+ pub(crate) fn is_compaction_expanded(&self, entry_ix: usize) -> bool {
+ self.expanded_compactions.contains(&entry_ix)
+ }
+
+ pub(crate) fn collapse_compaction(&mut self, entry_ix: usize) {
+ self.expanded_compactions.remove(&entry_ix);
+ }
+
+ pub(crate) fn toggle_compaction_expansion(&mut self, entry_ix: usize) {
+ if !self.expanded_compactions.remove(&entry_ix) {
+ self.expanded_compactions.insert(entry_ix);
+ }
+ }
+
+ pub(crate) fn clear_auto_expand_tracking(&mut self) {
+ self.auto_expanded_thinking_block = None;
+ }
+
+ pub(crate) fn is_auto_expanded_thinking_block(&self, key: (usize, usize)) -> bool {
+ self.auto_expanded_thinking_block == Some(key)
+ }
+
+ pub(crate) fn auto_expand_streaming_thought(&mut self, thread: &AcpThread, cx: &App) -> bool {
+ let thinking_display = AgentSettings::get_global(cx).thinking_display;
+
+ if !matches!(
+ thinking_display,
+ ThinkingBlockDisplay::Auto | ThinkingBlockDisplay::Preview
+ ) {
+ return false;
+ }
+
+ let last_ix = thread.entries().len().saturating_sub(1);
+ let key = match thread.entries().get(last_ix) {
+ Some(AgentThreadEntry::AssistantMessage(message)) => match message.chunks.last() {
+ Some(AssistantMessageChunk::Thought { .. }) => {
+ Some((last_ix, message.chunks.len() - 1))
+ }
+ _ => None,
+ },
+ _ => None,
+ };
+
+ if let Some(key) = key {
+ if self.auto_expanded_thinking_block != Some(key) {
+ self.auto_expanded_thinking_block = Some(key);
+ self.expanded_thinking_blocks.insert(key);
+ return true;
+ }
+ } else if self.auto_expanded_thinking_block.is_some() {
+ if thinking_display == ThinkingBlockDisplay::Auto
+ && let Some(key) = self.auto_expanded_thinking_block
+ && !self.user_toggled_thinking_blocks.contains(&key)
+ {
+ self.expanded_thinking_blocks.remove(&key);
+ }
+ self.auto_expanded_thinking_block = None;
+ return true;
+ }
+
+ false
+ }
+
+ pub(crate) fn toggle_thinking_block_expansion(&mut self, key: (usize, usize), cx: &App) {
+ match AgentSettings::get_global(cx).thinking_display {
+ ThinkingBlockDisplay::Auto => {
+ let is_open = self.expanded_thinking_blocks.contains(&key)
+ || self.user_toggled_thinking_blocks.contains(&key);
+
+ if is_open {
+ self.expanded_thinking_blocks.remove(&key);
+ self.user_toggled_thinking_blocks.remove(&key);
+ } else {
+ self.expanded_thinking_blocks.insert(key);
+ self.user_toggled_thinking_blocks.insert(key);
+ }
+ }
+ ThinkingBlockDisplay::Preview => {
+ let is_user_expanded = self.user_toggled_thinking_blocks.contains(&key);
+ let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
+
+ if is_user_expanded {
+ self.user_toggled_thinking_blocks.remove(&key);
+ self.expanded_thinking_blocks.remove(&key);
+ } else if is_in_expanded_set {
+ self.user_toggled_thinking_blocks.insert(key);
+ } else {
+ self.expanded_thinking_blocks.insert(key);
+ self.user_toggled_thinking_blocks.insert(key);
+ }
+ }
+ ThinkingBlockDisplay::AlwaysExpanded => {
+ if self.user_toggled_thinking_blocks.contains(&key) {
+ self.user_toggled_thinking_blocks.remove(&key);
+ } else {
+ self.user_toggled_thinking_blocks.insert(key);
+ }
+ }
+ ThinkingBlockDisplay::AlwaysCollapsed => {
+ if self.user_toggled_thinking_blocks.contains(&key) {
+ self.user_toggled_thinking_blocks.remove(&key);
+ self.expanded_thinking_blocks.remove(&key);
+ } else {
+ self.expanded_thinking_blocks.insert(key);
+ self.user_toggled_thinking_blocks.insert(key);
+ }
+ }
+ }
+ }
+
+ pub(crate) fn thinking_block_state(&self, key: (usize, usize), cx: &App) -> (bool, bool) {
+ let is_user_toggled = self.user_toggled_thinking_blocks.contains(&key);
+ let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
+
+ match AgentSettings::get_global(cx).thinking_display {
+ ThinkingBlockDisplay::Auto => {
+ let is_open = is_user_toggled || is_in_expanded_set;
+ (is_open, false)
+ }
+ ThinkingBlockDisplay::Preview => {
+ let is_open = is_user_toggled || is_in_expanded_set;
+ let is_constrained = is_in_expanded_set && !is_user_toggled;
+ (is_open, is_constrained)
+ }
+ ThinkingBlockDisplay::AlwaysExpanded => (!is_user_toggled, false),
+ ThinkingBlockDisplay::AlwaysCollapsed => (is_user_toggled, false),
}
}
@@ -249,7 +419,32 @@ impl EntryViewState {
}
pub fn remove(&mut self, range: Range<usize>) {
- self.entries.drain(range);
+ self.entries.drain(range.clone());
+
+ self.expanded_compactions = self
+ .expanded_compactions
+ .iter()
+ .filter_map(|&entry_ix| reindex_after_removal(entry_ix, &range))
+ .collect();
+ self.expanded_thinking_blocks = self
+ .expanded_thinking_blocks
+ .iter()
+ .filter_map(|&(entry_ix, chunk_ix)| {
+ reindex_after_removal(entry_ix, &range).map(|entry_ix| (entry_ix, chunk_ix))
+ })
+ .collect();
+ self.user_toggled_thinking_blocks = self
+ .user_toggled_thinking_blocks
+ .iter()
+ .filter_map(|&(entry_ix, chunk_ix)| {
+ reindex_after_removal(entry_ix, &range).map(|entry_ix| (entry_ix, chunk_ix))
+ })
+ .collect();
+ self.auto_expanded_thinking_block =
+ self.auto_expanded_thinking_block
+ .and_then(|(entry_ix, chunk_ix)| {
+ reindex_after_removal(entry_ix, &range).map(|entry_ix| (entry_ix, chunk_ix))
+ });
}
pub fn agent_ui_font_size_changed(&mut self, cx: &mut App) {
@@ -512,6 +707,23 @@ mod tests {
use util::path;
use workspace::{MultiWorkspace, PathList};
+ #[test]
+ fn test_reindex_after_removal() {
+ use super::reindex_after_removal;
+
+ // Entries before the removed range keep their index.
+ assert_eq!(reindex_after_removal(0, &(2..4)), Some(0));
+ assert_eq!(reindex_after_removal(1, &(2..4)), Some(1));
+ // Entries inside the removed range are dropped.
+ assert_eq!(reindex_after_removal(2, &(2..4)), None);
+ assert_eq!(reindex_after_removal(3, &(2..4)), None);
+ // Entries after the removed range slide down by its length.
+ assert_eq!(reindex_after_removal(4, &(2..4)), Some(2));
+ assert_eq!(reindex_after_removal(5, &(2..4)), Some(3));
+ // An empty removal range leaves indices untouched.
+ assert_eq!(reindex_after_removal(3, &(2..2)), Some(3));
+ }
+
#[gpui::test]
async fn test_diff_sync(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs
index ad32a9ac76a..0b38a944d52 100644
--- a/crates/agent_ui/src/message_editor.rs
+++ b/crates/agent_ui/src/message_editor.rs
@@ -698,7 +698,6 @@ impl MessageEditor {
.detach();
}
- #[cfg(test)]
pub(crate) fn editor(&self) -> &Entity<Editor> {
&self.editor
}
diff --git a/crates/gpui/src/elements/list.rs b/crates/gpui/src/elements/list.rs
index 28f47a6b7b0..85b38d5234e 100644
--- a/crates/gpui/src/elements/list.rs
+++ b/crates/gpui/src/elements/list.rs
@@ -1239,9 +1239,38 @@ impl StateInner {
&& autoscroll
{
if autoscroll_bounds.top() < bounds.top() {
+ let mut item_ix = item.index;
+ let mut offset_in_item = autoscroll_bounds.top() - item_origin.y;
+
+ // The requested top can sit above this item's own
+ // top. Walk into earlier items so the offset stays
+ // non-negative and no blank space appears above the
+ // list.
+ if offset_in_item < Pixels::ZERO {
+ let mut cursor = self.items.cursor::<Count>(());
+ cursor.seek(&Count(item_ix), Bias::Right);
+ while offset_in_item < Pixels::ZERO {
+ cursor.prev();
+ let Some(prev_item) = cursor.item() else {
+ offset_in_item = Pixels::ZERO;
+ break;
+ };
+ let size = prev_item.size().unwrap_or_else(|| {
+ let mut element = render_item(cursor.start().0, window, cx);
+ let item_available_size = size(
+ bounds.size.width.into(),
+ AvailableSpace::MinContent,
+ );
+ element.layout_as_root(item_available_size, window, cx)
+ });
+ item_ix = cursor.start().0;
+ offset_in_item += size.height;
+ }
+ }
+
return Err(ListOffset {
- item_ix: item.index,
- offset_in_item: autoscroll_bounds.top() - item_origin.y,
+ item_ix,
+ offset_in_item,
});
} else if autoscroll_bounds.bottom() > bounds.bottom() {
let mut cursor = self.items.cursor::<Count>(());
@@ -1638,10 +1667,63 @@ mod test {
use std::rc::Rc;
use crate::{
- self as gpui, AppContext, Context, Element, FollowMode, IntoElement, ListState, Render,
- Styled, TestAppContext, Window, div, list, point, px, size,
+ self as gpui, AppContext, Bounds, Context, Element, FollowMode, IntoElement, ListState,
+ Render, Styled, TestAppContext, Window, canvas, div, list, point, px, size,
};
+ #[gpui::test]
+ fn test_autoscroll_above_item_top_renders_items_above(cx: &mut TestAppContext) {
+ let cx = cx.add_empty_window();
+
+ let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
+ state.scroll_to(gpui::ListOffset {
+ item_ix: 2,
+ offset_in_item: px(0.),
+ });
+
+ struct TestView(ListState);
+ impl Render for TestView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ list(self.0.clone(), |ix, _, _| {
+ if ix == 2 {
+ // Request an autoscroll whose top sits 30px above item 2's
+ // own top, mimicking a scroll-margin overshoot.
+ canvas(
+ |bounds, window, _| {
+ window.request_autoscroll(Bounds::from_corners(
+ point(bounds.left(), bounds.top() - px(30.)),
+ point(bounds.right(), bounds.top() + px(5.)),
+ ));
+ },
+ |_, _, _, _| {},
+ )
+ .h(px(20.))
+ .w_full()
+ .into_any()
+ } else {
+ div().h(px(20.)).w_full().into_any()
+ }
+ })
+ .w_full()
+ .h_full()
+ }
+ }
+
+ cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
+ cx.new(|_| TestView(state.clone())).into_any_element()
+ });
+
+ // 30px above item 2's top, with 20px items, lands 10px into item 0.
+ let scroll_top = state.logical_scroll_top();
+ assert!(
+ scroll_top.offset_in_item >= px(0.),
+ "offset_in_item must never be negative (would leave blank space above), got {:?}",
+ scroll_top.offset_in_item,
+ );
+ assert_eq!(scroll_top.item_ix, 0);
+ assert_eq!(scroll_top.offset_in_item, px(10.));
+ }
+
#[gpui::test]
fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
let cx = cx.add_empty_window();
diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs
index 4a8d679b53b..50d6a7671ad 100644
--- a/crates/markdown/src/markdown.rs
+++ b/crates/markdown/src/markdown.rs
@@ -694,7 +694,7 @@ impl Markdown {
}
}
- pub fn source(&self) -> &str {
+ pub fn source(&self) -> &SharedString {
&self.source
}
@@ -762,7 +762,7 @@ impl Markdown {
}
pub fn reset(&mut self, source: SharedString, cx: &mut Context<Self>) {
- if source == self.source() {
+ if &source == self.source() {
return;
}
self.source = source;
diff --git a/crates/project/tests/integration/signature_help.rs b/crates/project/tests/integration/signature_help.rs
index 18c0eeb3448..a526bfed700 100644
--- a/crates/project/tests/integration/signature_help.rs
+++ b/crates/project/tests/integration/signature_help.rs
@@ -50,7 +50,7 @@ fn test_create_signature_help_markdown_string_1(cx: &mut TestAppContext) {
signature
.documentation
.unwrap()
- .update(cx, |documentation, _| documentation.source().to_owned()),
+ .update(cx, |documentation, _| documentation.source().to_string()),
"This is a test documentation",
)
}
@@ -96,7 +96,7 @@ fn test_create_signature_help_markdown_string_2(cx: &mut TestAppContext) {
signature
.documentation
.unwrap()
- .update(cx, |documentation, _| documentation.source().to_owned()),
+ .update(cx, |documentation, _| documentation.source().to_string()),
"This is a test documentation",
)
}
@@ -464,7 +464,7 @@ fn test_parameter_documentation(cx: &mut TestAppContext) {
.documentation
.as_ref()
.unwrap()
- .update(cx, |documentation, _| documentation.source().to_owned()),
+ .update(cx, |documentation, _| documentation.source().to_string()),
"The foo parameter",
);
assert_eq!(
@@ -472,7 +472,7 @@ fn test_parameter_documentation(cx: &mut TestAppContext) {
.documentation
.as_ref()
.unwrap()
- .update(cx, |documentation, _| documentation.source().to_owned()),
+ .update(cx, |documentation, _| documentation.source().to_string()),
"The bar parameter",
);