assistant_panel.rs

  1use std::sync::Arc;
  2
  3use anyhow::Result;
  4use assistant_tool::ToolWorkingSet;
  5use client::zed_urls;
  6use fs::Fs;
  7use gpui::{
  8    prelude::*, px, svg, Action, AnyElement, AppContext, AsyncWindowContext, EventEmitter,
  9    FocusHandle, FocusableView, FontWeight, Model, Pixels, Task, View, ViewContext, WeakView,
 10    WindowContext,
 11};
 12use language::LanguageRegistry;
 13use settings::Settings;
 14use time::UtcOffset;
 15use ui::{prelude::*, KeyBinding, Tab, Tooltip};
 16use workspace::dock::{DockPosition, Panel, PanelEvent};
 17use workspace::Workspace;
 18
 19use crate::active_thread::ActiveThread;
 20use crate::assistant_settings::{AssistantDockPosition, AssistantSettings};
 21use crate::message_editor::MessageEditor;
 22use crate::thread::{Thread, ThreadError, ThreadId};
 23use crate::thread_history::{PastThread, ThreadHistory};
 24use crate::thread_store::ThreadStore;
 25use crate::{NewThread, OpenHistory, ToggleFocus};
 26
 27pub fn init(cx: &mut AppContext) {
 28    cx.observe_new_views(
 29        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
 30            workspace
 31                .register_action(|workspace, _: &ToggleFocus, cx| {
 32                    workspace.toggle_panel_focus::<AssistantPanel>(cx);
 33                })
 34                .register_action(|workspace, _: &NewThread, cx| {
 35                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
 36                        panel.update(cx, |panel, cx| panel.new_thread(cx));
 37                        workspace.focus_panel::<AssistantPanel>(cx);
 38                    }
 39                })
 40                .register_action(|workspace, _: &OpenHistory, cx| {
 41                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
 42                        workspace.focus_panel::<AssistantPanel>(cx);
 43                        panel.update(cx, |panel, cx| panel.open_history(cx));
 44                    }
 45                });
 46        },
 47    )
 48    .detach();
 49}
 50
 51enum ActiveView {
 52    Thread,
 53    History,
 54}
 55
 56pub struct AssistantPanel {
 57    workspace: WeakView<Workspace>,
 58    fs: Arc<dyn Fs>,
 59    language_registry: Arc<LanguageRegistry>,
 60    thread_store: Model<ThreadStore>,
 61    thread: View<ActiveThread>,
 62    message_editor: View<MessageEditor>,
 63    tools: Arc<ToolWorkingSet>,
 64    local_timezone: UtcOffset,
 65    active_view: ActiveView,
 66    history: View<ThreadHistory>,
 67    width: Option<Pixels>,
 68    height: Option<Pixels>,
 69}
 70
 71impl AssistantPanel {
 72    pub fn load(
 73        workspace: WeakView<Workspace>,
 74        cx: AsyncWindowContext,
 75    ) -> Task<Result<View<Self>>> {
 76        cx.spawn(|mut cx| async move {
 77            let tools = Arc::new(ToolWorkingSet::default());
 78            let thread_store = workspace
 79                .update(&mut cx, |workspace, cx| {
 80                    let project = workspace.project().clone();
 81                    ThreadStore::new(project, tools.clone(), cx)
 82                })?
 83                .await?;
 84
 85            workspace.update(&mut cx, |workspace, cx| {
 86                cx.new_view(|cx| Self::new(workspace, thread_store, tools, cx))
 87            })
 88        })
 89    }
 90
 91    fn new(
 92        workspace: &Workspace,
 93        thread_store: Model<ThreadStore>,
 94        tools: Arc<ToolWorkingSet>,
 95        cx: &mut ViewContext<Self>,
 96    ) -> Self {
 97        let thread = thread_store.update(cx, |this, cx| this.create_thread(cx));
 98        let fs = workspace.app_state().fs.clone();
 99        let language_registry = workspace.project().read(cx).languages().clone();
100        let workspace = workspace.weak_handle();
101        let weak_self = cx.view().downgrade();
102
103        Self {
104            active_view: ActiveView::Thread,
105            workspace: workspace.clone(),
106            fs: fs.clone(),
107            language_registry: language_registry.clone(),
108            thread_store: thread_store.clone(),
109            thread: cx.new_view(|cx| {
110                ActiveThread::new(
111                    thread.clone(),
112                    workspace.clone(),
113                    language_registry,
114                    tools.clone(),
115                    cx,
116                )
117            }),
118            message_editor: cx.new_view(|cx| {
119                MessageEditor::new(
120                    fs.clone(),
121                    workspace,
122                    thread_store.downgrade(),
123                    thread.clone(),
124                    cx,
125                )
126            }),
127            tools,
128            local_timezone: UtcOffset::from_whole_seconds(
129                chrono::Local::now().offset().local_minus_utc(),
130            )
131            .unwrap(),
132            history: cx.new_view(|cx| ThreadHistory::new(weak_self, thread_store, cx)),
133            width: None,
134            height: None,
135        }
136    }
137
138    pub(crate) fn local_timezone(&self) -> UtcOffset {
139        self.local_timezone
140    }
141
142    pub(crate) fn thread_store(&self) -> &Model<ThreadStore> {
143        &self.thread_store
144    }
145
146    fn new_thread(&mut self, cx: &mut ViewContext<Self>) {
147        let thread = self
148            .thread_store
149            .update(cx, |this, cx| this.create_thread(cx));
150
151        self.active_view = ActiveView::Thread;
152        self.thread = cx.new_view(|cx| {
153            ActiveThread::new(
154                thread.clone(),
155                self.workspace.clone(),
156                self.language_registry.clone(),
157                self.tools.clone(),
158                cx,
159            )
160        });
161        self.message_editor = cx.new_view(|cx| {
162            MessageEditor::new(
163                self.fs.clone(),
164                self.workspace.clone(),
165                self.thread_store.downgrade(),
166                thread,
167                cx,
168            )
169        });
170        self.message_editor.focus_handle(cx).focus(cx);
171    }
172
173    fn open_history(&mut self, cx: &mut ViewContext<Self>) {
174        self.active_view = ActiveView::History;
175        self.history.focus_handle(cx).focus(cx);
176        cx.notify();
177    }
178
179    pub(crate) fn open_thread(&mut self, thread_id: &ThreadId, cx: &mut ViewContext<Self>) {
180        let Some(thread) = self
181            .thread_store
182            .update(cx, |this, cx| this.open_thread(thread_id, cx))
183        else {
184            return;
185        };
186
187        self.active_view = ActiveView::Thread;
188        self.thread = cx.new_view(|cx| {
189            ActiveThread::new(
190                thread.clone(),
191                self.workspace.clone(),
192                self.language_registry.clone(),
193                self.tools.clone(),
194                cx,
195            )
196        });
197        self.message_editor = cx.new_view(|cx| {
198            MessageEditor::new(
199                self.fs.clone(),
200                self.workspace.clone(),
201                self.thread_store.downgrade(),
202                thread,
203                cx,
204            )
205        });
206        self.message_editor.focus_handle(cx).focus(cx);
207    }
208
209    pub(crate) fn active_thread(&self, cx: &AppContext) -> Model<Thread> {
210        self.thread.read(cx).thread.clone()
211    }
212
213    pub(crate) fn delete_thread(&mut self, thread_id: &ThreadId, cx: &mut ViewContext<Self>) {
214        self.thread_store
215            .update(cx, |this, cx| this.delete_thread(thread_id, cx));
216    }
217}
218
219impl FocusableView for AssistantPanel {
220    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
221        match self.active_view {
222            ActiveView::Thread => self.message_editor.focus_handle(cx),
223            ActiveView::History => self.history.focus_handle(cx),
224        }
225    }
226}
227
228impl EventEmitter<PanelEvent> for AssistantPanel {}
229
230impl Panel for AssistantPanel {
231    fn persistent_name() -> &'static str {
232        "AssistantPanel2"
233    }
234
235    fn position(&self, _cx: &WindowContext) -> DockPosition {
236        DockPosition::Right
237    }
238
239    fn position_is_valid(&self, _: DockPosition) -> bool {
240        true
241    }
242
243    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
244        settings::update_settings_file::<AssistantSettings>(
245            self.fs.clone(),
246            cx,
247            move |settings, _| {
248                let dock = match position {
249                    DockPosition::Left => AssistantDockPosition::Left,
250                    DockPosition::Bottom => AssistantDockPosition::Bottom,
251                    DockPosition::Right => AssistantDockPosition::Right,
252                };
253                settings.set_dock(dock);
254            },
255        );
256    }
257
258    fn size(&self, cx: &WindowContext) -> Pixels {
259        let settings = AssistantSettings::get_global(cx);
260        match self.position(cx) {
261            DockPosition::Left | DockPosition::Right => {
262                self.width.unwrap_or(settings.default_width)
263            }
264            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
265        }
266    }
267
268    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
269        match self.position(cx) {
270            DockPosition::Left | DockPosition::Right => self.width = size,
271            DockPosition::Bottom => self.height = size,
272        }
273        cx.notify();
274    }
275
276    fn set_active(&mut self, _active: bool, _cx: &mut ViewContext<Self>) {}
277
278    fn remote_id() -> Option<proto::PanelId> {
279        Some(proto::PanelId::AssistantPanel)
280    }
281
282    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
283        let settings = AssistantSettings::get_global(cx);
284        if !settings.enabled || !settings.button {
285            return None;
286        }
287
288        Some(IconName::ZedAssistant2)
289    }
290
291    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
292        Some("Assistant Panel")
293    }
294
295    fn toggle_action(&self) -> Box<dyn Action> {
296        Box::new(ToggleFocus)
297    }
298
299    fn activation_priority(&self) -> u32 {
300        3
301    }
302}
303
304impl AssistantPanel {
305    fn render_toolbar(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
306        let focus_handle = self.focus_handle(cx);
307
308        let thread = self.thread.read(cx);
309
310        let title = if thread.is_empty() {
311            thread.summary_or_default(cx)
312        } else {
313            thread
314                .summary(cx)
315                .unwrap_or_else(|| SharedString::from("Loading Summary…"))
316        };
317
318        h_flex()
319            .id("assistant-toolbar")
320            .px(DynamicSpacing::Base08.rems(cx))
321            .h(Tab::container_height(cx))
322            .flex_none()
323            .justify_between()
324            .gap(DynamicSpacing::Base08.rems(cx))
325            .bg(cx.theme().colors().tab_bar_background)
326            .border_b_1()
327            .border_color(cx.theme().colors().border)
328            .child(h_flex().child(Label::new(title)))
329            .child(
330                h_flex()
331                    .h_full()
332                    .pl_1p5()
333                    .border_l_1()
334                    .border_color(cx.theme().colors().border)
335                    .gap(DynamicSpacing::Base02.rems(cx))
336                    .child(
337                        IconButton::new("new-thread", IconName::Plus)
338                            .icon_size(IconSize::Small)
339                            .style(ButtonStyle::Subtle)
340                            .tooltip({
341                                let focus_handle = focus_handle.clone();
342                                move |cx| {
343                                    Tooltip::for_action_in(
344                                        "New Thread",
345                                        &NewThread,
346                                        &focus_handle,
347                                        cx,
348                                    )
349                                }
350                            })
351                            .on_click(move |_event, cx| {
352                                cx.dispatch_action(NewThread.boxed_clone());
353                            }),
354                    )
355                    .child(
356                        IconButton::new("open-history", IconName::HistoryRerun)
357                            .icon_size(IconSize::Small)
358                            .style(ButtonStyle::Subtle)
359                            .tooltip({
360                                let focus_handle = focus_handle.clone();
361                                move |cx| {
362                                    Tooltip::for_action_in(
363                                        "Open History",
364                                        &OpenHistory,
365                                        &focus_handle,
366                                        cx,
367                                    )
368                                }
369                            })
370                            .on_click(move |_event, cx| {
371                                cx.dispatch_action(OpenHistory.boxed_clone());
372                            }),
373                    )
374                    .child(
375                        IconButton::new("configure-assistant", IconName::Settings)
376                            .icon_size(IconSize::Small)
377                            .style(ButtonStyle::Subtle)
378                            .tooltip(move |cx| Tooltip::text("Configure Assistant", cx))
379                            .on_click(move |_event, _cx| {
380                                println!("Configure Assistant");
381                            }),
382                    ),
383            )
384    }
385
386    fn render_active_thread_or_empty_state(&self, cx: &mut ViewContext<Self>) -> AnyElement {
387        if self.thread.read(cx).is_empty() {
388            return self.render_thread_empty_state(cx).into_any_element();
389        }
390
391        self.thread.clone().into_any()
392    }
393
394    fn render_thread_empty_state(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
395        let recent_threads = self
396            .thread_store
397            .update(cx, |this, cx| this.recent_threads(3, cx));
398
399        v_flex()
400            .gap_2()
401            .child(
402                v_flex().w_full().child(
403                    svg()
404                        .path("icons/logo_96.svg")
405                        .text_color(cx.theme().colors().text)
406                        .w(px(40.))
407                        .h(px(40.))
408                        .mx_auto()
409                        .mb_4(),
410                ),
411            )
412            .when(!recent_threads.is_empty(), |parent| {
413                parent
414                    .child(
415                        h_flex().w_full().justify_center().child(
416                            Label::new("Recent Threads:")
417                                .size(LabelSize::Small)
418                                .color(Color::Muted),
419                        ),
420                    )
421                    .child(
422                        v_flex().mx_auto().w_4_5().gap_2().children(
423                            recent_threads
424                                .into_iter()
425                                .map(|thread| PastThread::new(thread, cx.view().downgrade())),
426                        ),
427                    )
428                    .child(
429                        h_flex().w_full().justify_center().child(
430                            Button::new("view-all-past-threads", "View All Past Threads")
431                                .style(ButtonStyle::Subtle)
432                                .label_size(LabelSize::Small)
433                                .key_binding(KeyBinding::for_action_in(
434                                    &OpenHistory,
435                                    &self.focus_handle(cx),
436                                    cx,
437                                ))
438                                .on_click(move |_event, cx| {
439                                    cx.dispatch_action(OpenHistory.boxed_clone());
440                                }),
441                        ),
442                    )
443            })
444    }
445
446    fn render_last_error(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
447        let last_error = self.thread.read(cx).last_error()?;
448
449        Some(
450            div()
451                .absolute()
452                .right_3()
453                .bottom_12()
454                .max_w_96()
455                .py_2()
456                .px_3()
457                .elevation_2(cx)
458                .occlude()
459                .child(match last_error {
460                    ThreadError::PaymentRequired => self.render_payment_required_error(cx),
461                    ThreadError::MaxMonthlySpendReached => {
462                        self.render_max_monthly_spend_reached_error(cx)
463                    }
464                    ThreadError::Message(error_message) => {
465                        self.render_error_message(&error_message, cx)
466                    }
467                })
468                .into_any(),
469        )
470    }
471
472    fn render_payment_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
473        const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
474
475        v_flex()
476            .gap_0p5()
477            .child(
478                h_flex()
479                    .gap_1p5()
480                    .items_center()
481                    .child(Icon::new(IconName::XCircle).color(Color::Error))
482                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
483            )
484            .child(
485                div()
486                    .id("error-message")
487                    .max_h_24()
488                    .overflow_y_scroll()
489                    .child(Label::new(ERROR_MESSAGE)),
490            )
491            .child(
492                h_flex()
493                    .justify_end()
494                    .mt_1()
495                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
496                        |this, _, cx| {
497                            this.thread.update(cx, |this, _cx| {
498                                this.clear_last_error();
499                            });
500
501                            cx.open_url(&zed_urls::account_url(cx));
502                            cx.notify();
503                        },
504                    )))
505                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
506                        |this, _, cx| {
507                            this.thread.update(cx, |this, _cx| {
508                                this.clear_last_error();
509                            });
510
511                            cx.notify();
512                        },
513                    ))),
514            )
515            .into_any()
516    }
517
518    fn render_max_monthly_spend_reached_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
519        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
520
521        v_flex()
522            .gap_0p5()
523            .child(
524                h_flex()
525                    .gap_1p5()
526                    .items_center()
527                    .child(Icon::new(IconName::XCircle).color(Color::Error))
528                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
529            )
530            .child(
531                div()
532                    .id("error-message")
533                    .max_h_24()
534                    .overflow_y_scroll()
535                    .child(Label::new(ERROR_MESSAGE)),
536            )
537            .child(
538                h_flex()
539                    .justify_end()
540                    .mt_1()
541                    .child(
542                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
543                            cx.listener(|this, _, cx| {
544                                this.thread.update(cx, |this, _cx| {
545                                    this.clear_last_error();
546                                });
547
548                                cx.open_url(&zed_urls::account_url(cx));
549                                cx.notify();
550                            }),
551                        ),
552                    )
553                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
554                        |this, _, cx| {
555                            this.thread.update(cx, |this, _cx| {
556                                this.clear_last_error();
557                            });
558
559                            cx.notify();
560                        },
561                    ))),
562            )
563            .into_any()
564    }
565
566    fn render_error_message(
567        &self,
568        error_message: &SharedString,
569        cx: &mut ViewContext<Self>,
570    ) -> AnyElement {
571        v_flex()
572            .gap_0p5()
573            .child(
574                h_flex()
575                    .gap_1p5()
576                    .items_center()
577                    .child(Icon::new(IconName::XCircle).color(Color::Error))
578                    .child(
579                        Label::new("Error interacting with language model")
580                            .weight(FontWeight::MEDIUM),
581                    ),
582            )
583            .child(
584                div()
585                    .id("error-message")
586                    .max_h_32()
587                    .overflow_y_scroll()
588                    .child(Label::new(error_message.clone())),
589            )
590            .child(
591                h_flex()
592                    .justify_end()
593                    .mt_1()
594                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
595                        |this, _, cx| {
596                            this.thread.update(cx, |this, _cx| {
597                                this.clear_last_error();
598                            });
599
600                            cx.notify();
601                        },
602                    ))),
603            )
604            .into_any()
605    }
606}
607
608impl Render for AssistantPanel {
609    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
610        v_flex()
611            .key_context("AssistantPanel2")
612            .justify_between()
613            .size_full()
614            .on_action(cx.listener(|this, _: &NewThread, cx| {
615                this.new_thread(cx);
616            }))
617            .on_action(cx.listener(|this, _: &OpenHistory, cx| {
618                this.open_history(cx);
619            }))
620            .child(self.render_toolbar(cx))
621            .map(|parent| match self.active_view {
622                ActiveView::Thread => parent
623                    .child(self.render_active_thread_or_empty_state(cx))
624                    .child(
625                        h_flex()
626                            .border_t_1()
627                            .border_color(cx.theme().colors().border)
628                            .child(self.message_editor.clone()),
629                    )
630                    .children(self.render_last_error(cx)),
631                ActiveView::History => parent.child(self.history.clone()),
632            })
633    }
634}