thread_view.rs

  1use std::path::Path;
  2use std::rc::Rc;
  3
  4use anyhow::Result;
  5use editor::{Editor, MultiBuffer};
  6use gpui::{
  7    App, EdgesRefinement, Empty, Entity, Focusable, ListState, SharedString, StyleRefinement,
  8    Subscription, TextStyleRefinement, UnderlineStyle, Window, div, list, prelude::*,
  9};
 10use gpui::{FocusHandle, Task};
 11use language::Buffer;
 12use markdown::{HeadingLevelStyles, MarkdownElement, MarkdownStyle};
 13use project::Project;
 14use settings::Settings as _;
 15use theme::ThemeSettings;
 16use ui::Tooltip;
 17use ui::prelude::*;
 18use util::ResultExt;
 19use zed_actions::agent::Chat;
 20
 21use crate::{
 22    AcpServer, AcpThread, AcpThreadEvent, AgentThreadEntryContent, MessageChunk, Role, ThreadEntry,
 23};
 24
 25pub struct AcpThreadView {
 26    thread_state: ThreadState,
 27    // todo! use full message editor from agent2
 28    message_editor: Entity<Editor>,
 29    list_state: ListState,
 30    send_task: Option<Task<Result<()>>>,
 31}
 32
 33enum ThreadState {
 34    Loading {
 35        _task: Task<()>,
 36    },
 37    Ready {
 38        thread: Entity<AcpThread>,
 39        _subscription: Subscription,
 40    },
 41    LoadError(SharedString),
 42}
 43
 44impl AcpThreadView {
 45    pub fn new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 46        let Some(root_dir) = project
 47            .read(cx)
 48            .visible_worktrees(cx)
 49            .next()
 50            .map(|worktree| worktree.read(cx).abs_path())
 51        else {
 52            todo!();
 53        };
 54
 55        let cli_path =
 56            Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../gemini-cli/packages/cli");
 57
 58        let child = util::command::new_smol_command("node")
 59            .arg(cli_path)
 60            .arg("--acp")
 61            .args(["--model", "gemini-2.5-flash"])
 62            .current_dir(root_dir)
 63            .stdin(std::process::Stdio::piped())
 64            .stdout(std::process::Stdio::piped())
 65            .stderr(std::process::Stdio::inherit())
 66            .kill_on_drop(true)
 67            .spawn()
 68            .unwrap();
 69
 70        let message_editor = cx.new(|cx| {
 71            let buffer = cx.new(|cx| Buffer::local("", cx));
 72            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 73
 74            let mut editor = Editor::new(
 75                editor::EditorMode::AutoHeight {
 76                    min_lines: 5,
 77                    max_lines: None,
 78                },
 79                buffer,
 80                None,
 81                window,
 82                cx,
 83            );
 84            editor.set_placeholder_text("Send a message", cx);
 85            editor.set_soft_wrap();
 86            editor
 87        });
 88
 89        let project = project.clone();
 90        let load_task = cx.spawn_in(window, async move |this, cx| {
 91            let agent = AcpServer::stdio(child, project, cx);
 92            let result = agent.create_thread(cx).await;
 93
 94            this.update(cx, |this, cx| {
 95                match result {
 96                    Ok(thread) => {
 97                        let subscription = cx.subscribe(&thread, |this, _, event, cx| {
 98                            let count = this.list_state.item_count();
 99                            match event {
100                                AcpThreadEvent::NewEntry => {
101                                    this.list_state.splice(count..count, 1);
102                                }
103                                AcpThreadEvent::LastEntryUpdated => {
104                                    this.list_state.splice(count - 1..count, 1);
105                                }
106                            }
107                            cx.notify();
108                        });
109                        this.list_state
110                            .splice(0..0, thread.read(cx).entries().len());
111
112                        this.thread_state = ThreadState::Ready {
113                            thread,
114                            _subscription: subscription,
115                        };
116                    }
117                    Err(e) => this.thread_state = ThreadState::LoadError(e.to_string().into()),
118                };
119                cx.notify();
120            })
121            .log_err();
122        });
123
124        let list_state = ListState::new(
125            0,
126            gpui::ListAlignment::Top,
127            px(1000.0),
128            cx.processor({
129                move |this: &mut Self, item: usize, window, cx| {
130                    let Some(entry) = this
131                        .thread()
132                        .and_then(|thread| thread.read(cx).entries.get(item))
133                    else {
134                        return Empty.into_any();
135                    };
136                    this.render_entry(entry, window, cx)
137                }
138            }),
139        );
140
141        Self {
142            thread_state: ThreadState::Loading { _task: load_task },
143            message_editor,
144            send_task: None,
145            list_state: list_state,
146        }
147    }
148
149    fn thread(&self) -> Option<&Entity<AcpThread>> {
150        match &self.thread_state {
151            ThreadState::Ready { thread, .. } => Some(thread),
152            _ => None,
153        }
154    }
155
156    pub fn title(&self, cx: &App) -> SharedString {
157        match &self.thread_state {
158            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
159            ThreadState::Loading { .. } => "Loading...".into(),
160            ThreadState::LoadError(_) => "Failed to load".into(),
161        }
162    }
163
164    pub fn cancel(&mut self) {
165        self.send_task.take();
166    }
167
168    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
169        let text = self.message_editor.read(cx).text(cx);
170        if text.is_empty() {
171            return;
172        }
173        let Some(thread) = self.thread() else { return };
174
175        let task = thread.update(cx, |thread, cx| thread.send(&text, cx));
176
177        self.send_task = Some(cx.spawn(async move |this, cx| {
178            task.await?;
179
180            this.update(cx, |this, _cx| {
181                this.send_task.take();
182            })
183        }));
184
185        self.message_editor.update(cx, |editor, cx| {
186            editor.clear(window, cx);
187        });
188    }
189
190    fn render_entry(
191        &self,
192        entry: &ThreadEntry,
193        window: &mut Window,
194        cx: &Context<Self>,
195    ) -> AnyElement {
196        match &entry.content {
197            AgentThreadEntryContent::Message(message) => {
198                let style = if message.role == Role::User {
199                    user_message_markdown_style(window, cx)
200                } else {
201                    default_markdown_style(window, cx)
202                };
203                let message_body = div()
204                    .children(message.chunks.iter().map(|chunk| match chunk {
205                        MessageChunk::Text { chunk } => {
206                            // todo!() open link
207                            MarkdownElement::new(chunk.clone(), style.clone())
208                        }
209                        _ => todo!(),
210                    }))
211                    .into_any();
212
213                match message.role {
214                    Role::User => div()
215                        .text_xs()
216                        .m_1()
217                        .p_2()
218                        .bg(cx.theme().colors().editor_background)
219                        .rounded_lg()
220                        .shadow_md()
221                        .border_1()
222                        .border_color(cx.theme().colors().border)
223                        .child(message_body)
224                        .into_any(),
225                    Role::Assistant => div()
226                        .text_ui(cx)
227                        .px_2()
228                        .py_4()
229                        .child(message_body)
230                        .into_any(),
231                }
232            }
233            AgentThreadEntryContent::ReadFile { path, content: _ } => {
234                // todo!
235                div()
236                    .child(format!("<Reading file {}>", path.display()))
237                    .into_any()
238            }
239        }
240    }
241}
242
243impl Focusable for AcpThreadView {
244    fn focus_handle(&self, cx: &App) -> FocusHandle {
245        self.message_editor.focus_handle(cx)
246    }
247}
248
249impl Render for AcpThreadView {
250    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
251        let text = self.message_editor.read(cx).text(cx);
252        let is_editor_empty = text.is_empty();
253        let focus_handle = self.message_editor.focus_handle(cx);
254
255        v_flex()
256            .key_context("MessageEditor")
257            .on_action(cx.listener(Self::chat))
258            .child(match &self.thread_state {
259                ThreadState::Loading { .. } => div().p_2().child(Label::new("Loading...")),
260                ThreadState::LoadError(e) => div()
261                    .p_2()
262                    .child(Label::new(format!("Failed to load {e}")).into_any_element()),
263                ThreadState::Ready { .. } => div()
264                    .child(
265                        list(self.list_state.clone())
266                            .with_sizing_behavior(gpui::ListSizingBehavior::Infer),
267                    )
268                    .p_2(),
269            })
270            .when(self.send_task.is_some(), |this| {
271                this.child(
272                    div().p_2().child(
273                        Label::new("Generating...")
274                            .color(Color::Muted)
275                            .size(LabelSize::Small),
276                    ),
277                )
278            })
279            .child(
280                div()
281                    .bg(cx.theme().colors().editor_background)
282                    .border_t_1()
283                    .border_color(cx.theme().colors().border)
284                    .p_2()
285                    .child(self.message_editor.clone()),
286            )
287            .child(
288                h_flex()
289                    .p_2()
290                    .justify_end()
291                    .child(if self.send_task.is_some() {
292                        IconButton::new("stop-generation", IconName::StopFilled)
293                            .icon_color(Color::Error)
294                            .style(ButtonStyle::Tinted(ui::TintColor::Error))
295                            .tooltip(move |window, cx| {
296                                Tooltip::for_action(
297                                    "Stop Generation",
298                                    &editor::actions::Cancel,
299                                    window,
300                                    cx,
301                                )
302                            })
303                            .disabled(is_editor_empty)
304                            .on_click(cx.listener(|this, _event, _, _| this.cancel()))
305                    } else {
306                        IconButton::new("send-message", IconName::Send)
307                            .icon_color(Color::Accent)
308                            .style(ButtonStyle::Filled)
309                            .disabled(is_editor_empty)
310                            .on_click({
311                                let focus_handle = focus_handle.clone();
312                                move |_event, window, cx| {
313                                    focus_handle.dispatch_action(&Chat, window, cx);
314                                }
315                            })
316                            .when(!is_editor_empty, |button| {
317                                button.tooltip(move |window, cx| {
318                                    Tooltip::for_action("Send", &Chat, window, cx)
319                                })
320                            })
321                            .when(is_editor_empty, |button| {
322                                button.tooltip(Tooltip::text("Type a message to submit"))
323                            })
324                    }),
325            )
326    }
327}
328
329fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
330    let mut style = default_markdown_style(window, cx);
331    let mut text_style = window.text_style();
332    let theme_settings = ThemeSettings::get_global(cx);
333
334    let buffer_font = theme_settings.buffer_font.family.clone();
335    let buffer_font_size = TextSize::Small.rems(cx);
336
337    text_style.refine(&TextStyleRefinement {
338        font_family: Some(buffer_font),
339        font_size: Some(buffer_font_size.into()),
340        ..Default::default()
341    });
342
343    style.base_text_style = text_style;
344    style
345}
346
347fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
348    let theme_settings = ThemeSettings::get_global(cx);
349    let colors = cx.theme().colors();
350    let ui_font_size = TextSize::Default.rems(cx);
351    let buffer_font_size = TextSize::Small.rems(cx);
352    let mut text_style = window.text_style();
353    let line_height = buffer_font_size * 1.75;
354
355    text_style.refine(&TextStyleRefinement {
356        font_family: Some(theme_settings.ui_font.family.clone()),
357        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
358        font_features: Some(theme_settings.ui_font.features.clone()),
359        font_size: Some(ui_font_size.into()),
360        line_height: Some(line_height.into()),
361        color: Some(cx.theme().colors().text),
362        ..Default::default()
363    });
364
365    MarkdownStyle {
366        base_text_style: text_style.clone(),
367        syntax: cx.theme().syntax().clone(),
368        selection_background_color: cx.theme().colors().element_selection_background,
369        code_block_overflow_x_scroll: true,
370        table_overflow_x_scroll: true,
371        heading_level_styles: Some(HeadingLevelStyles {
372            h1: Some(TextStyleRefinement {
373                font_size: Some(rems(1.15).into()),
374                ..Default::default()
375            }),
376            h2: Some(TextStyleRefinement {
377                font_size: Some(rems(1.1).into()),
378                ..Default::default()
379            }),
380            h3: Some(TextStyleRefinement {
381                font_size: Some(rems(1.05).into()),
382                ..Default::default()
383            }),
384            h4: Some(TextStyleRefinement {
385                font_size: Some(rems(1.).into()),
386                ..Default::default()
387            }),
388            h5: Some(TextStyleRefinement {
389                font_size: Some(rems(0.95).into()),
390                ..Default::default()
391            }),
392            h6: Some(TextStyleRefinement {
393                font_size: Some(rems(0.875).into()),
394                ..Default::default()
395            }),
396        }),
397        code_block: StyleRefinement {
398            padding: EdgesRefinement {
399                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
400                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
401                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
402                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
403            },
404            background: Some(colors.editor_background.into()),
405            text: Some(TextStyleRefinement {
406                font_family: Some(theme_settings.buffer_font.family.clone()),
407                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
408                font_features: Some(theme_settings.buffer_font.features.clone()),
409                font_size: Some(buffer_font_size.into()),
410                ..Default::default()
411            }),
412            ..Default::default()
413        },
414        inline_code: TextStyleRefinement {
415            font_family: Some(theme_settings.buffer_font.family.clone()),
416            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
417            font_features: Some(theme_settings.buffer_font.features.clone()),
418            font_size: Some(buffer_font_size.into()),
419            background_color: Some(colors.editor_foreground.opacity(0.08)),
420            ..Default::default()
421        },
422        link: TextStyleRefinement {
423            background_color: Some(colors.editor_foreground.opacity(0.025)),
424            underline: Some(UnderlineStyle {
425                color: Some(colors.text_accent.opacity(0.5)),
426                thickness: px(1.),
427                ..Default::default()
428            }),
429            ..Default::default()
430        },
431        link_callback: Some(Rc::new(move |_url, _cx| {
432            // todo!()
433            // if MentionLink::is_valid(url) {
434            //     let colors = cx.theme().colors();
435            //     Some(TextStyleRefinement {
436            //         background_color: Some(colors.element_background),
437            //         ..Default::default()
438            //     })
439            // } else {
440            None
441            // }
442        })),
443        ..Default::default()
444    }
445}