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