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        Some(IconName::ZedAssistant2)
284    }
285
286    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
287        Some("Assistant Panel")
288    }
289
290    fn toggle_action(&self) -> Box<dyn Action> {
291        Box::new(ToggleFocus)
292    }
293
294    fn activation_priority(&self) -> u32 {
295        3
296    }
297}
298
299impl AssistantPanel {
300    fn render_toolbar(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
301        let focus_handle = self.focus_handle(cx);
302
303        let title = if self.thread.read(cx).is_empty() {
304            SharedString::from("New Thread")
305        } else {
306            self.thread
307                .read(cx)
308                .summary(cx)
309                .unwrap_or_else(|| SharedString::from("Loading Summary…"))
310        };
311
312        h_flex()
313            .id("assistant-toolbar")
314            .px(DynamicSpacing::Base08.rems(cx))
315            .h(Tab::container_height(cx))
316            .flex_none()
317            .justify_between()
318            .gap(DynamicSpacing::Base08.rems(cx))
319            .bg(cx.theme().colors().tab_bar_background)
320            .border_b_1()
321            .border_color(cx.theme().colors().border)
322            .child(h_flex().child(Label::new(title)))
323            .child(
324                h_flex()
325                    .h_full()
326                    .pl_1p5()
327                    .border_l_1()
328                    .border_color(cx.theme().colors().border)
329                    .gap(DynamicSpacing::Base02.rems(cx))
330                    .child(
331                        IconButton::new("new-thread", IconName::Plus)
332                            .icon_size(IconSize::Small)
333                            .style(ButtonStyle::Subtle)
334                            .tooltip({
335                                let focus_handle = focus_handle.clone();
336                                move |cx| {
337                                    Tooltip::for_action_in(
338                                        "New Thread",
339                                        &NewThread,
340                                        &focus_handle,
341                                        cx,
342                                    )
343                                }
344                            })
345                            .on_click(move |_event, cx| {
346                                cx.dispatch_action(NewThread.boxed_clone());
347                            }),
348                    )
349                    .child(
350                        IconButton::new("open-history", IconName::HistoryRerun)
351                            .icon_size(IconSize::Small)
352                            .style(ButtonStyle::Subtle)
353                            .tooltip({
354                                let focus_handle = focus_handle.clone();
355                                move |cx| {
356                                    Tooltip::for_action_in(
357                                        "Open History",
358                                        &OpenHistory,
359                                        &focus_handle,
360                                        cx,
361                                    )
362                                }
363                            })
364                            .on_click(move |_event, cx| {
365                                cx.dispatch_action(OpenHistory.boxed_clone());
366                            }),
367                    )
368                    .child(
369                        IconButton::new("configure-assistant", IconName::Settings)
370                            .icon_size(IconSize::Small)
371                            .style(ButtonStyle::Subtle)
372                            .tooltip(move |cx| Tooltip::text("Configure Assistant", cx))
373                            .on_click(move |_event, _cx| {
374                                println!("Configure Assistant");
375                            }),
376                    ),
377            )
378    }
379
380    fn render_active_thread_or_empty_state(&self, cx: &mut ViewContext<Self>) -> AnyElement {
381        if self.thread.read(cx).is_empty() {
382            return self.render_thread_empty_state(cx).into_any_element();
383        }
384
385        self.thread.clone().into_any()
386    }
387
388    fn render_thread_empty_state(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
389        let recent_threads = self
390            .thread_store
391            .update(cx, |this, cx| this.recent_threads(3, cx));
392
393        v_flex()
394            .gap_2()
395            .child(
396                v_flex().w_full().child(
397                    svg()
398                        .path("icons/logo_96.svg")
399                        .text_color(cx.theme().colors().text)
400                        .w(px(40.))
401                        .h(px(40.))
402                        .mx_auto()
403                        .mb_4(),
404                ),
405            )
406            .when(!recent_threads.is_empty(), |parent| {
407                parent
408                    .child(
409                        h_flex().w_full().justify_center().child(
410                            Label::new("Recent Threads:")
411                                .size(LabelSize::Small)
412                                .color(Color::Muted),
413                        ),
414                    )
415                    .child(
416                        v_flex().mx_auto().w_4_5().gap_2().children(
417                            recent_threads
418                                .into_iter()
419                                .map(|thread| PastThread::new(thread, cx.view().downgrade())),
420                        ),
421                    )
422                    .child(
423                        h_flex().w_full().justify_center().child(
424                            Button::new("view-all-past-threads", "View All Past Threads")
425                                .style(ButtonStyle::Subtle)
426                                .label_size(LabelSize::Small)
427                                .key_binding(KeyBinding::for_action_in(
428                                    &OpenHistory,
429                                    &self.focus_handle(cx),
430                                    cx,
431                                ))
432                                .on_click(move |_event, cx| {
433                                    cx.dispatch_action(OpenHistory.boxed_clone());
434                                }),
435                        ),
436                    )
437            })
438    }
439
440    fn render_last_error(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
441        let last_error = self.thread.read(cx).last_error()?;
442
443        Some(
444            div()
445                .absolute()
446                .right_3()
447                .bottom_12()
448                .max_w_96()
449                .py_2()
450                .px_3()
451                .elevation_2(cx)
452                .occlude()
453                .child(match last_error {
454                    ThreadError::PaymentRequired => self.render_payment_required_error(cx),
455                    ThreadError::MaxMonthlySpendReached => {
456                        self.render_max_monthly_spend_reached_error(cx)
457                    }
458                    ThreadError::Message(error_message) => {
459                        self.render_error_message(&error_message, cx)
460                    }
461                })
462                .into_any(),
463        )
464    }
465
466    fn render_payment_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
467        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.";
468
469        v_flex()
470            .gap_0p5()
471            .child(
472                h_flex()
473                    .gap_1p5()
474                    .items_center()
475                    .child(Icon::new(IconName::XCircle).color(Color::Error))
476                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
477            )
478            .child(
479                div()
480                    .id("error-message")
481                    .max_h_24()
482                    .overflow_y_scroll()
483                    .child(Label::new(ERROR_MESSAGE)),
484            )
485            .child(
486                h_flex()
487                    .justify_end()
488                    .mt_1()
489                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
490                        |this, _, cx| {
491                            this.thread.update(cx, |this, _cx| {
492                                this.clear_last_error();
493                            });
494
495                            cx.open_url(&zed_urls::account_url(cx));
496                            cx.notify();
497                        },
498                    )))
499                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
500                        |this, _, cx| {
501                            this.thread.update(cx, |this, _cx| {
502                                this.clear_last_error();
503                            });
504
505                            cx.notify();
506                        },
507                    ))),
508            )
509            .into_any()
510    }
511
512    fn render_max_monthly_spend_reached_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
513        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
514
515        v_flex()
516            .gap_0p5()
517            .child(
518                h_flex()
519                    .gap_1p5()
520                    .items_center()
521                    .child(Icon::new(IconName::XCircle).color(Color::Error))
522                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
523            )
524            .child(
525                div()
526                    .id("error-message")
527                    .max_h_24()
528                    .overflow_y_scroll()
529                    .child(Label::new(ERROR_MESSAGE)),
530            )
531            .child(
532                h_flex()
533                    .justify_end()
534                    .mt_1()
535                    .child(
536                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
537                            cx.listener(|this, _, cx| {
538                                this.thread.update(cx, |this, _cx| {
539                                    this.clear_last_error();
540                                });
541
542                                cx.open_url(&zed_urls::account_url(cx));
543                                cx.notify();
544                            }),
545                        ),
546                    )
547                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
548                        |this, _, cx| {
549                            this.thread.update(cx, |this, _cx| {
550                                this.clear_last_error();
551                            });
552
553                            cx.notify();
554                        },
555                    ))),
556            )
557            .into_any()
558    }
559
560    fn render_error_message(
561        &self,
562        error_message: &SharedString,
563        cx: &mut ViewContext<Self>,
564    ) -> AnyElement {
565        v_flex()
566            .gap_0p5()
567            .child(
568                h_flex()
569                    .gap_1p5()
570                    .items_center()
571                    .child(Icon::new(IconName::XCircle).color(Color::Error))
572                    .child(
573                        Label::new("Error interacting with language model")
574                            .weight(FontWeight::MEDIUM),
575                    ),
576            )
577            .child(
578                div()
579                    .id("error-message")
580                    .max_h_32()
581                    .overflow_y_scroll()
582                    .child(Label::new(error_message.clone())),
583            )
584            .child(
585                h_flex()
586                    .justify_end()
587                    .mt_1()
588                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
589                        |this, _, cx| {
590                            this.thread.update(cx, |this, _cx| {
591                                this.clear_last_error();
592                            });
593
594                            cx.notify();
595                        },
596                    ))),
597            )
598            .into_any()
599    }
600}
601
602impl Render for AssistantPanel {
603    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
604        v_flex()
605            .key_context("AssistantPanel2")
606            .justify_between()
607            .size_full()
608            .on_action(cx.listener(|this, _: &NewThread, cx| {
609                this.new_thread(cx);
610            }))
611            .on_action(cx.listener(|this, _: &OpenHistory, cx| {
612                this.open_history(cx);
613            }))
614            .child(self.render_toolbar(cx))
615            .map(|parent| match self.active_view {
616                ActiveView::Thread => parent
617                    .child(self.render_active_thread_or_empty_state(cx))
618                    .child(
619                        h_flex()
620                            .border_t_1()
621                            .border_color(cx.theme().colors().border)
622                            .child(self.message_editor.clone()),
623                    )
624                    .children(self.render_last_error(cx)),
625                ActiveView::History => parent.child(self.history.clone()),
626            })
627    }
628}