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