active_thread.rs

  1use std::sync::Arc;
  2
  3use assistant_tool::ToolWorkingSet;
  4use collections::HashMap;
  5use gpui::{
  6    list, AbsoluteLength, AnyElement, App, DefiniteLength, EdgesRefinement, Empty, Entity, Length,
  7    ListAlignment, ListOffset, ListState, StyleRefinement, Subscription, TextStyleRefinement,
  8    UnderlineStyle, WeakEntity,
  9};
 10use language::LanguageRegistry;
 11use language_model::{LanguageModelRegistry, LanguageModelToolUseId, Role};
 12use markdown::{Markdown, MarkdownStyle};
 13use settings::Settings as _;
 14use theme::ThemeSettings;
 15use ui::{prelude::*, Disclosure};
 16use workspace::Workspace;
 17
 18use crate::thread::{MessageId, RequestKind, Thread, ThreadError, ThreadEvent};
 19use crate::thread_store::ThreadStore;
 20use crate::tool_use::{ToolUse, ToolUseStatus};
 21use crate::ui::ContextPill;
 22
 23pub struct ActiveThread {
 24    workspace: WeakEntity<Workspace>,
 25    language_registry: Arc<LanguageRegistry>,
 26    tools: Arc<ToolWorkingSet>,
 27    thread_store: Entity<ThreadStore>,
 28    thread: Entity<Thread>,
 29    messages: Vec<MessageId>,
 30    list_state: ListState,
 31    rendered_messages_by_id: HashMap<MessageId, Entity<Markdown>>,
 32    expanded_tool_uses: HashMap<LanguageModelToolUseId, bool>,
 33    last_error: Option<ThreadError>,
 34    _subscriptions: Vec<Subscription>,
 35}
 36
 37impl ActiveThread {
 38    pub fn new(
 39        thread: Entity<Thread>,
 40        thread_store: Entity<ThreadStore>,
 41        workspace: WeakEntity<Workspace>,
 42        language_registry: Arc<LanguageRegistry>,
 43        tools: Arc<ToolWorkingSet>,
 44        window: &mut Window,
 45        cx: &mut Context<Self>,
 46    ) -> Self {
 47        let subscriptions = vec![
 48            cx.observe(&thread, |_, _, cx| cx.notify()),
 49            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 50        ];
 51
 52        let mut this = Self {
 53            workspace,
 54            language_registry,
 55            tools,
 56            thread_store,
 57            thread: thread.clone(),
 58            messages: Vec::new(),
 59            rendered_messages_by_id: HashMap::default(),
 60            expanded_tool_uses: HashMap::default(),
 61            list_state: ListState::new(0, ListAlignment::Bottom, px(1024.), {
 62                let this = cx.entity().downgrade();
 63                move |ix, _: &mut Window, cx: &mut App| {
 64                    this.update(cx, |this, cx| this.render_message(ix, cx))
 65                        .unwrap()
 66                }
 67            }),
 68            last_error: None,
 69            _subscriptions: subscriptions,
 70        };
 71
 72        for message in thread.read(cx).messages().cloned().collect::<Vec<_>>() {
 73            this.push_message(&message.id, message.text.clone(), window, cx);
 74        }
 75
 76        this
 77    }
 78
 79    pub fn thread(&self) -> &Entity<Thread> {
 80        &self.thread
 81    }
 82
 83    pub fn is_empty(&self) -> bool {
 84        self.messages.is_empty()
 85    }
 86
 87    pub fn summary(&self, cx: &App) -> Option<SharedString> {
 88        self.thread.read(cx).summary()
 89    }
 90
 91    pub fn summary_or_default(&self, cx: &App) -> SharedString {
 92        self.thread.read(cx).summary_or_default()
 93    }
 94
 95    pub fn cancel_last_completion(&mut self, cx: &mut App) -> bool {
 96        self.last_error.take();
 97        self.thread
 98            .update(cx, |thread, _cx| thread.cancel_last_completion())
 99    }
100
101    pub fn last_error(&self) -> Option<ThreadError> {
102        self.last_error.clone()
103    }
104
105    pub fn clear_last_error(&mut self) {
106        self.last_error.take();
107    }
108
109    fn push_message(
110        &mut self,
111        id: &MessageId,
112        text: String,
113        window: &mut Window,
114        cx: &mut Context<Self>,
115    ) {
116        let old_len = self.messages.len();
117        self.messages.push(*id);
118        self.list_state.splice(old_len..old_len, 1);
119
120        let theme_settings = ThemeSettings::get_global(cx);
121        let colors = cx.theme().colors();
122        let ui_font_size = TextSize::Default.rems(cx);
123        let buffer_font_size = TextSize::Small.rems(cx);
124        let mut text_style = window.text_style();
125
126        text_style.refine(&TextStyleRefinement {
127            font_family: Some(theme_settings.ui_font.family.clone()),
128            font_size: Some(ui_font_size.into()),
129            color: Some(cx.theme().colors().text),
130            ..Default::default()
131        });
132
133        let markdown_style = MarkdownStyle {
134            base_text_style: text_style,
135            syntax: cx.theme().syntax().clone(),
136            selection_background_color: cx.theme().players().local().selection,
137            code_block: StyleRefinement {
138                margin: EdgesRefinement {
139                    top: Some(Length::Definite(rems(0.).into())),
140                    left: Some(Length::Definite(rems(0.).into())),
141                    right: Some(Length::Definite(rems(0.).into())),
142                    bottom: Some(Length::Definite(rems(0.5).into())),
143                },
144                padding: EdgesRefinement {
145                    top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
146                    left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
147                    right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
148                    bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
149                },
150                background: Some(colors.editor_background.into()),
151                border_color: Some(colors.border_variant),
152                border_widths: EdgesRefinement {
153                    top: Some(AbsoluteLength::Pixels(Pixels(1.))),
154                    left: Some(AbsoluteLength::Pixels(Pixels(1.))),
155                    right: Some(AbsoluteLength::Pixels(Pixels(1.))),
156                    bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
157                },
158                text: Some(TextStyleRefinement {
159                    font_family: Some(theme_settings.buffer_font.family.clone()),
160                    font_size: Some(buffer_font_size.into()),
161                    ..Default::default()
162                }),
163                ..Default::default()
164            },
165            inline_code: TextStyleRefinement {
166                font_family: Some(theme_settings.buffer_font.family.clone()),
167                font_size: Some(buffer_font_size.into()),
168                background_color: Some(colors.editor_foreground.opacity(0.1)),
169                ..Default::default()
170            },
171            link: TextStyleRefinement {
172                background_color: Some(colors.editor_foreground.opacity(0.025)),
173                underline: Some(UnderlineStyle {
174                    color: Some(colors.text_accent.opacity(0.5)),
175                    thickness: px(1.),
176                    ..Default::default()
177                }),
178                ..Default::default()
179            },
180            ..Default::default()
181        };
182
183        let markdown = cx.new(|cx| {
184            Markdown::new(
185                text.into(),
186                markdown_style,
187                Some(self.language_registry.clone()),
188                None,
189                cx,
190            )
191        });
192        self.rendered_messages_by_id.insert(*id, markdown);
193        self.list_state.scroll_to(ListOffset {
194            item_ix: old_len,
195            offset_in_item: Pixels(0.0),
196        });
197    }
198
199    fn handle_thread_event(
200        &mut self,
201        _: &Entity<Thread>,
202        event: &ThreadEvent,
203        window: &mut Window,
204        cx: &mut Context<Self>,
205    ) {
206        match event {
207            ThreadEvent::ShowError(error) => {
208                self.last_error = Some(error.clone());
209            }
210            ThreadEvent::StreamedCompletion | ThreadEvent::SummaryChanged => {
211                self.thread_store
212                    .update(cx, |thread_store, cx| {
213                        thread_store.save_thread(&self.thread, cx)
214                    })
215                    .detach_and_log_err(cx);
216            }
217            ThreadEvent::StreamedAssistantText(message_id, text) => {
218                if let Some(markdown) = self.rendered_messages_by_id.get_mut(&message_id) {
219                    markdown.update(cx, |markdown, cx| {
220                        markdown.append(text, cx);
221                    });
222                }
223            }
224            ThreadEvent::MessageAdded(message_id) => {
225                if let Some(message_text) = self
226                    .thread
227                    .read(cx)
228                    .message(*message_id)
229                    .map(|message| message.text.clone())
230                {
231                    self.push_message(message_id, message_text, window, cx);
232                }
233
234                self.thread_store
235                    .update(cx, |thread_store, cx| {
236                        thread_store.save_thread(&self.thread, cx)
237                    })
238                    .detach_and_log_err(cx);
239
240                cx.notify();
241            }
242            ThreadEvent::UsePendingTools => {
243                let pending_tool_uses = self
244                    .thread
245                    .read(cx)
246                    .pending_tool_uses()
247                    .into_iter()
248                    .filter(|tool_use| tool_use.status.is_idle())
249                    .cloned()
250                    .collect::<Vec<_>>();
251
252                for tool_use in pending_tool_uses {
253                    if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
254                        let task = tool.run(tool_use.input, self.workspace.clone(), window, cx);
255
256                        self.thread.update(cx, |thread, cx| {
257                            thread.insert_tool_output(tool_use.id.clone(), task, cx);
258                        });
259                    }
260                }
261            }
262            ThreadEvent::ToolFinished { .. } => {
263                let all_tools_finished = self
264                    .thread
265                    .read(cx)
266                    .pending_tool_uses()
267                    .into_iter()
268                    .all(|tool_use| tool_use.status.is_error());
269                if all_tools_finished {
270                    let model_registry = LanguageModelRegistry::read_global(cx);
271                    if let Some(model) = model_registry.active_model() {
272                        self.thread.update(cx, |thread, cx| {
273                            // Insert an empty user message to contain the tool results.
274                            thread.insert_user_message("", Vec::new(), cx);
275                            thread.send_to_model(model, RequestKind::Chat, true, cx);
276                        });
277                    }
278                }
279            }
280        }
281    }
282
283    fn render_message(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
284        let message_id = self.messages[ix];
285        let Some(message) = self.thread.read(cx).message(message_id) else {
286            return Empty.into_any();
287        };
288
289        let Some(markdown) = self.rendered_messages_by_id.get(&message_id) else {
290            return Empty.into_any();
291        };
292
293        let context = self.thread.read(cx).context_for_message(message_id);
294        let tool_uses = self.thread.read(cx).tool_uses_for_message(message_id);
295        let colors = cx.theme().colors();
296
297        // Don't render user messages that are just there for returning tool results.
298        if message.role == Role::User
299            && message.text.is_empty()
300            && self.thread.read(cx).message_has_tool_results(message_id)
301        {
302            return Empty.into_any();
303        }
304
305        let message_content = v_flex()
306            .child(div().p_2p5().text_ui(cx).child(markdown.clone()))
307            .when_some(context, |parent, context| {
308                if !context.is_empty() {
309                    parent.child(
310                        h_flex().flex_wrap().gap_1().px_1p5().pb_1p5().children(
311                            context
312                                .into_iter()
313                                .map(|context| ContextPill::added(context, false, false, None)),
314                        ),
315                    )
316                } else {
317                    parent
318                }
319            });
320
321        let styled_message = match message.role {
322            Role::User => v_flex()
323                .id(("message-container", ix))
324                .pt_2p5()
325                .px_2p5()
326                .child(
327                    v_flex()
328                        .bg(colors.editor_background)
329                        .rounded_lg()
330                        .border_1()
331                        .border_color(colors.border)
332                        .shadow_sm()
333                        .child(
334                            h_flex()
335                                .py_1()
336                                .px_2()
337                                .bg(colors.editor_foreground.opacity(0.05))
338                                .border_b_1()
339                                .border_color(colors.border)
340                                .justify_between()
341                                .rounded_t(px(6.))
342                                .child(
343                                    h_flex()
344                                        .gap_1p5()
345                                        .child(
346                                            Icon::new(IconName::PersonCircle)
347                                                .size(IconSize::XSmall)
348                                                .color(Color::Muted),
349                                        )
350                                        .child(
351                                            Label::new("You")
352                                                .size(LabelSize::Small)
353                                                .color(Color::Muted),
354                                        ),
355                                ),
356                        )
357                        .child(message_content),
358                ),
359            Role::Assistant => div()
360                .id(("message-container", ix))
361                .child(message_content)
362                .map(|parent| {
363                    if tool_uses.is_empty() {
364                        return parent;
365                    }
366
367                    parent.child(
368                        v_flex().children(
369                            tool_uses
370                                .into_iter()
371                                .map(|tool_use| self.render_tool_use(tool_use, cx)),
372                        ),
373                    )
374                }),
375            Role::System => div().id(("message-container", ix)).py_1().px_2().child(
376                v_flex()
377                    .bg(colors.editor_background)
378                    .rounded_md()
379                    .child(message_content),
380            ),
381        };
382
383        styled_message.into_any()
384    }
385
386    fn render_tool_use(&self, tool_use: ToolUse, cx: &mut Context<Self>) -> impl IntoElement {
387        let is_open = self
388            .expanded_tool_uses
389            .get(&tool_use.id)
390            .copied()
391            .unwrap_or_default();
392
393        div().px_2p5().child(
394            v_flex()
395                .gap_1()
396                .rounded_lg()
397                .border_1()
398                .border_color(cx.theme().colors().border)
399                .child(
400                    h_flex()
401                        .justify_between()
402                        .py_0p5()
403                        .pl_1()
404                        .pr_2()
405                        .bg(cx.theme().colors().editor_foreground.opacity(0.02))
406                        .when(is_open, |element| element.border_b_1().rounded_t(px(6.)))
407                        .when(!is_open, |element| element.rounded(px(6.)))
408                        .border_color(cx.theme().colors().border)
409                        .child(
410                            h_flex()
411                                .gap_1()
412                                .child(Disclosure::new("tool-use-disclosure", is_open).on_click(
413                                    cx.listener({
414                                        let tool_use_id = tool_use.id.clone();
415                                        move |this, _event, _window, _cx| {
416                                            let is_open = this
417                                                .expanded_tool_uses
418                                                .entry(tool_use_id.clone())
419                                                .or_insert(false);
420
421                                            *is_open = !*is_open;
422                                        }
423                                    }),
424                                ))
425                                .child(Label::new(tool_use.name)),
426                        )
427                        .child(
428                            Label::new(match tool_use.status {
429                                ToolUseStatus::Pending => "Pending",
430                                ToolUseStatus::Running => "Running",
431                                ToolUseStatus::Finished(_) => "Finished",
432                                ToolUseStatus::Error(_) => "Error",
433                            })
434                            .size(LabelSize::XSmall)
435                            .buffer_font(cx),
436                        ),
437                )
438                .map(|parent| {
439                    if !is_open {
440                        return parent;
441                    }
442
443                    parent.child(
444                        v_flex()
445                            .child(
446                                v_flex()
447                                    .gap_0p5()
448                                    .py_1()
449                                    .px_2p5()
450                                    .border_b_1()
451                                    .border_color(cx.theme().colors().border)
452                                    .child(Label::new("Input:"))
453                                    .child(Label::new(
454                                        serde_json::to_string_pretty(&tool_use.input)
455                                            .unwrap_or_default(),
456                                    )),
457                            )
458                            .map(|parent| match tool_use.status {
459                                ToolUseStatus::Finished(output) => parent.child(
460                                    v_flex()
461                                        .gap_0p5()
462                                        .py_1()
463                                        .px_2p5()
464                                        .child(Label::new("Result:"))
465                                        .child(Label::new(output)),
466                                ),
467                                ToolUseStatus::Error(err) => parent.child(
468                                    v_flex()
469                                        .gap_0p5()
470                                        .py_1()
471                                        .px_2p5()
472                                        .child(Label::new("Error:"))
473                                        .child(Label::new(err)),
474                                ),
475                                ToolUseStatus::Pending | ToolUseStatus::Running => parent,
476                            }),
477                    )
478                }),
479        )
480    }
481}
482
483impl Render for ActiveThread {
484    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
485        v_flex()
486            .size_full()
487            .child(list(self.list_state.clone()).flex_grow())
488    }
489}