1use std::ops::Range;
2
3use super::thread_history::ThreadHistory;
4use acp_thread::{AcpThread, AgentThreadEntry};
5use agent::ThreadStore;
6use agent_client_protocol::ToolCallId;
7use collections::HashMap;
8use editor::{Editor, EditorEvent, EditorMode, MinimapVisibility, SizingBehavior};
9use gpui::{
10 AnyEntity, App, AppContext as _, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
11 ScrollHandle, TextStyleRefinement, WeakEntity, Window,
12};
13use language::language_settings::SoftWrap;
14use project::{AgentId, Project};
15use prompt_store::PromptStore;
16use rope::Point;
17use settings::Settings as _;
18use terminal_view::TerminalView;
19use theme::ThemeSettings;
20use ui::{Context, TextSize};
21use workspace::Workspace;
22
23use crate::message_editor::{MessageEditor, MessageEditorEvent, SharedSessionCapabilities};
24
25pub struct EntryViewState {
26 workspace: WeakEntity<Workspace>,
27 project: WeakEntity<Project>,
28 thread_store: Option<Entity<ThreadStore>>,
29 history: Option<WeakEntity<ThreadHistory>>,
30 prompt_store: Option<Entity<PromptStore>>,
31 entries: Vec<Entry>,
32 session_capabilities: SharedSessionCapabilities,
33 agent_id: AgentId,
34}
35
36impl EntryViewState {
37 pub fn new(
38 workspace: WeakEntity<Workspace>,
39 project: WeakEntity<Project>,
40 thread_store: Option<Entity<ThreadStore>>,
41 history: Option<WeakEntity<ThreadHistory>>,
42 prompt_store: Option<Entity<PromptStore>>,
43 session_capabilities: SharedSessionCapabilities,
44 agent_id: AgentId,
45 ) -> Self {
46 Self {
47 workspace,
48 project,
49 thread_store,
50 history,
51 prompt_store,
52 entries: Vec::new(),
53 session_capabilities,
54 agent_id,
55 }
56 }
57
58 pub fn entry(&self, index: usize) -> Option<&Entry> {
59 self.entries.get(index)
60 }
61
62 pub fn sync_entry(
63 &mut self,
64 index: usize,
65 thread: &Entity<AcpThread>,
66 window: &mut Window,
67 cx: &mut Context<Self>,
68 ) {
69 let Some(thread_entry) = thread.read(cx).entries().get(index) else {
70 return;
71 };
72
73 match thread_entry {
74 AgentThreadEntry::UserMessage(message) => {
75 let has_id = message.id.is_some();
76 let is_subagent = thread.read(cx).parent_session_id().is_some();
77 let chunks = message.chunks.clone();
78 if let Some(Entry::UserMessage(editor)) = self.entries.get_mut(index) {
79 if !editor.focus_handle(cx).is_focused(window) {
80 // Only update if we are not editing.
81 // If we are, cancelling the edit will set the message to the newest content.
82 editor.update(cx, |editor, cx| {
83 editor.set_message(chunks, window, cx);
84 });
85 }
86 } else {
87 let message_editor = cx.new(|cx| {
88 let mut editor = MessageEditor::new(
89 self.workspace.clone(),
90 self.project.clone(),
91 self.thread_store.clone(),
92 self.history.clone(),
93 self.prompt_store.clone(),
94 self.session_capabilities.clone(),
95 self.agent_id.clone(),
96 "Edit message - @ to include context",
97 editor::EditorMode::AutoHeight {
98 min_lines: 1,
99 max_lines: None,
100 },
101 window,
102 cx,
103 );
104 if !has_id || is_subagent {
105 editor.set_read_only(true, cx);
106 }
107 editor.set_message(chunks, window, cx);
108 editor
109 });
110 cx.subscribe(&message_editor, move |_, editor, event, cx| {
111 cx.emit(EntryViewEvent {
112 entry_index: index,
113 view_event: ViewEvent::MessageEditorEvent(editor, event.clone()),
114 })
115 })
116 .detach();
117 self.set_entry(index, Entry::UserMessage(message_editor));
118 }
119 }
120 AgentThreadEntry::ToolCall(tool_call) => {
121 let id = tool_call.id.clone();
122 let terminals = tool_call.terminals().cloned().collect::<Vec<_>>();
123 let diffs = tool_call.diffs().cloned().collect::<Vec<_>>();
124
125 let views = if let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) {
126 &mut tool_call.content
127 } else {
128 self.set_entry(
129 index,
130 Entry::ToolCall(ToolCallEntry {
131 content: HashMap::default(),
132 }),
133 );
134 let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) else {
135 unreachable!()
136 };
137 &mut tool_call.content
138 };
139
140 let is_tool_call_completed =
141 matches!(tool_call.status, acp_thread::ToolCallStatus::Completed);
142
143 for terminal in terminals {
144 match views.entry(terminal.entity_id()) {
145 collections::hash_map::Entry::Vacant(entry) => {
146 let element = create_terminal(
147 self.workspace.clone(),
148 self.project.clone(),
149 terminal.clone(),
150 window,
151 cx,
152 )
153 .into_any();
154 cx.emit(EntryViewEvent {
155 entry_index: index,
156 view_event: ViewEvent::NewTerminal(id.clone()),
157 });
158 entry.insert(element);
159 }
160 collections::hash_map::Entry::Occupied(_entry) => {
161 if is_tool_call_completed && terminal.read(cx).output().is_none() {
162 cx.emit(EntryViewEvent {
163 entry_index: index,
164 view_event: ViewEvent::TerminalMovedToBackground(id.clone()),
165 });
166 }
167 }
168 }
169 }
170
171 for diff in diffs {
172 views.entry(diff.entity_id()).or_insert_with(|| {
173 let editor = create_editor_diff(diff.clone(), window, cx);
174 cx.subscribe(&editor, {
175 let diff = diff.clone();
176 let entry_index = index;
177 move |_this, _editor, event: &EditorEvent, cx| {
178 if let EditorEvent::OpenExcerptsRequested {
179 selections_by_buffer,
180 split,
181 } = event
182 {
183 let multibuffer = diff.read(cx).multibuffer();
184 if let Some((buffer_id, (ranges, _))) =
185 selections_by_buffer.iter().next()
186 {
187 if let Some(buffer) =
188 multibuffer.read(cx).buffer(*buffer_id)
189 {
190 if let Some(range) = ranges.first() {
191 let point =
192 buffer.read(cx).offset_to_point(range.start.0);
193 if let Some(path) = diff.read(cx).file_path(cx) {
194 cx.emit(EntryViewEvent {
195 entry_index,
196 view_event: ViewEvent::OpenDiffLocation {
197 path,
198 position: point,
199 split: *split,
200 },
201 });
202 }
203 }
204 }
205 }
206 }
207 }
208 })
209 .detach();
210 cx.emit(EntryViewEvent {
211 entry_index: index,
212 view_event: ViewEvent::NewDiff(id.clone()),
213 });
214 editor.into_any()
215 });
216 }
217 }
218 AgentThreadEntry::AssistantMessage(message) => {
219 let entry = if let Some(Entry::AssistantMessage(entry)) =
220 self.entries.get_mut(index)
221 {
222 entry
223 } else {
224 self.set_entry(
225 index,
226 Entry::AssistantMessage(AssistantMessageEntry {
227 scroll_handles_by_chunk_index: HashMap::default(),
228 focus_handle: cx.focus_handle(),
229 }),
230 );
231 let Some(Entry::AssistantMessage(entry)) = self.entries.get_mut(index) else {
232 unreachable!()
233 };
234 entry
235 };
236 entry.sync(message);
237 }
238 };
239 }
240
241 fn set_entry(&mut self, index: usize, entry: Entry) {
242 if index == self.entries.len() {
243 self.entries.push(entry);
244 } else {
245 self.entries[index] = entry;
246 }
247 }
248
249 pub fn remove(&mut self, range: Range<usize>) {
250 self.entries.drain(range);
251 }
252
253 pub fn agent_ui_font_size_changed(&mut self, cx: &mut App) {
254 for entry in self.entries.iter() {
255 match entry {
256 Entry::UserMessage { .. } | Entry::AssistantMessage { .. } => {}
257 Entry::ToolCall(ToolCallEntry { content }) => {
258 for view in content.values() {
259 if let Ok(diff_editor) = view.clone().downcast::<Editor>() {
260 diff_editor.update(cx, |diff_editor, cx| {
261 diff_editor.set_text_style_refinement(
262 diff_editor_text_style_refinement(cx),
263 );
264 cx.notify();
265 })
266 }
267 }
268 }
269 }
270 }
271 }
272}
273
274impl EventEmitter<EntryViewEvent> for EntryViewState {}
275
276pub struct EntryViewEvent {
277 pub entry_index: usize,
278 pub view_event: ViewEvent,
279}
280
281pub enum ViewEvent {
282 NewDiff(ToolCallId),
283 NewTerminal(ToolCallId),
284 TerminalMovedToBackground(ToolCallId),
285 MessageEditorEvent(Entity<MessageEditor>, MessageEditorEvent),
286 OpenDiffLocation {
287 path: String,
288 position: Point,
289 split: bool,
290 },
291}
292
293#[derive(Debug)]
294pub struct AssistantMessageEntry {
295 scroll_handles_by_chunk_index: HashMap<usize, ScrollHandle>,
296 focus_handle: FocusHandle,
297}
298
299impl AssistantMessageEntry {
300 pub fn scroll_handle_for_chunk(&self, ix: usize) -> Option<ScrollHandle> {
301 self.scroll_handles_by_chunk_index.get(&ix).cloned()
302 }
303
304 pub fn sync(&mut self, message: &acp_thread::AssistantMessage) {
305 if let Some(acp_thread::AssistantMessageChunk::Thought { .. }) = message.chunks.last() {
306 let ix = message.chunks.len() - 1;
307 let handle = self.scroll_handles_by_chunk_index.entry(ix).or_default();
308 handle.scroll_to_bottom();
309 }
310 }
311}
312
313#[derive(Debug)]
314pub struct ToolCallEntry {
315 content: HashMap<EntityId, AnyEntity>,
316}
317
318#[derive(Debug)]
319pub enum Entry {
320 UserMessage(Entity<MessageEditor>),
321 AssistantMessage(AssistantMessageEntry),
322 ToolCall(ToolCallEntry),
323}
324
325impl Entry {
326 pub fn focus_handle(&self, cx: &App) -> Option<FocusHandle> {
327 match self {
328 Self::UserMessage(editor) => Some(editor.read(cx).focus_handle(cx)),
329 Self::AssistantMessage(message) => Some(message.focus_handle.clone()),
330 Self::ToolCall(_) => None,
331 }
332 }
333
334 pub fn message_editor(&self) -> Option<&Entity<MessageEditor>> {
335 match self {
336 Self::UserMessage(editor) => Some(editor),
337 Self::AssistantMessage(_) | Self::ToolCall(_) => None,
338 }
339 }
340
341 pub fn editor_for_diff(&self, diff: &Entity<acp_thread::Diff>) -> Option<Entity<Editor>> {
342 self.content_map()?
343 .get(&diff.entity_id())
344 .cloned()
345 .map(|entity| entity.downcast::<Editor>().unwrap())
346 }
347
348 pub fn terminal(
349 &self,
350 terminal: &Entity<acp_thread::Terminal>,
351 ) -> Option<Entity<TerminalView>> {
352 self.content_map()?
353 .get(&terminal.entity_id())
354 .cloned()
355 .map(|entity| entity.downcast::<TerminalView>().unwrap())
356 }
357
358 pub fn scroll_handle_for_assistant_message_chunk(
359 &self,
360 chunk_ix: usize,
361 ) -> Option<ScrollHandle> {
362 match self {
363 Self::AssistantMessage(message) => message.scroll_handle_for_chunk(chunk_ix),
364 Self::UserMessage(_) | Self::ToolCall(_) => None,
365 }
366 }
367
368 fn content_map(&self) -> Option<&HashMap<EntityId, AnyEntity>> {
369 match self {
370 Self::ToolCall(ToolCallEntry { content }) => Some(content),
371 _ => None,
372 }
373 }
374
375 #[cfg(test)]
376 pub fn has_content(&self) -> bool {
377 match self {
378 Self::ToolCall(ToolCallEntry { content }) => !content.is_empty(),
379 Self::UserMessage(_) | Self::AssistantMessage(_) => false,
380 }
381 }
382}
383
384fn create_terminal(
385 workspace: WeakEntity<Workspace>,
386 project: WeakEntity<Project>,
387 terminal: Entity<acp_thread::Terminal>,
388 window: &mut Window,
389 cx: &mut App,
390) -> Entity<TerminalView> {
391 cx.new(|cx| {
392 let mut view = TerminalView::new(
393 terminal.read(cx).inner().clone(),
394 workspace,
395 None,
396 project,
397 window,
398 cx,
399 );
400 view.set_embedded_mode(Some(1000), cx);
401 view
402 })
403}
404
405fn create_editor_diff(
406 diff: Entity<acp_thread::Diff>,
407 window: &mut Window,
408 cx: &mut App,
409) -> Entity<Editor> {
410 cx.new(|cx| {
411 let mut editor = Editor::new(
412 EditorMode::Full {
413 scale_ui_elements_with_buffer_font_size: false,
414 show_active_line_background: false,
415 sizing_behavior: SizingBehavior::SizeByContent,
416 },
417 diff.read(cx).multibuffer().clone(),
418 None,
419 window,
420 cx,
421 );
422 editor.set_show_gutter(false, cx);
423 editor.disable_inline_diagnostics();
424 editor.disable_expand_excerpt_buttons(cx);
425 editor.set_show_vertical_scrollbar(false, cx);
426 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
427 editor.set_soft_wrap_mode(SoftWrap::None, cx);
428 editor.scroll_manager.set_forbid_vertical_scroll(true);
429 editor.set_show_indent_guides(false, cx);
430 editor.set_read_only(true);
431 editor.set_delegate_open_excerpts(true);
432 editor.set_show_breakpoints(false, cx);
433 editor.set_show_code_actions(false, cx);
434 editor.set_show_git_diff_gutter(false, cx);
435 editor.set_expand_all_diff_hunks(cx);
436 editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
437 editor
438 })
439}
440
441fn diff_editor_text_style_refinement(cx: &mut App) -> TextStyleRefinement {
442 TextStyleRefinement {
443 font_size: Some(
444 TextSize::Small
445 .rems(cx)
446 .to_pixels(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
447 .into(),
448 ),
449 ..Default::default()
450 }
451}
452
453#[cfg(test)]
454mod tests {
455 use std::path::Path;
456 use std::rc::Rc;
457 use std::sync::Arc;
458
459 use acp_thread::{AgentConnection, StubAgentConnection};
460 use agent_client_protocol as acp;
461 use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
462 use editor::RowInfo;
463 use fs::FakeFs;
464 use gpui::{AppContext as _, TestAppContext};
465 use parking_lot::RwLock;
466
467 use crate::entry_view_state::EntryViewState;
468 use crate::message_editor::SessionCapabilities;
469 use multi_buffer::MultiBufferRow;
470 use pretty_assertions::assert_matches;
471 use project::Project;
472 use serde_json::json;
473 use settings::SettingsStore;
474 use util::path;
475 use workspace::{MultiWorkspace, PathList};
476
477 #[gpui::test]
478 async fn test_diff_sync(cx: &mut TestAppContext) {
479 init_test(cx);
480 let fs = FakeFs::new(cx.executor());
481 fs.insert_tree(
482 "/project",
483 json!({
484 "hello.txt": "hi world"
485 }),
486 )
487 .await;
488 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
489
490 let (multi_workspace, cx) =
491 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
492 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
493
494 let tool_call = acp::ToolCall::new("tool", "Tool call")
495 .status(acp::ToolCallStatus::InProgress)
496 .content(vec![acp::ToolCallContent::Diff(
497 acp::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),
498 )]);
499 let connection = Rc::new(StubAgentConnection::new());
500 let thread = cx
501 .update(|_, cx| {
502 connection.clone().new_session(
503 project.clone(),
504 PathList::new(&[Path::new(path!("/project"))]),
505 cx,
506 )
507 })
508 .await
509 .unwrap();
510 let session_id = thread.update(cx, |thread, _| thread.session_id().clone());
511
512 cx.update(|_, cx| {
513 connection.send_update(session_id, acp::SessionUpdate::ToolCall(tool_call), cx)
514 });
515
516 let thread_store = None;
517 let history: Option<gpui::WeakEntity<crate::ThreadHistory>> = None;
518
519 let view_state = cx.new(|_cx| {
520 EntryViewState::new(
521 workspace.downgrade(),
522 project.downgrade(),
523 thread_store,
524 history,
525 None,
526 Arc::new(RwLock::new(SessionCapabilities::default())),
527 "Test Agent".into(),
528 )
529 });
530
531 view_state.update_in(cx, |view_state, window, cx| {
532 view_state.sync_entry(0, &thread, window, cx)
533 });
534
535 let diff = thread.read_with(cx, |thread, _| {
536 thread
537 .entries()
538 .get(0)
539 .unwrap()
540 .diffs()
541 .next()
542 .unwrap()
543 .clone()
544 });
545
546 cx.run_until_parked();
547
548 let diff_editor = view_state.read_with(cx, |view_state, _cx| {
549 view_state.entry(0).unwrap().editor_for_diff(&diff).unwrap()
550 });
551 assert_eq!(
552 diff_editor.read_with(cx, |editor, cx| editor.text(cx)),
553 "hi world\nhello world"
554 );
555 let row_infos = diff_editor.read_with(cx, |editor, cx| {
556 let multibuffer = editor.buffer().read(cx);
557 multibuffer
558 .snapshot(cx)
559 .row_infos(MultiBufferRow(0))
560 .collect::<Vec<_>>()
561 });
562 assert_matches!(
563 row_infos.as_slice(),
564 [
565 RowInfo {
566 multibuffer_row: Some(MultiBufferRow(0)),
567 diff_status: Some(DiffHunkStatus {
568 kind: DiffHunkStatusKind::Deleted,
569 ..
570 }),
571 ..
572 },
573 RowInfo {
574 multibuffer_row: Some(MultiBufferRow(1)),
575 diff_status: Some(DiffHunkStatus {
576 kind: DiffHunkStatusKind::Added,
577 ..
578 }),
579 ..
580 }
581 ]
582 );
583 }
584
585 fn init_test(cx: &mut TestAppContext) {
586 cx.update(|cx| {
587 let settings_store = SettingsStore::test(cx);
588 cx.set_global(settings_store);
589 theme::init(theme::LoadThemes::JustBase, cx);
590 release_channel::init(semver::Version::new(0, 0, 0), cx);
591 });
592 }
593}