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