entry_view_state.rs

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