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