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