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, Focusable, ScrollHandle,
 10    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 message_editor(&self) -> Option<&Entity<MessageEditor>> {
251        match self {
252            Self::UserMessage(editor) => Some(editor),
253            Self::AssistantMessage(_) | Self::Content(_) => None,
254        }
255    }
256
257    pub fn editor_for_diff(&self, diff: &Entity<acp_thread::Diff>) -> Option<Entity<Editor>> {
258        self.content_map()?
259            .get(&diff.entity_id())
260            .cloned()
261            .map(|entity| entity.downcast::<Editor>().unwrap())
262    }
263
264    pub fn terminal(
265        &self,
266        terminal: &Entity<acp_thread::Terminal>,
267    ) -> Option<Entity<TerminalView>> {
268        self.content_map()?
269            .get(&terminal.entity_id())
270            .cloned()
271            .map(|entity| entity.downcast::<TerminalView>().unwrap())
272    }
273
274    pub fn scroll_handle_for_assistant_message_chunk(
275        &self,
276        chunk_ix: usize,
277    ) -> Option<ScrollHandle> {
278        match self {
279            Self::AssistantMessage(message) => message.scroll_handle_for_chunk(chunk_ix),
280            Self::UserMessage(_) | Self::Content(_) => None,
281        }
282    }
283
284    fn content_map(&self) -> Option<&HashMap<EntityId, AnyEntity>> {
285        match self {
286            Self::Content(map) => Some(map),
287            _ => None,
288        }
289    }
290
291    fn empty() -> Self {
292        Self::Content(HashMap::default())
293    }
294
295    #[cfg(test)]
296    pub fn has_content(&self) -> bool {
297        match self {
298            Self::Content(map) => !map.is_empty(),
299            Self::UserMessage(_) | Self::AssistantMessage(_) => false,
300        }
301    }
302}
303
304fn create_terminal(
305    workspace: WeakEntity<Workspace>,
306    project: Entity<Project>,
307    terminal: Entity<acp_thread::Terminal>,
308    window: &mut Window,
309    cx: &mut App,
310) -> Entity<TerminalView> {
311    cx.new(|cx| {
312        let mut view = TerminalView::new(
313            terminal.read(cx).inner().clone(),
314            workspace.clone(),
315            None,
316            project.downgrade(),
317            window,
318            cx,
319        );
320        view.set_embedded_mode(Some(1000), cx);
321        view
322    })
323}
324
325fn create_editor_diff(
326    diff: Entity<acp_thread::Diff>,
327    window: &mut Window,
328    cx: &mut App,
329) -> Entity<Editor> {
330    cx.new(|cx| {
331        let mut editor = Editor::new(
332            EditorMode::Full {
333                scale_ui_elements_with_buffer_font_size: false,
334                show_active_line_background: false,
335                sized_by_content: true,
336            },
337            diff.read(cx).multibuffer().clone(),
338            None,
339            window,
340            cx,
341        );
342        editor.set_show_gutter(false, cx);
343        editor.disable_inline_diagnostics();
344        editor.disable_expand_excerpt_buttons(cx);
345        editor.set_show_vertical_scrollbar(false, cx);
346        editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
347        editor.set_soft_wrap_mode(SoftWrap::None, cx);
348        editor.scroll_manager.set_forbid_vertical_scroll(true);
349        editor.set_show_indent_guides(false, cx);
350        editor.set_read_only(true);
351        editor.set_show_breakpoints(false, cx);
352        editor.set_show_code_actions(false, cx);
353        editor.set_show_git_diff_gutter(false, cx);
354        editor.set_expand_all_diff_hunks(cx);
355        editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
356        editor
357    })
358}
359
360fn diff_editor_text_style_refinement(cx: &mut App) -> TextStyleRefinement {
361    TextStyleRefinement {
362        font_size: Some(
363            TextSize::Small
364                .rems(cx)
365                .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
366                .into(),
367        ),
368        ..Default::default()
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use std::{path::Path, rc::Rc};
375
376    use acp_thread::{AgentConnection, StubAgentConnection};
377    use agent_client_protocol as acp;
378    use agent_settings::AgentSettings;
379    use agent2::HistoryStore;
380    use assistant_context::ContextStore;
381    use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
382    use editor::{EditorSettings, RowInfo};
383    use fs::FakeFs;
384    use gpui::{AppContext as _, SemanticVersion, TestAppContext};
385
386    use crate::acp::entry_view_state::EntryViewState;
387    use multi_buffer::MultiBufferRow;
388    use pretty_assertions::assert_matches;
389    use project::Project;
390    use serde_json::json;
391    use settings::{Settings as _, SettingsStore};
392    use theme::ThemeSettings;
393    use util::path;
394    use workspace::Workspace;
395
396    #[gpui::test]
397    async fn test_diff_sync(cx: &mut TestAppContext) {
398        init_test(cx);
399        let fs = FakeFs::new(cx.executor());
400        fs.insert_tree(
401            "/project",
402            json!({
403                "hello.txt": "hi world"
404            }),
405        )
406        .await;
407        let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
408
409        let (workspace, cx) =
410            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
411
412        let tool_call = acp::ToolCall {
413            id: acp::ToolCallId("tool".into()),
414            title: "Tool call".into(),
415            kind: acp::ToolKind::Other,
416            status: acp::ToolCallStatus::InProgress,
417            content: vec![acp::ToolCallContent::Diff {
418                diff: acp::Diff {
419                    path: "/project/hello.txt".into(),
420                    old_text: Some("hi world".into()),
421                    new_text: "hello world".into(),
422                },
423            }],
424            locations: vec![],
425            raw_input: None,
426            raw_output: None,
427        };
428        let connection = Rc::new(StubAgentConnection::new());
429        let thread = cx
430            .update(|_, cx| {
431                connection
432                    .clone()
433                    .new_thread(project.clone(), Path::new(path!("/project")), cx)
434            })
435            .await
436            .unwrap();
437        let session_id = thread.update(cx, |thread, _| thread.session_id().clone());
438
439        cx.update(|_, cx| {
440            connection.send_update(session_id, acp::SessionUpdate::ToolCall(tool_call), cx)
441        });
442
443        let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
444        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
445
446        let view_state = cx.new(|_cx| {
447            EntryViewState::new(
448                workspace.downgrade(),
449                project.clone(),
450                history_store,
451                None,
452                Default::default(),
453                false,
454            )
455        });
456
457        view_state.update_in(cx, |view_state, window, cx| {
458            view_state.sync_entry(0, &thread, window, cx)
459        });
460
461        let diff = thread.read_with(cx, |thread, _cx| {
462            thread
463                .entries()
464                .get(0)
465                .unwrap()
466                .diffs()
467                .next()
468                .unwrap()
469                .clone()
470        });
471
472        cx.run_until_parked();
473
474        let diff_editor = view_state.read_with(cx, |view_state, _cx| {
475            view_state.entry(0).unwrap().editor_for_diff(&diff).unwrap()
476        });
477        assert_eq!(
478            diff_editor.read_with(cx, |editor, cx| editor.text(cx)),
479            "hi world\nhello world"
480        );
481        let row_infos = diff_editor.read_with(cx, |editor, cx| {
482            let multibuffer = editor.buffer().read(cx);
483            multibuffer
484                .snapshot(cx)
485                .row_infos(MultiBufferRow(0))
486                .collect::<Vec<_>>()
487        });
488        assert_matches!(
489            row_infos.as_slice(),
490            [
491                RowInfo {
492                    multibuffer_row: Some(MultiBufferRow(0)),
493                    diff_status: Some(DiffHunkStatus {
494                        kind: DiffHunkStatusKind::Deleted,
495                        ..
496                    }),
497                    ..
498                },
499                RowInfo {
500                    multibuffer_row: Some(MultiBufferRow(1)),
501                    diff_status: Some(DiffHunkStatus {
502                        kind: DiffHunkStatusKind::Added,
503                        ..
504                    }),
505                    ..
506                }
507            ]
508        );
509    }
510
511    fn init_test(cx: &mut TestAppContext) {
512        cx.update(|cx| {
513            let settings_store = SettingsStore::test(cx);
514            cx.set_global(settings_store);
515            language::init(cx);
516            Project::init_settings(cx);
517            AgentSettings::register(cx);
518            workspace::init_settings(cx);
519            ThemeSettings::register(cx);
520            release_channel::init(SemanticVersion::default(), cx);
521            EditorSettings::register(cx);
522        });
523    }
524}