1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
3 AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
4 ToolCallStatus, UserMessageId,
5};
6use acp_thread::{AgentConnection, Plan};
7use action_log::ActionLog;
8use agent_client_protocol::{self as acp, PromptCapabilities};
9use agent_servers::{AgentServer, AgentServerDelegate, ClaudeCode};
10use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, NotifyWhenAgentWaiting};
11use agent2::{DbThreadMetadata, HistoryEntry, HistoryEntryId, HistoryStore, NativeAgentServer};
12use anyhow::{Context as _, Result, anyhow, bail};
13use audio::{Audio, Sound};
14use buffer_diff::BufferDiff;
15use client::zed_urls;
16use collections::{HashMap, HashSet};
17use editor::scroll::Autoscroll;
18use editor::{Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects};
19use file_icons::FileIcons;
20use fs::Fs;
21use futures::FutureExt as _;
22use gpui::{
23 Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
24 CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
25 ListOffset, ListState, MouseButton, PlatformDisplay, SharedString, Stateful, StyleRefinement,
26 Subscription, Task, TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window,
27 WindowHandle, div, ease_in_out, linear_color_stop, linear_gradient, list, point, prelude::*,
28 pulsating_between,
29};
30use language::Buffer;
31
32use language_model::LanguageModelRegistry;
33use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
34use project::{Project, ProjectEntryId};
35use prompt_store::{PromptId, PromptStore};
36use rope::Point;
37use settings::{Settings as _, SettingsStore};
38use std::cell::{Cell, RefCell};
39use std::path::Path;
40use std::sync::Arc;
41use std::time::Instant;
42use std::{collections::BTreeMap, rc::Rc, time::Duration};
43use task::SpawnInTerminal;
44use terminal_view::terminal_panel::TerminalPanel;
45use text::Anchor;
46use theme::ThemeSettings;
47use ui::{
48 Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
49 PopoverMenuHandle, Scrollbar, ScrollbarState, SpinnerLabel, TintColor, Tooltip, prelude::*,
50};
51use util::{ResultExt, size::format_file_size, time::duration_alt_display};
52use workspace::{CollaboratorId, Workspace};
53use zed_actions::agent::{Chat, ToggleModelSelector};
54use zed_actions::assistant::OpenRulesLibrary;
55
56use super::entry_view_state::EntryViewState;
57use crate::acp::AcpModelSelectorPopover;
58use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
59use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
60use crate::agent_diff::AgentDiff;
61use crate::profile_selector::{ProfileProvider, ProfileSelector};
62
63use crate::ui::preview::UsageCallout;
64use crate::ui::{
65 AgentNotification, AgentNotificationEvent, BurnModeTooltip, UnavailableEditingTooltip,
66};
67use crate::{
68 AgentDiffPane, AgentPanel, ContinueThread, ContinueWithBurnMode, ExpandMessageEditor, Follow,
69 KeepAll, OpenAgentDiff, OpenHistory, RejectAll, ToggleBurnMode, ToggleProfileSelector,
70};
71
72pub const MIN_EDITOR_LINES: usize = 4;
73pub const MAX_EDITOR_LINES: usize = 8;
74
75#[derive(Copy, Clone, Debug, PartialEq, Eq)]
76enum ThreadFeedback {
77 Positive,
78 Negative,
79}
80
81#[derive(Debug)]
82enum ThreadError {
83 PaymentRequired,
84 ModelRequestLimitReached(cloud_llm_client::Plan),
85 ToolUseLimitReached,
86 Refusal,
87 AuthenticationRequired(SharedString),
88 Other(SharedString),
89}
90
91impl ThreadError {
92 fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
93 if error.is::<language_model::PaymentRequiredError>() {
94 Self::PaymentRequired
95 } else if error.is::<language_model::ToolUseLimitReachedError>() {
96 Self::ToolUseLimitReached
97 } else if let Some(error) =
98 error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
99 {
100 Self::ModelRequestLimitReached(error.plan)
101 } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
102 && acp_error.code == acp::ErrorCode::AUTH_REQUIRED.code
103 {
104 Self::AuthenticationRequired(acp_error.message.clone().into())
105 } else {
106 let string = error.to_string();
107 // TODO: we should have Gemini return better errors here.
108 if agent.clone().downcast::<agent_servers::Gemini>().is_some()
109 && string.contains("Could not load the default credentials")
110 || string.contains("API key not valid")
111 || string.contains("Request had invalid authentication credentials")
112 {
113 Self::AuthenticationRequired(string.into())
114 } else {
115 Self::Other(error.to_string().into())
116 }
117 }
118 }
119}
120
121impl ProfileProvider for Entity<agent2::Thread> {
122 fn profile_id(&self, cx: &App) -> AgentProfileId {
123 self.read(cx).profile().clone()
124 }
125
126 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
127 self.update(cx, |thread, _cx| {
128 thread.set_profile(profile_id);
129 });
130 }
131
132 fn profiles_supported(&self, cx: &App) -> bool {
133 self.read(cx)
134 .model()
135 .is_some_and(|model| model.supports_tools())
136 }
137}
138
139#[derive(Default)]
140struct ThreadFeedbackState {
141 feedback: Option<ThreadFeedback>,
142 comments_editor: Option<Entity<Editor>>,
143}
144
145impl ThreadFeedbackState {
146 pub fn submit(
147 &mut self,
148 thread: Entity<AcpThread>,
149 feedback: ThreadFeedback,
150 window: &mut Window,
151 cx: &mut App,
152 ) {
153 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
154 return;
155 };
156
157 if self.feedback == Some(feedback) {
158 return;
159 }
160
161 self.feedback = Some(feedback);
162 match feedback {
163 ThreadFeedback::Positive => {
164 self.comments_editor = None;
165 }
166 ThreadFeedback::Negative => {
167 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
168 }
169 }
170 let session_id = thread.read(cx).session_id().clone();
171 let agent_name = telemetry.agent_name();
172 let task = telemetry.thread_data(&session_id, cx);
173 let rating = match feedback {
174 ThreadFeedback::Positive => "positive",
175 ThreadFeedback::Negative => "negative",
176 };
177 cx.background_spawn(async move {
178 let thread = task.await?;
179 telemetry::event!(
180 "Agent Thread Rated",
181 session_id = session_id,
182 rating = rating,
183 agent = agent_name,
184 thread = thread
185 );
186 anyhow::Ok(())
187 })
188 .detach_and_log_err(cx);
189 }
190
191 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
192 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
193 return;
194 };
195
196 let Some(comments) = self
197 .comments_editor
198 .as_ref()
199 .map(|editor| editor.read(cx).text(cx))
200 .filter(|text| !text.trim().is_empty())
201 else {
202 return;
203 };
204
205 self.comments_editor.take();
206
207 let session_id = thread.read(cx).session_id().clone();
208 let agent_name = telemetry.agent_name();
209 let task = telemetry.thread_data(&session_id, cx);
210 cx.background_spawn(async move {
211 let thread = task.await?;
212 telemetry::event!(
213 "Agent Thread Feedback Comments",
214 session_id = session_id,
215 comments = comments,
216 agent = agent_name,
217 thread = thread
218 );
219 anyhow::Ok(())
220 })
221 .detach_and_log_err(cx);
222 }
223
224 pub fn clear(&mut self) {
225 *self = Self::default()
226 }
227
228 pub fn dismiss_comments(&mut self) {
229 self.comments_editor.take();
230 }
231
232 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
233 let buffer = cx.new(|cx| {
234 let empty_string = String::new();
235 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
236 });
237
238 let editor = cx.new(|cx| {
239 let mut editor = Editor::new(
240 editor::EditorMode::AutoHeight {
241 min_lines: 1,
242 max_lines: Some(4),
243 },
244 buffer,
245 None,
246 window,
247 cx,
248 );
249 editor.set_placeholder_text(
250 "What went wrong? Share your feedback so we can improve.",
251 cx,
252 );
253 editor
254 });
255
256 editor.read(cx).focus_handle(cx).focus(window);
257 editor
258 }
259}
260
261pub struct AcpThreadView {
262 agent: Rc<dyn AgentServer>,
263 workspace: WeakEntity<Workspace>,
264 project: Entity<Project>,
265 thread_state: ThreadState,
266 history_store: Entity<HistoryStore>,
267 hovered_recent_history_item: Option<usize>,
268 entry_view_state: Entity<EntryViewState>,
269 message_editor: Entity<MessageEditor>,
270 focus_handle: FocusHandle,
271 model_selector: Option<Entity<AcpModelSelectorPopover>>,
272 profile_selector: Option<Entity<ProfileSelector>>,
273 notifications: Vec<WindowHandle<AgentNotification>>,
274 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
275 thread_retry_status: Option<RetryStatus>,
276 thread_error: Option<ThreadError>,
277 thread_feedback: ThreadFeedbackState,
278 list_state: ListState,
279 scrollbar_state: ScrollbarState,
280 auth_task: Option<Task<()>>,
281 expanded_tool_calls: HashSet<acp::ToolCallId>,
282 expanded_thinking_blocks: HashSet<(usize, usize)>,
283 edits_expanded: bool,
284 plan_expanded: bool,
285 editor_expanded: bool,
286 should_be_following: bool,
287 editing_message: Option<usize>,
288 prompt_capabilities: Rc<Cell<PromptCapabilities>>,
289 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
290 is_loading_contents: bool,
291 new_server_version_available: Option<SharedString>,
292 _cancel_task: Option<Task<()>>,
293 _subscriptions: [Subscription; 3],
294}
295
296enum ThreadState {
297 Loading(Entity<LoadingView>),
298 Ready {
299 thread: Entity<AcpThread>,
300 title_editor: Option<Entity<Editor>>,
301 _subscriptions: Vec<Subscription>,
302 },
303 LoadError(LoadError),
304 Unauthenticated {
305 connection: Rc<dyn AgentConnection>,
306 description: Option<Entity<Markdown>>,
307 configuration_view: Option<AnyView>,
308 pending_auth_method: Option<acp::AuthMethodId>,
309 _subscription: Option<Subscription>,
310 },
311}
312
313struct LoadingView {
314 title: SharedString,
315 _load_task: Task<()>,
316 _update_title_task: Task<anyhow::Result<()>>,
317}
318
319impl AcpThreadView {
320 pub fn new(
321 agent: Rc<dyn AgentServer>,
322 resume_thread: Option<DbThreadMetadata>,
323 summarize_thread: Option<DbThreadMetadata>,
324 workspace: WeakEntity<Workspace>,
325 project: Entity<Project>,
326 history_store: Entity<HistoryStore>,
327 prompt_store: Option<Entity<PromptStore>>,
328 window: &mut Window,
329 cx: &mut Context<Self>,
330 ) -> Self {
331 let prompt_capabilities = Rc::new(Cell::new(acp::PromptCapabilities::default()));
332 let available_commands = Rc::new(RefCell::new(vec![]));
333
334 let placeholder = if agent.name() == "Zed Agent" {
335 format!("Message the {} — @ to include context", agent.name())
336 } else if agent.name() == "Claude Code" || !available_commands.borrow().is_empty() {
337 format!(
338 "Message {} — @ to include context, / for commands",
339 agent.name()
340 )
341 } else {
342 format!("Message {} — @ to include context", agent.name())
343 };
344
345 let message_editor = cx.new(|cx| {
346 let mut editor = MessageEditor::new(
347 workspace.clone(),
348 project.clone(),
349 history_store.clone(),
350 prompt_store.clone(),
351 prompt_capabilities.clone(),
352 available_commands.clone(),
353 agent.name(),
354 placeholder,
355 editor::EditorMode::AutoHeight {
356 min_lines: MIN_EDITOR_LINES,
357 max_lines: Some(MAX_EDITOR_LINES),
358 },
359 window,
360 cx,
361 );
362 if let Some(entry) = summarize_thread {
363 editor.insert_thread_summary(entry, window, cx);
364 }
365 editor
366 });
367
368 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
369
370 let entry_view_state = cx.new(|_| {
371 EntryViewState::new(
372 workspace.clone(),
373 project.clone(),
374 history_store.clone(),
375 prompt_store.clone(),
376 prompt_capabilities.clone(),
377 available_commands.clone(),
378 agent.name(),
379 )
380 });
381
382 let subscriptions = [
383 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
384 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
385 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
386 ];
387
388 Self {
389 agent: agent.clone(),
390 workspace: workspace.clone(),
391 project: project.clone(),
392 entry_view_state,
393 thread_state: Self::initial_state(agent, resume_thread, workspace, project, window, cx),
394 message_editor,
395 model_selector: None,
396 profile_selector: None,
397 notifications: Vec::new(),
398 notification_subscriptions: HashMap::default(),
399 list_state: list_state.clone(),
400 scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
401 thread_retry_status: None,
402 thread_error: None,
403 thread_feedback: Default::default(),
404 auth_task: None,
405 expanded_tool_calls: HashSet::default(),
406 expanded_thinking_blocks: HashSet::default(),
407 editing_message: None,
408 edits_expanded: false,
409 plan_expanded: false,
410 prompt_capabilities,
411 available_commands,
412 editor_expanded: false,
413 should_be_following: false,
414 history_store,
415 hovered_recent_history_item: None,
416 is_loading_contents: false,
417 _subscriptions: subscriptions,
418 _cancel_task: None,
419 focus_handle: cx.focus_handle(),
420 new_server_version_available: None,
421 }
422 }
423
424 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
425 self.thread_state = Self::initial_state(
426 self.agent.clone(),
427 None,
428 self.workspace.clone(),
429 self.project.clone(),
430 window,
431 cx,
432 );
433 self.available_commands.replace(vec![]);
434 self.new_server_version_available.take();
435 cx.notify();
436 }
437
438 fn initial_state(
439 agent: Rc<dyn AgentServer>,
440 resume_thread: Option<DbThreadMetadata>,
441 workspace: WeakEntity<Workspace>,
442 project: Entity<Project>,
443 window: &mut Window,
444 cx: &mut Context<Self>,
445 ) -> ThreadState {
446 if !project.read(cx).is_local() && agent.clone().downcast::<NativeAgentServer>().is_none() {
447 return ThreadState::LoadError(LoadError::Other(
448 "External agents are not yet supported for remote projects.".into(),
449 ));
450 }
451 let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
452 // Pick the first non-single-file worktree for the root directory if there are any,
453 // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
454 worktrees.sort_by(|l, r| {
455 l.read(cx)
456 .is_single_file()
457 .cmp(&r.read(cx).is_single_file())
458 });
459 let root_dir = worktrees
460 .into_iter()
461 .filter_map(|worktree| {
462 if worktree.read(cx).is_single_file() {
463 Some(worktree.read(cx).abs_path().parent()?.into())
464 } else {
465 Some(worktree.read(cx).abs_path())
466 }
467 })
468 .next()
469 .unwrap_or_else(|| paths::home_dir().as_path().into());
470 let (status_tx, mut status_rx) = watch::channel("Loading…".into());
471 let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
472 let delegate = AgentServerDelegate::new(
473 project.clone(),
474 Some(status_tx),
475 Some(new_version_available_tx),
476 );
477
478 let connect_task = agent.connect(&root_dir, delegate, cx);
479 let load_task = cx.spawn_in(window, async move |this, cx| {
480 let connection = match connect_task.await {
481 Ok(connection) => connection,
482 Err(err) => {
483 this.update_in(cx, |this, window, cx| {
484 if err.downcast_ref::<LoadError>().is_some() {
485 this.handle_load_error(err, window, cx);
486 } else {
487 this.handle_thread_error(err, cx);
488 }
489 cx.notify();
490 })
491 .log_err();
492 return;
493 }
494 };
495
496 let result = if let Some(native_agent) = connection
497 .clone()
498 .downcast::<agent2::NativeAgentConnection>()
499 && let Some(resume) = resume_thread.clone()
500 {
501 cx.update(|_, cx| {
502 native_agent
503 .0
504 .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
505 })
506 .log_err()
507 } else {
508 cx.update(|_, cx| {
509 connection
510 .clone()
511 .new_thread(project.clone(), &root_dir, cx)
512 })
513 .log_err()
514 };
515
516 let Some(result) = result else {
517 return;
518 };
519
520 let result = match result.await {
521 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
522 Ok(err) => {
523 cx.update(|window, cx| {
524 Self::handle_auth_required(this, err, agent, connection, window, cx)
525 })
526 .log_err();
527 return;
528 }
529 Err(err) => Err(err),
530 },
531 Ok(thread) => Ok(thread),
532 };
533
534 this.update_in(cx, |this, window, cx| {
535 match result {
536 Ok(thread) => {
537 let action_log = thread.read(cx).action_log().clone();
538
539 this.prompt_capabilities
540 .set(thread.read(cx).prompt_capabilities());
541
542 let count = thread.read(cx).entries().len();
543 this.entry_view_state.update(cx, |view_state, cx| {
544 for ix in 0..count {
545 view_state.sync_entry(ix, &thread, window, cx);
546 }
547 this.list_state.splice_focusable(
548 0..0,
549 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
550 );
551 });
552
553 if let Some(resume) = resume_thread {
554 this.history_store.update(cx, |history, cx| {
555 history.push_recently_opened_entry(
556 HistoryEntryId::AcpThread(resume.id),
557 cx,
558 );
559 });
560 }
561
562 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
563
564 this.model_selector =
565 thread
566 .read(cx)
567 .connection()
568 .model_selector()
569 .map(|selector| {
570 cx.new(|cx| {
571 AcpModelSelectorPopover::new(
572 thread.read(cx).session_id().clone(),
573 selector,
574 PopoverMenuHandle::default(),
575 this.focus_handle(cx),
576 window,
577 cx,
578 )
579 })
580 });
581
582 let mut subscriptions = vec![
583 cx.subscribe_in(&thread, window, Self::handle_thread_event),
584 cx.observe(&action_log, |_, _, cx| cx.notify()),
585 ];
586
587 let title_editor =
588 if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
589 let editor = cx.new(|cx| {
590 let mut editor = Editor::single_line(window, cx);
591 editor.set_text(thread.read(cx).title(), window, cx);
592 editor
593 });
594 subscriptions.push(cx.subscribe_in(
595 &editor,
596 window,
597 Self::handle_title_editor_event,
598 ));
599 Some(editor)
600 } else {
601 None
602 };
603 this.thread_state = ThreadState::Ready {
604 thread,
605 title_editor,
606 _subscriptions: subscriptions,
607 };
608 this.message_editor.focus_handle(cx).focus(window);
609
610 this.profile_selector = this.as_native_thread(cx).map(|thread| {
611 cx.new(|cx| {
612 ProfileSelector::new(
613 <dyn Fs>::global(cx),
614 Arc::new(thread.clone()),
615 this.focus_handle(cx),
616 cx,
617 )
618 })
619 });
620
621 cx.notify();
622 }
623 Err(err) => {
624 this.handle_load_error(err, window, cx);
625 }
626 };
627 })
628 .log_err();
629 });
630
631 cx.spawn(async move |this, cx| {
632 while let Ok(new_version) = new_version_available_rx.recv().await {
633 if let Some(new_version) = new_version {
634 this.update(cx, |this, cx| {
635 this.new_server_version_available = Some(new_version.into());
636 cx.notify();
637 })
638 .log_err();
639 }
640 }
641 })
642 .detach();
643
644 let loading_view = cx.new(|cx| {
645 let update_title_task = cx.spawn(async move |this, cx| {
646 loop {
647 let status = status_rx.recv().await?;
648 this.update(cx, |this: &mut LoadingView, cx| {
649 this.title = status;
650 cx.notify();
651 })?;
652 }
653 });
654
655 LoadingView {
656 title: "Loading…".into(),
657 _load_task: load_task,
658 _update_title_task: update_title_task,
659 }
660 });
661
662 ThreadState::Loading(loading_view)
663 }
664
665 fn handle_auth_required(
666 this: WeakEntity<Self>,
667 err: AuthRequired,
668 agent: Rc<dyn AgentServer>,
669 connection: Rc<dyn AgentConnection>,
670 window: &mut Window,
671 cx: &mut App,
672 ) {
673 let agent_name = agent.name();
674 let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
675 let registry = LanguageModelRegistry::global(cx);
676
677 let sub = window.subscribe(®istry, cx, {
678 let provider_id = provider_id.clone();
679 let this = this.clone();
680 move |_, ev, window, cx| {
681 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
682 && &provider_id == updated_provider_id
683 && LanguageModelRegistry::global(cx)
684 .read(cx)
685 .provider(&provider_id)
686 .map_or(false, |provider| provider.is_authenticated(cx))
687 {
688 this.update(cx, |this, cx| {
689 this.reset(window, cx);
690 })
691 .ok();
692 }
693 }
694 });
695
696 let view = registry.read(cx).provider(&provider_id).map(|provider| {
697 provider.configuration_view(
698 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
699 window,
700 cx,
701 )
702 });
703
704 (view, Some(sub))
705 } else {
706 (None, None)
707 };
708
709 this.update(cx, |this, cx| {
710 this.thread_state = ThreadState::Unauthenticated {
711 pending_auth_method: None,
712 connection,
713 configuration_view,
714 description: err
715 .description
716 .clone()
717 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
718 _subscription: subscription,
719 };
720 if this.message_editor.focus_handle(cx).is_focused(window) {
721 this.focus_handle.focus(window)
722 }
723 cx.notify();
724 })
725 .ok();
726 }
727
728 fn handle_load_error(
729 &mut self,
730 err: anyhow::Error,
731 window: &mut Window,
732 cx: &mut Context<Self>,
733 ) {
734 if let Some(load_err) = err.downcast_ref::<LoadError>() {
735 self.thread_state = ThreadState::LoadError(load_err.clone());
736 } else {
737 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
738 }
739 if self.message_editor.focus_handle(cx).is_focused(window) {
740 self.focus_handle.focus(window)
741 }
742 cx.notify();
743 }
744
745 pub fn workspace(&self) -> &WeakEntity<Workspace> {
746 &self.workspace
747 }
748
749 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
750 match &self.thread_state {
751 ThreadState::Ready { thread, .. } => Some(thread),
752 ThreadState::Unauthenticated { .. }
753 | ThreadState::Loading { .. }
754 | ThreadState::LoadError { .. } => None,
755 }
756 }
757
758 pub fn title(&self, cx: &App) -> SharedString {
759 match &self.thread_state {
760 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
761 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
762 ThreadState::LoadError(error) => match error {
763 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
764 LoadError::FailedToInstall(_) => {
765 format!("Failed to Install {}", self.agent.name()).into()
766 }
767 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
768 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
769 },
770 }
771 }
772
773 pub fn title_editor(&self) -> Option<Entity<Editor>> {
774 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
775 title_editor.clone()
776 } else {
777 None
778 }
779 }
780
781 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
782 self.thread_error.take();
783 self.thread_retry_status.take();
784
785 if let Some(thread) = self.thread() {
786 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
787 }
788 }
789
790 pub fn expand_message_editor(
791 &mut self,
792 _: &ExpandMessageEditor,
793 _window: &mut Window,
794 cx: &mut Context<Self>,
795 ) {
796 self.set_editor_is_expanded(!self.editor_expanded, cx);
797 cx.notify();
798 }
799
800 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
801 self.editor_expanded = is_expanded;
802 self.message_editor.update(cx, |editor, cx| {
803 if is_expanded {
804 editor.set_mode(
805 EditorMode::Full {
806 scale_ui_elements_with_buffer_font_size: false,
807 show_active_line_background: false,
808 sized_by_content: false,
809 },
810 cx,
811 )
812 } else {
813 editor.set_mode(
814 EditorMode::AutoHeight {
815 min_lines: MIN_EDITOR_LINES,
816 max_lines: Some(MAX_EDITOR_LINES),
817 },
818 cx,
819 )
820 }
821 });
822 cx.notify();
823 }
824
825 pub fn handle_title_editor_event(
826 &mut self,
827 title_editor: &Entity<Editor>,
828 event: &EditorEvent,
829 window: &mut Window,
830 cx: &mut Context<Self>,
831 ) {
832 let Some(thread) = self.thread() else { return };
833
834 match event {
835 EditorEvent::BufferEdited => {
836 let new_title = title_editor.read(cx).text(cx);
837 thread.update(cx, |thread, cx| {
838 thread
839 .set_title(new_title.into(), cx)
840 .detach_and_log_err(cx);
841 })
842 }
843 EditorEvent::Blurred => {
844 if title_editor.read(cx).text(cx).is_empty() {
845 title_editor.update(cx, |editor, cx| {
846 editor.set_text("New Thread", window, cx);
847 });
848 }
849 }
850 _ => {}
851 }
852 }
853
854 pub fn handle_message_editor_event(
855 &mut self,
856 _: &Entity<MessageEditor>,
857 event: &MessageEditorEvent,
858 window: &mut Window,
859 cx: &mut Context<Self>,
860 ) {
861 match event {
862 MessageEditorEvent::Send => self.send(window, cx),
863 MessageEditorEvent::Cancel => self.cancel_generation(cx),
864 MessageEditorEvent::Focus => {
865 self.cancel_editing(&Default::default(), window, cx);
866 }
867 MessageEditorEvent::LostFocus => {}
868 }
869 }
870
871 pub fn handle_entry_view_event(
872 &mut self,
873 _: &Entity<EntryViewState>,
874 event: &EntryViewEvent,
875 window: &mut Window,
876 cx: &mut Context<Self>,
877 ) {
878 match &event.view_event {
879 ViewEvent::NewDiff(tool_call_id) => {
880 if AgentSettings::get_global(cx).expand_edit_card {
881 self.expanded_tool_calls.insert(tool_call_id.clone());
882 }
883 }
884 ViewEvent::NewTerminal(tool_call_id) => {
885 if AgentSettings::get_global(cx).expand_terminal_card {
886 self.expanded_tool_calls.insert(tool_call_id.clone());
887 }
888 }
889 ViewEvent::TerminalMovedToBackground(tool_call_id) => {
890 self.expanded_tool_calls.remove(tool_call_id);
891 }
892 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
893 if let Some(thread) = self.thread()
894 && let Some(AgentThreadEntry::UserMessage(user_message)) =
895 thread.read(cx).entries().get(event.entry_index)
896 && user_message.id.is_some()
897 {
898 self.editing_message = Some(event.entry_index);
899 cx.notify();
900 }
901 }
902 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
903 if let Some(thread) = self.thread()
904 && let Some(AgentThreadEntry::UserMessage(user_message)) =
905 thread.read(cx).entries().get(event.entry_index)
906 && user_message.id.is_some()
907 {
908 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
909 self.editing_message = None;
910 cx.notify();
911 }
912 }
913 }
914 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
915 self.regenerate(event.entry_index, editor, window, cx);
916 }
917 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
918 self.cancel_editing(&Default::default(), window, cx);
919 }
920 }
921 }
922
923 fn resume_chat(&mut self, cx: &mut Context<Self>) {
924 self.thread_error.take();
925 let Some(thread) = self.thread() else {
926 return;
927 };
928 if !thread.read(cx).can_resume(cx) {
929 return;
930 }
931
932 let task = thread.update(cx, |thread, cx| thread.resume(cx));
933 cx.spawn(async move |this, cx| {
934 let result = task.await;
935
936 this.update(cx, |this, cx| {
937 if let Err(err) = result {
938 this.handle_thread_error(err, cx);
939 }
940 })
941 })
942 .detach();
943 }
944
945 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
946 let Some(thread) = self.thread() else { return };
947
948 if self.is_loading_contents {
949 return;
950 }
951
952 self.history_store.update(cx, |history, cx| {
953 history.push_recently_opened_entry(
954 HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
955 cx,
956 );
957 });
958
959 if thread.read(cx).status() != ThreadStatus::Idle {
960 self.stop_current_and_send_new_message(window, cx);
961 return;
962 }
963
964 let text = self.message_editor.read(cx).text(cx);
965 let text = text.trim();
966 if text == "/login" || text == "/logout" {
967 let ThreadState::Ready { thread, .. } = &self.thread_state else {
968 return;
969 };
970
971 let connection = thread.read(cx).connection().clone();
972 if !connection
973 .auth_methods()
974 .iter()
975 .any(|method| method.id.0.as_ref() == "claude-login")
976 {
977 return;
978 };
979 let this = cx.weak_entity();
980 let agent = self.agent.clone();
981 window.defer(cx, |window, cx| {
982 Self::handle_auth_required(
983 this,
984 AuthRequired {
985 description: None,
986 provider_id: None,
987 },
988 agent,
989 connection,
990 window,
991 cx,
992 );
993 });
994 cx.notify();
995 return;
996 }
997
998 let contents = self
999 .message_editor
1000 .update(cx, |message_editor, cx| message_editor.contents(cx));
1001 self.send_impl(contents, window, cx)
1002 }
1003
1004 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1005 let Some(thread) = self.thread().cloned() else {
1006 return;
1007 };
1008
1009 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1010
1011 let contents = self
1012 .message_editor
1013 .update(cx, |message_editor, cx| message_editor.contents(cx));
1014
1015 cx.spawn_in(window, async move |this, cx| {
1016 cancelled.await;
1017
1018 this.update_in(cx, |this, window, cx| {
1019 this.send_impl(contents, window, cx);
1020 })
1021 .ok();
1022 })
1023 .detach();
1024 }
1025
1026 fn send_impl(
1027 &mut self,
1028 contents: Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>,
1029 window: &mut Window,
1030 cx: &mut Context<Self>,
1031 ) {
1032 let agent_telemetry_id = self.agent.telemetry_id();
1033
1034 self.thread_error.take();
1035 self.editing_message.take();
1036 self.thread_feedback.clear();
1037
1038 let Some(thread) = self.thread() else {
1039 return;
1040 };
1041 let thread = thread.downgrade();
1042 if self.should_be_following {
1043 self.workspace
1044 .update(cx, |workspace, cx| {
1045 workspace.follow(CollaboratorId::Agent, window, cx);
1046 })
1047 .ok();
1048 }
1049
1050 self.is_loading_contents = true;
1051 let guard = cx.new(|_| ());
1052 cx.observe_release(&guard, |this, _guard, cx| {
1053 this.is_loading_contents = false;
1054 cx.notify();
1055 })
1056 .detach();
1057
1058 let task = cx.spawn_in(window, async move |this, cx| {
1059 let (contents, tracked_buffers) = contents.await?;
1060
1061 if contents.is_empty() {
1062 return Ok(());
1063 }
1064
1065 this.update_in(cx, |this, window, cx| {
1066 this.set_editor_is_expanded(false, cx);
1067 this.scroll_to_bottom(cx);
1068 this.message_editor.update(cx, |message_editor, cx| {
1069 message_editor.clear(window, cx);
1070 });
1071 })?;
1072 let send = thread.update(cx, |thread, cx| {
1073 thread.action_log().update(cx, |action_log, cx| {
1074 for buffer in tracked_buffers {
1075 action_log.buffer_read(buffer, cx)
1076 }
1077 });
1078 drop(guard);
1079
1080 telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
1081
1082 thread.send(contents, cx)
1083 })?;
1084 send.await
1085 });
1086
1087 cx.spawn(async move |this, cx| {
1088 if let Err(err) = task.await {
1089 this.update(cx, |this, cx| {
1090 this.handle_thread_error(err, cx);
1091 })
1092 .ok();
1093 } else {
1094 this.update(cx, |this, cx| {
1095 this.should_be_following = this
1096 .workspace
1097 .update(cx, |workspace, _| {
1098 workspace.is_being_followed(CollaboratorId::Agent)
1099 })
1100 .unwrap_or_default();
1101 })
1102 .ok();
1103 }
1104 })
1105 .detach();
1106 }
1107
1108 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1109 let Some(thread) = self.thread().cloned() else {
1110 return;
1111 };
1112
1113 if let Some(index) = self.editing_message.take()
1114 && let Some(editor) = self
1115 .entry_view_state
1116 .read(cx)
1117 .entry(index)
1118 .and_then(|e| e.message_editor())
1119 .cloned()
1120 {
1121 editor.update(cx, |editor, cx| {
1122 if let Some(user_message) = thread
1123 .read(cx)
1124 .entries()
1125 .get(index)
1126 .and_then(|e| e.user_message())
1127 {
1128 editor.set_message(user_message.chunks.clone(), window, cx);
1129 }
1130 })
1131 };
1132 self.focus_handle(cx).focus(window);
1133 cx.notify();
1134 }
1135
1136 fn regenerate(
1137 &mut self,
1138 entry_ix: usize,
1139 message_editor: &Entity<MessageEditor>,
1140 window: &mut Window,
1141 cx: &mut Context<Self>,
1142 ) {
1143 let Some(thread) = self.thread().cloned() else {
1144 return;
1145 };
1146 if self.is_loading_contents {
1147 return;
1148 }
1149
1150 let Some(user_message_id) = thread.update(cx, |thread, _| {
1151 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1152 }) else {
1153 return;
1154 };
1155
1156 let contents = message_editor.update(cx, |message_editor, cx| message_editor.contents(cx));
1157
1158 let task = cx.spawn(async move |_, cx| {
1159 let contents = contents.await?;
1160 thread
1161 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1162 .await?;
1163 Ok(contents)
1164 });
1165 self.send_impl(task, window, cx);
1166 }
1167
1168 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
1169 if let Some(thread) = self.thread() {
1170 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
1171 }
1172 }
1173
1174 fn open_edited_buffer(
1175 &mut self,
1176 buffer: &Entity<Buffer>,
1177 window: &mut Window,
1178 cx: &mut Context<Self>,
1179 ) {
1180 let Some(thread) = self.thread() else {
1181 return;
1182 };
1183
1184 let Some(diff) =
1185 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1186 else {
1187 return;
1188 };
1189
1190 diff.update(cx, |diff, cx| {
1191 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1192 })
1193 }
1194
1195 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1196 let Some(thread) = self.as_native_thread(cx) else {
1197 return;
1198 };
1199 let project_context = thread.read(cx).project_context().read(cx);
1200
1201 let project_entry_ids = project_context
1202 .worktrees
1203 .iter()
1204 .flat_map(|worktree| worktree.rules_file.as_ref())
1205 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1206 .collect::<Vec<_>>();
1207
1208 self.workspace
1209 .update(cx, move |workspace, cx| {
1210 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1211 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1212 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1213 let project = workspace.project().read(cx);
1214 let project_paths = project_entry_ids
1215 .into_iter()
1216 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1217 .collect::<Vec<_>>();
1218 for project_path in project_paths {
1219 workspace
1220 .open_path(project_path, None, true, window, cx)
1221 .detach_and_log_err(cx);
1222 }
1223 })
1224 .ok();
1225 }
1226
1227 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1228 self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1229 cx.notify();
1230 }
1231
1232 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1233 self.thread_error = None;
1234 cx.notify();
1235 }
1236
1237 fn handle_thread_event(
1238 &mut self,
1239 thread: &Entity<AcpThread>,
1240 event: &AcpThreadEvent,
1241 window: &mut Window,
1242 cx: &mut Context<Self>,
1243 ) {
1244 match event {
1245 AcpThreadEvent::NewEntry => {
1246 let len = thread.read(cx).entries().len();
1247 let index = len - 1;
1248 self.entry_view_state.update(cx, |view_state, cx| {
1249 view_state.sync_entry(index, thread, window, cx);
1250 self.list_state.splice_focusable(
1251 index..index,
1252 [view_state
1253 .entry(index)
1254 .and_then(|entry| entry.focus_handle(cx))],
1255 );
1256 });
1257 }
1258 AcpThreadEvent::EntryUpdated(index) => {
1259 self.entry_view_state.update(cx, |view_state, cx| {
1260 view_state.sync_entry(*index, thread, window, cx)
1261 });
1262 }
1263 AcpThreadEvent::EntriesRemoved(range) => {
1264 self.entry_view_state
1265 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1266 self.list_state.splice(range.clone(), 0);
1267 }
1268 AcpThreadEvent::ToolAuthorizationRequired => {
1269 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1270 }
1271 AcpThreadEvent::Retry(retry) => {
1272 self.thread_retry_status = Some(retry.clone());
1273 }
1274 AcpThreadEvent::Stopped => {
1275 self.thread_retry_status.take();
1276 let used_tools = thread.read(cx).used_tools_since_last_user_message();
1277 self.notify_with_sound(
1278 if used_tools {
1279 "Finished running tools"
1280 } else {
1281 "New message"
1282 },
1283 IconName::ZedAssistant,
1284 window,
1285 cx,
1286 );
1287 }
1288 AcpThreadEvent::Refusal => {
1289 self.thread_retry_status.take();
1290 self.thread_error = Some(ThreadError::Refusal);
1291 let model_or_agent_name = self.get_current_model_name(cx);
1292 let notification_message =
1293 format!("{} refused to respond to this request", model_or_agent_name);
1294 self.notify_with_sound(¬ification_message, IconName::Warning, window, cx);
1295 }
1296 AcpThreadEvent::Error => {
1297 self.thread_retry_status.take();
1298 self.notify_with_sound(
1299 "Agent stopped due to an error",
1300 IconName::Warning,
1301 window,
1302 cx,
1303 );
1304 }
1305 AcpThreadEvent::LoadError(error) => {
1306 self.thread_retry_status.take();
1307 self.thread_state = ThreadState::LoadError(error.clone());
1308 if self.message_editor.focus_handle(cx).is_focused(window) {
1309 self.focus_handle.focus(window)
1310 }
1311 }
1312 AcpThreadEvent::TitleUpdated => {
1313 let title = thread.read(cx).title();
1314 if let Some(title_editor) = self.title_editor() {
1315 title_editor.update(cx, |editor, cx| {
1316 if editor.text(cx) != title {
1317 editor.set_text(title, window, cx);
1318 }
1319 });
1320 }
1321 }
1322 AcpThreadEvent::PromptCapabilitiesUpdated => {
1323 self.prompt_capabilities
1324 .set(thread.read(cx).prompt_capabilities());
1325 }
1326 AcpThreadEvent::TokenUsageUpdated => {}
1327 AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1328 let mut available_commands = available_commands.clone();
1329
1330 if thread
1331 .read(cx)
1332 .connection()
1333 .auth_methods()
1334 .iter()
1335 .any(|method| method.id.0.as_ref() == "claude-login")
1336 {
1337 available_commands.push(acp::AvailableCommand {
1338 name: "login".to_owned(),
1339 description: "Authenticate".to_owned(),
1340 input: None,
1341 });
1342 available_commands.push(acp::AvailableCommand {
1343 name: "logout".to_owned(),
1344 description: "Authenticate".to_owned(),
1345 input: None,
1346 });
1347 }
1348
1349 self.available_commands.replace(available_commands);
1350 }
1351 }
1352 cx.notify();
1353 }
1354
1355 fn authenticate(
1356 &mut self,
1357 method: acp::AuthMethodId,
1358 window: &mut Window,
1359 cx: &mut Context<Self>,
1360 ) {
1361 let ThreadState::Unauthenticated {
1362 connection,
1363 pending_auth_method,
1364 configuration_view,
1365 ..
1366 } = &mut self.thread_state
1367 else {
1368 return;
1369 };
1370
1371 if method.0.as_ref() == "gemini-api-key" {
1372 let registry = LanguageModelRegistry::global(cx);
1373 let provider = registry
1374 .read(cx)
1375 .provider(&language_model::GOOGLE_PROVIDER_ID)
1376 .unwrap();
1377 if !provider.is_authenticated(cx) {
1378 let this = cx.weak_entity();
1379 let agent = self.agent.clone();
1380 let connection = connection.clone();
1381 window.defer(cx, |window, cx| {
1382 Self::handle_auth_required(
1383 this,
1384 AuthRequired {
1385 description: Some("GEMINI_API_KEY must be set".to_owned()),
1386 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1387 },
1388 agent,
1389 connection,
1390 window,
1391 cx,
1392 );
1393 });
1394 return;
1395 }
1396 } else if method.0.as_ref() == "anthropic-api-key" {
1397 let registry = LanguageModelRegistry::global(cx);
1398 let provider = registry
1399 .read(cx)
1400 .provider(&language_model::ANTHROPIC_PROVIDER_ID)
1401 .unwrap();
1402 let this = cx.weak_entity();
1403 let agent = self.agent.clone();
1404 let connection = connection.clone();
1405 window.defer(cx, move |window, cx| {
1406 if !provider.is_authenticated(cx) {
1407 Self::handle_auth_required(
1408 this,
1409 AuthRequired {
1410 description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
1411 provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1412 },
1413 agent,
1414 connection,
1415 window,
1416 cx,
1417 );
1418 } else {
1419 this.update(cx, |this, cx| {
1420 this.thread_state = Self::initial_state(
1421 agent,
1422 None,
1423 this.workspace.clone(),
1424 this.project.clone(),
1425 window,
1426 cx,
1427 )
1428 })
1429 .ok();
1430 }
1431 });
1432 return;
1433 } else if method.0.as_ref() == "vertex-ai"
1434 && std::env::var("GOOGLE_API_KEY").is_err()
1435 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1436 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1437 {
1438 let this = cx.weak_entity();
1439 let agent = self.agent.clone();
1440 let connection = connection.clone();
1441
1442 window.defer(cx, |window, cx| {
1443 Self::handle_auth_required(
1444 this,
1445 AuthRequired {
1446 description: Some(
1447 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1448 .to_owned(),
1449 ),
1450 provider_id: None,
1451 },
1452 agent,
1453 connection,
1454 window,
1455 cx,
1456 )
1457 });
1458 return;
1459 }
1460
1461 self.thread_error.take();
1462 configuration_view.take();
1463 pending_auth_method.replace(method.clone());
1464 let authenticate = if method.0.as_ref() == "claude-login" {
1465 if let Some(workspace) = self.workspace.upgrade() {
1466 Self::spawn_claude_login(&workspace, window, cx)
1467 } else {
1468 Task::ready(Ok(()))
1469 }
1470 } else {
1471 connection.authenticate(method, cx)
1472 };
1473 cx.notify();
1474 self.auth_task =
1475 Some(cx.spawn_in(window, {
1476 let agent = self.agent.clone();
1477 async move |this, cx| {
1478 let result = authenticate.await;
1479
1480 match &result {
1481 Ok(_) => telemetry::event!(
1482 "Authenticate Agent Succeeded",
1483 agent = agent.telemetry_id()
1484 ),
1485 Err(_) => {
1486 telemetry::event!(
1487 "Authenticate Agent Failed",
1488 agent = agent.telemetry_id(),
1489 )
1490 }
1491 }
1492
1493 this.update_in(cx, |this, window, cx| {
1494 if let Err(err) = result {
1495 if let ThreadState::Unauthenticated {
1496 pending_auth_method,
1497 ..
1498 } = &mut this.thread_state
1499 {
1500 pending_auth_method.take();
1501 }
1502 this.handle_thread_error(err, cx);
1503 } else {
1504 this.reset(window, cx);
1505 }
1506 this.auth_task.take()
1507 })
1508 .ok();
1509 }
1510 }));
1511 }
1512
1513 fn spawn_claude_login(
1514 workspace: &Entity<Workspace>,
1515 window: &mut Window,
1516 cx: &mut App,
1517 ) -> Task<Result<()>> {
1518 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1519 return Task::ready(Ok(()));
1520 };
1521 let project_entity = workspace.read(cx).project();
1522 let project = project_entity.read(cx);
1523 let cwd = project.first_project_directory(cx);
1524 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1525
1526 let delegate = AgentServerDelegate::new(project_entity.clone(), None, None);
1527 let command = ClaudeCode::login_command(delegate, cx);
1528
1529 window.spawn(cx, async move |cx| {
1530 let login_command = command.await?;
1531 let command = login_command
1532 .path
1533 .to_str()
1534 .with_context(|| format!("invalid login command: {:?}", login_command.path))?;
1535 let command = shlex::try_quote(command)?;
1536 let args = login_command
1537 .arguments
1538 .iter()
1539 .map(|arg| {
1540 Ok(shlex::try_quote(arg)
1541 .context("Failed to quote argument")?
1542 .to_string())
1543 })
1544 .collect::<Result<Vec<_>>>()?;
1545
1546 let terminal = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1547 terminal_panel.spawn_task(
1548 &SpawnInTerminal {
1549 id: task::TaskId("claude-login".into()),
1550 full_label: "claude /login".to_owned(),
1551 label: "claude /login".to_owned(),
1552 command: Some(command.into()),
1553 args,
1554 command_label: "claude /login".to_owned(),
1555 cwd,
1556 use_new_terminal: true,
1557 allow_concurrent_runs: true,
1558 hide: task::HideStrategy::Always,
1559 shell,
1560 ..Default::default()
1561 },
1562 window,
1563 cx,
1564 )
1565 })?;
1566
1567 let terminal = terminal.await?;
1568 let mut exit_status = terminal
1569 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1570 .fuse();
1571
1572 let logged_in = cx
1573 .spawn({
1574 let terminal = terminal.clone();
1575 async move |cx| {
1576 loop {
1577 cx.background_executor().timer(Duration::from_secs(1)).await;
1578 let content =
1579 terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1580 if content.contains("Login successful") {
1581 return anyhow::Ok(());
1582 }
1583 }
1584 }
1585 })
1586 .fuse();
1587 futures::pin_mut!(logged_in);
1588 futures::select_biased! {
1589 result = logged_in => {
1590 if let Err(e) = result {
1591 log::error!("{e}");
1592 return Err(anyhow!("exited before logging in"));
1593 }
1594 }
1595 _ = exit_status => {
1596 return Err(anyhow!("exited before logging in"));
1597 }
1598 }
1599 terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1600 Ok(())
1601 })
1602 }
1603
1604 fn authorize_tool_call(
1605 &mut self,
1606 tool_call_id: acp::ToolCallId,
1607 option_id: acp::PermissionOptionId,
1608 option_kind: acp::PermissionOptionKind,
1609 window: &mut Window,
1610 cx: &mut Context<Self>,
1611 ) {
1612 let Some(thread) = self.thread() else {
1613 return;
1614 };
1615 thread.update(cx, |thread, cx| {
1616 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1617 });
1618 if self.should_be_following {
1619 self.workspace
1620 .update(cx, |workspace, cx| {
1621 workspace.follow(CollaboratorId::Agent, window, cx);
1622 })
1623 .ok();
1624 }
1625 cx.notify();
1626 }
1627
1628 fn rewind(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1629 let Some(thread) = self.thread() else {
1630 return;
1631 };
1632 thread
1633 .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
1634 .detach_and_log_err(cx);
1635 cx.notify();
1636 }
1637
1638 fn render_entry(
1639 &self,
1640 entry_ix: usize,
1641 total_entries: usize,
1642 entry: &AgentThreadEntry,
1643 window: &mut Window,
1644 cx: &Context<Self>,
1645 ) -> AnyElement {
1646 let primary = match &entry {
1647 AgentThreadEntry::UserMessage(message) => {
1648 let Some(editor) = self
1649 .entry_view_state
1650 .read(cx)
1651 .entry(entry_ix)
1652 .and_then(|entry| entry.message_editor())
1653 .cloned()
1654 else {
1655 return Empty.into_any_element();
1656 };
1657
1658 let editing = self.editing_message == Some(entry_ix);
1659 let editor_focus = editor.focus_handle(cx).is_focused(window);
1660 let focus_border = cx.theme().colors().border_focused;
1661
1662 let rules_item = if entry_ix == 0 {
1663 self.render_rules_item(cx)
1664 } else {
1665 None
1666 };
1667
1668 let has_checkpoint_button = message
1669 .checkpoint
1670 .as_ref()
1671 .is_some_and(|checkpoint| checkpoint.show);
1672
1673 let agent_name = self.agent.name();
1674
1675 v_flex()
1676 .id(("user_message", entry_ix))
1677 .map(|this| {
1678 if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none() {
1679 this.pt(rems_from_px(18.))
1680 } else if rules_item.is_some() {
1681 this.pt_3()
1682 } else {
1683 this.pt_2()
1684 }
1685 })
1686 .pb_3()
1687 .px_2()
1688 .gap_1p5()
1689 .w_full()
1690 .children(rules_item)
1691 .children(message.id.clone().and_then(|message_id| {
1692 message.checkpoint.as_ref()?.show.then(|| {
1693 h_flex()
1694 .px_3()
1695 .gap_2()
1696 .child(Divider::horizontal())
1697 .child(
1698 Button::new("restore-checkpoint", "Restore Checkpoint")
1699 .icon(IconName::Undo)
1700 .icon_size(IconSize::XSmall)
1701 .icon_position(IconPosition::Start)
1702 .label_size(LabelSize::XSmall)
1703 .icon_color(Color::Muted)
1704 .color(Color::Muted)
1705 .on_click(cx.listener(move |this, _, _window, cx| {
1706 this.rewind(&message_id, cx);
1707 }))
1708 )
1709 .child(Divider::horizontal())
1710 })
1711 }))
1712 .child(
1713 div()
1714 .relative()
1715 .child(
1716 div()
1717 .py_3()
1718 .px_2()
1719 .rounded_md()
1720 .shadow_md()
1721 .bg(cx.theme().colors().editor_background)
1722 .border_1()
1723 .when(editing && !editor_focus, |this| this.border_dashed())
1724 .border_color(cx.theme().colors().border)
1725 .map(|this|{
1726 if editing && editor_focus {
1727 this.border_color(focus_border)
1728 } else if message.id.is_some() {
1729 this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1730 } else {
1731 this
1732 }
1733 })
1734 .text_xs()
1735 .child(editor.clone().into_any_element()),
1736 )
1737 .when(editor_focus, |this| {
1738 let base_container = h_flex()
1739 .absolute()
1740 .top_neg_3p5()
1741 .right_3()
1742 .gap_1()
1743 .rounded_sm()
1744 .border_1()
1745 .border_color(cx.theme().colors().border)
1746 .bg(cx.theme().colors().editor_background)
1747 .overflow_hidden();
1748
1749 if message.id.is_some() {
1750 this.child(
1751 base_container
1752 .child(
1753 IconButton::new("cancel", IconName::Close)
1754 .disabled(self.is_loading_contents)
1755 .icon_color(Color::Error)
1756 .icon_size(IconSize::XSmall)
1757 .on_click(cx.listener(Self::cancel_editing))
1758 )
1759 .child(
1760 if self.is_loading_contents {
1761 div()
1762 .id("loading-edited-message-content")
1763 .tooltip(Tooltip::text("Loading Added Context…"))
1764 .child(loading_contents_spinner(IconSize::XSmall))
1765 .into_any_element()
1766 } else {
1767 IconButton::new("regenerate", IconName::Return)
1768 .icon_color(Color::Muted)
1769 .icon_size(IconSize::XSmall)
1770 .tooltip(Tooltip::text(
1771 "Editing will restart the thread from this point."
1772 ))
1773 .on_click(cx.listener({
1774 let editor = editor.clone();
1775 move |this, _, window, cx| {
1776 this.regenerate(
1777 entry_ix, &editor, window, cx,
1778 );
1779 }
1780 })).into_any_element()
1781 }
1782 )
1783 )
1784 } else {
1785 this.child(
1786 base_container
1787 .border_dashed()
1788 .child(
1789 IconButton::new("editing_unavailable", IconName::PencilUnavailable)
1790 .icon_size(IconSize::Small)
1791 .icon_color(Color::Muted)
1792 .style(ButtonStyle::Transparent)
1793 .tooltip(move |_window, cx| {
1794 cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
1795 .into()
1796 })
1797 )
1798 )
1799 }
1800 }),
1801 )
1802 .into_any()
1803 }
1804 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1805 let is_last = entry_ix + 1 == total_entries;
1806
1807 let style = default_markdown_style(false, false, window, cx);
1808 let message_body = v_flex()
1809 .w_full()
1810 .gap_3()
1811 .children(chunks.iter().enumerate().filter_map(
1812 |(chunk_ix, chunk)| match chunk {
1813 AssistantMessageChunk::Message { block } => {
1814 block.markdown().map(|md| {
1815 self.render_markdown(md.clone(), style.clone())
1816 .into_any_element()
1817 })
1818 }
1819 AssistantMessageChunk::Thought { block } => {
1820 block.markdown().map(|md| {
1821 self.render_thinking_block(
1822 entry_ix,
1823 chunk_ix,
1824 md.clone(),
1825 window,
1826 cx,
1827 )
1828 .into_any_element()
1829 })
1830 }
1831 },
1832 ))
1833 .into_any();
1834
1835 v_flex()
1836 .px_5()
1837 .py_1p5()
1838 .when(is_last, |this| this.pb_4())
1839 .w_full()
1840 .text_ui(cx)
1841 .child(message_body)
1842 .into_any()
1843 }
1844 AgentThreadEntry::ToolCall(tool_call) => {
1845 let has_terminals = tool_call.terminals().next().is_some();
1846
1847 div().w_full().map(|this| {
1848 if has_terminals {
1849 this.children(tool_call.terminals().map(|terminal| {
1850 self.render_terminal_tool_call(
1851 entry_ix, terminal, tool_call, window, cx,
1852 )
1853 }))
1854 } else {
1855 this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
1856 }
1857 })
1858 }
1859 .into_any(),
1860 };
1861
1862 let Some(thread) = self.thread() else {
1863 return primary;
1864 };
1865
1866 let primary = if entry_ix == total_entries - 1 {
1867 v_flex()
1868 .w_full()
1869 .child(primary)
1870 .child(self.render_thread_controls(&thread, cx))
1871 .when_some(
1872 self.thread_feedback.comments_editor.clone(),
1873 |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
1874 )
1875 .into_any_element()
1876 } else {
1877 primary
1878 };
1879
1880 if let Some(editing_index) = self.editing_message.as_ref()
1881 && *editing_index < entry_ix
1882 {
1883 let backdrop = div()
1884 .id(("backdrop", entry_ix))
1885 .size_full()
1886 .absolute()
1887 .inset_0()
1888 .bg(cx.theme().colors().panel_background)
1889 .opacity(0.8)
1890 .block_mouse_except_scroll()
1891 .on_click(cx.listener(Self::cancel_editing));
1892
1893 div()
1894 .relative()
1895 .child(primary)
1896 .child(backdrop)
1897 .into_any_element()
1898 } else {
1899 primary
1900 }
1901 }
1902
1903 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1904 cx.theme()
1905 .colors()
1906 .element_background
1907 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1908 }
1909
1910 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1911 cx.theme().colors().border.opacity(0.8)
1912 }
1913
1914 fn tool_name_font_size(&self) -> Rems {
1915 rems_from_px(13.)
1916 }
1917
1918 fn render_thinking_block(
1919 &self,
1920 entry_ix: usize,
1921 chunk_ix: usize,
1922 chunk: Entity<Markdown>,
1923 window: &Window,
1924 cx: &Context<Self>,
1925 ) -> AnyElement {
1926 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
1927 let card_header_id = SharedString::from("inner-card-header");
1928
1929 let key = (entry_ix, chunk_ix);
1930
1931 let is_open = self.expanded_thinking_blocks.contains(&key);
1932
1933 let scroll_handle = self
1934 .entry_view_state
1935 .read(cx)
1936 .entry(entry_ix)
1937 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
1938
1939 let thinking_content = {
1940 div()
1941 .id(("thinking-content", chunk_ix))
1942 .when_some(scroll_handle, |this, scroll_handle| {
1943 this.track_scroll(&scroll_handle)
1944 })
1945 .text_ui_sm(cx)
1946 .overflow_hidden()
1947 .child(
1948 self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
1949 )
1950 };
1951
1952 v_flex()
1953 .gap_1()
1954 .child(
1955 h_flex()
1956 .id(header_id)
1957 .group(&card_header_id)
1958 .relative()
1959 .w_full()
1960 .pr_1()
1961 .justify_between()
1962 .child(
1963 h_flex()
1964 .h(window.line_height() - px(2.))
1965 .gap_1p5()
1966 .overflow_hidden()
1967 .child(
1968 Icon::new(IconName::ToolThink)
1969 .size(IconSize::Small)
1970 .color(Color::Muted),
1971 )
1972 .child(
1973 div()
1974 .text_size(self.tool_name_font_size())
1975 .text_color(cx.theme().colors().text_muted)
1976 .child("Thinking"),
1977 ),
1978 )
1979 .child(
1980 Disclosure::new(("expand", entry_ix), is_open)
1981 .opened_icon(IconName::ChevronUp)
1982 .closed_icon(IconName::ChevronDown)
1983 .visible_on_hover(&card_header_id)
1984 .on_click(cx.listener({
1985 move |this, _event, _window, cx| {
1986 if is_open {
1987 this.expanded_thinking_blocks.remove(&key);
1988 } else {
1989 this.expanded_thinking_blocks.insert(key);
1990 }
1991 cx.notify();
1992 }
1993 })),
1994 )
1995 .on_click(cx.listener({
1996 move |this, _event, _window, cx| {
1997 if is_open {
1998 this.expanded_thinking_blocks.remove(&key);
1999 } else {
2000 this.expanded_thinking_blocks.insert(key);
2001 }
2002 cx.notify();
2003 }
2004 })),
2005 )
2006 .when(is_open, |this| {
2007 this.child(
2008 div()
2009 .ml_1p5()
2010 .pl_3p5()
2011 .border_l_1()
2012 .border_color(self.tool_card_border_color(cx))
2013 .child(thinking_content),
2014 )
2015 })
2016 .into_any_element()
2017 }
2018
2019 fn render_tool_call(
2020 &self,
2021 entry_ix: usize,
2022 tool_call: &ToolCall,
2023 window: &Window,
2024 cx: &Context<Self>,
2025 ) -> Div {
2026 let card_header_id = SharedString::from("inner-tool-call-header");
2027
2028 let tool_icon =
2029 if tool_call.kind == acp::ToolKind::Edit && tool_call.locations.len() == 1 {
2030 FileIcons::get_icon(&tool_call.locations[0].path, cx)
2031 .map(Icon::from_path)
2032 .unwrap_or(Icon::new(IconName::ToolPencil))
2033 } else {
2034 Icon::new(match tool_call.kind {
2035 acp::ToolKind::Read => IconName::ToolSearch,
2036 acp::ToolKind::Edit => IconName::ToolPencil,
2037 acp::ToolKind::Delete => IconName::ToolDeleteFile,
2038 acp::ToolKind::Move => IconName::ArrowRightLeft,
2039 acp::ToolKind::Search => IconName::ToolSearch,
2040 acp::ToolKind::Execute => IconName::ToolTerminal,
2041 acp::ToolKind::Think => IconName::ToolThink,
2042 acp::ToolKind::Fetch => IconName::ToolWeb,
2043 acp::ToolKind::Other => IconName::ToolHammer,
2044 })
2045 }
2046 .size(IconSize::Small)
2047 .color(Color::Muted);
2048
2049 let failed_or_canceled = match &tool_call.status {
2050 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
2051 _ => false,
2052 };
2053
2054 let has_location = tool_call.locations.len() == 1;
2055 let needs_confirmation = matches!(
2056 tool_call.status,
2057 ToolCallStatus::WaitingForConfirmation { .. }
2058 );
2059 let is_edit =
2060 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2061 let use_card_layout = needs_confirmation || is_edit;
2062
2063 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2064
2065 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2066
2067 let gradient_overlay = {
2068 div()
2069 .absolute()
2070 .top_0()
2071 .right_0()
2072 .w_12()
2073 .h_full()
2074 .map(|this| {
2075 if use_card_layout {
2076 this.bg(linear_gradient(
2077 90.,
2078 linear_color_stop(self.tool_card_header_bg(cx), 1.),
2079 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
2080 ))
2081 } else {
2082 this.bg(linear_gradient(
2083 90.,
2084 linear_color_stop(cx.theme().colors().panel_background, 1.),
2085 linear_color_stop(
2086 cx.theme().colors().panel_background.opacity(0.2),
2087 0.,
2088 ),
2089 ))
2090 }
2091 })
2092 };
2093
2094 let tool_output_display = if is_open {
2095 match &tool_call.status {
2096 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2097 .w_full()
2098 .children(tool_call.content.iter().map(|content| {
2099 div()
2100 .child(self.render_tool_call_content(
2101 entry_ix,
2102 content,
2103 tool_call,
2104 use_card_layout,
2105 window,
2106 cx,
2107 ))
2108 .into_any_element()
2109 }))
2110 .child(self.render_permission_buttons(
2111 options,
2112 entry_ix,
2113 tool_call.id.clone(),
2114 cx,
2115 ))
2116 .into_any(),
2117 ToolCallStatus::Pending | ToolCallStatus::InProgress
2118 if is_edit
2119 && tool_call.content.is_empty()
2120 && self.as_native_connection(cx).is_some() =>
2121 {
2122 self.render_diff_loading(cx).into_any()
2123 }
2124 ToolCallStatus::Pending
2125 | ToolCallStatus::InProgress
2126 | ToolCallStatus::Completed
2127 | ToolCallStatus::Failed
2128 | ToolCallStatus::Canceled => v_flex()
2129 .w_full()
2130 .children(tool_call.content.iter().map(|content| {
2131 div().child(self.render_tool_call_content(
2132 entry_ix,
2133 content,
2134 tool_call,
2135 use_card_layout,
2136 window,
2137 cx,
2138 ))
2139 }))
2140 .into_any(),
2141 ToolCallStatus::Rejected => Empty.into_any(),
2142 }
2143 .into()
2144 } else {
2145 None
2146 };
2147
2148 v_flex()
2149 .map(|this| {
2150 if use_card_layout {
2151 this.my_1p5()
2152 .rounded_md()
2153 .border_1()
2154 .border_color(self.tool_card_border_color(cx))
2155 .bg(cx.theme().colors().editor_background)
2156 .overflow_hidden()
2157 } else {
2158 this.my_1()
2159 }
2160 })
2161 .map(|this| {
2162 if has_location && !use_card_layout {
2163 this.ml_4()
2164 } else {
2165 this.ml_5()
2166 }
2167 })
2168 .mr_5()
2169 .child(
2170 h_flex()
2171 .group(&card_header_id)
2172 .relative()
2173 .w_full()
2174 .gap_1()
2175 .justify_between()
2176 .when(use_card_layout, |this| {
2177 this.p_0p5()
2178 .rounded_t(rems_from_px(5.))
2179 .bg(self.tool_card_header_bg(cx))
2180 })
2181 .child(
2182 h_flex()
2183 .relative()
2184 .w_full()
2185 .h(window.line_height() - px(2.))
2186 .text_size(self.tool_name_font_size())
2187 .gap_1p5()
2188 .when(has_location || use_card_layout, |this| this.px_1())
2189 .when(has_location, |this| {
2190 this.cursor(CursorStyle::PointingHand)
2191 .rounded(rems_from_px(3.)) // Concentric border radius
2192 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
2193 })
2194 .overflow_hidden()
2195 .child(tool_icon)
2196 .child(if has_location {
2197 let name = tool_call.locations[0]
2198 .path
2199 .file_name()
2200 .unwrap_or_default()
2201 .display()
2202 .to_string();
2203
2204 h_flex()
2205 .id(("open-tool-call-location", entry_ix))
2206 .w_full()
2207 .map(|this| {
2208 if use_card_layout {
2209 this.text_color(cx.theme().colors().text)
2210 } else {
2211 this.text_color(cx.theme().colors().text_muted)
2212 }
2213 })
2214 .child(name)
2215 .tooltip(Tooltip::text("Jump to File"))
2216 .on_click(cx.listener(move |this, _, window, cx| {
2217 this.open_tool_call_location(entry_ix, 0, window, cx);
2218 }))
2219 .into_any_element()
2220 } else {
2221 h_flex()
2222 .w_full()
2223 .child(self.render_markdown(
2224 tool_call.label.clone(),
2225 default_markdown_style(false, true, window, cx),
2226 ))
2227 .into_any()
2228 })
2229 .when(!has_location, |this| this.child(gradient_overlay)),
2230 )
2231 .when(is_collapsible || failed_or_canceled, |this| {
2232 this.child(
2233 h_flex()
2234 .px_1()
2235 .gap_px()
2236 .when(is_collapsible, |this| {
2237 this.child(
2238 Disclosure::new(("expand", entry_ix), is_open)
2239 .opened_icon(IconName::ChevronUp)
2240 .closed_icon(IconName::ChevronDown)
2241 .visible_on_hover(&card_header_id)
2242 .on_click(cx.listener({
2243 let id = tool_call.id.clone();
2244 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2245 if is_open {
2246 this.expanded_tool_calls.remove(&id);
2247 } else {
2248 this.expanded_tool_calls.insert(id.clone());
2249 }
2250 cx.notify();
2251 }
2252 })),
2253 )
2254 })
2255 .when(failed_or_canceled, |this| {
2256 this.child(
2257 Icon::new(IconName::Close)
2258 .color(Color::Error)
2259 .size(IconSize::Small),
2260 )
2261 }),
2262 )
2263 }),
2264 )
2265 .children(tool_output_display)
2266 }
2267
2268 fn render_tool_call_content(
2269 &self,
2270 entry_ix: usize,
2271 content: &ToolCallContent,
2272 tool_call: &ToolCall,
2273 card_layout: bool,
2274 window: &Window,
2275 cx: &Context<Self>,
2276 ) -> AnyElement {
2277 match content {
2278 ToolCallContent::ContentBlock(content) => {
2279 if let Some(resource_link) = content.resource_link() {
2280 self.render_resource_link(resource_link, cx)
2281 } else if let Some(markdown) = content.markdown() {
2282 self.render_markdown_output(
2283 markdown.clone(),
2284 tool_call.id.clone(),
2285 card_layout,
2286 window,
2287 cx,
2288 )
2289 } else {
2290 Empty.into_any_element()
2291 }
2292 }
2293 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2294 ToolCallContent::Terminal(terminal) => {
2295 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2296 }
2297 }
2298 }
2299
2300 fn render_markdown_output(
2301 &self,
2302 markdown: Entity<Markdown>,
2303 tool_call_id: acp::ToolCallId,
2304 card_layout: bool,
2305 window: &Window,
2306 cx: &Context<Self>,
2307 ) -> AnyElement {
2308 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2309
2310 v_flex()
2311 .mt_1p5()
2312 .gap_2()
2313 .when(!card_layout, |this| {
2314 this.ml(rems(0.4))
2315 .px_3p5()
2316 .border_l_1()
2317 .border_color(self.tool_card_border_color(cx))
2318 })
2319 .when(card_layout, |this| {
2320 this.p_2()
2321 .border_t_1()
2322 .border_color(self.tool_card_border_color(cx))
2323 })
2324 .text_sm()
2325 .text_color(cx.theme().colors().text_muted)
2326 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2327 .when(!card_layout, |this| {
2328 this.child(
2329 IconButton::new(button_id, IconName::ChevronUp)
2330 .full_width()
2331 .style(ButtonStyle::Outlined)
2332 .icon_color(Color::Muted)
2333 .on_click(cx.listener({
2334 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2335 this.expanded_tool_calls.remove(&tool_call_id);
2336 cx.notify();
2337 }
2338 })),
2339 )
2340 })
2341 .into_any_element()
2342 }
2343
2344 fn render_resource_link(
2345 &self,
2346 resource_link: &acp::ResourceLink,
2347 cx: &Context<Self>,
2348 ) -> AnyElement {
2349 let uri: SharedString = resource_link.uri.clone().into();
2350 let is_file = resource_link.uri.strip_prefix("file://");
2351
2352 let label: SharedString = if let Some(abs_path) = is_file {
2353 if let Some(project_path) = self
2354 .project
2355 .read(cx)
2356 .project_path_for_absolute_path(&Path::new(abs_path), cx)
2357 && let Some(worktree) = self
2358 .project
2359 .read(cx)
2360 .worktree_for_id(project_path.worktree_id, cx)
2361 {
2362 worktree
2363 .read(cx)
2364 .full_path(&project_path.path)
2365 .to_string_lossy()
2366 .to_string()
2367 .into()
2368 } else {
2369 abs_path.to_string().into()
2370 }
2371 } else {
2372 uri.clone()
2373 };
2374
2375 let button_id = SharedString::from(format!("item-{}", uri));
2376
2377 div()
2378 .ml(rems(0.4))
2379 .pl_2p5()
2380 .border_l_1()
2381 .border_color(self.tool_card_border_color(cx))
2382 .overflow_hidden()
2383 .child(
2384 Button::new(button_id, label)
2385 .label_size(LabelSize::Small)
2386 .color(Color::Muted)
2387 .truncate(true)
2388 .when(is_file.is_none(), |this| {
2389 this.icon(IconName::ArrowUpRight)
2390 .icon_size(IconSize::XSmall)
2391 .icon_color(Color::Muted)
2392 })
2393 .on_click(cx.listener({
2394 let workspace = self.workspace.clone();
2395 move |_, _, window, cx: &mut Context<Self>| {
2396 Self::open_link(uri.clone(), &workspace, window, cx);
2397 }
2398 })),
2399 )
2400 .into_any_element()
2401 }
2402
2403 fn render_permission_buttons(
2404 &self,
2405 options: &[acp::PermissionOption],
2406 entry_ix: usize,
2407 tool_call_id: acp::ToolCallId,
2408 cx: &Context<Self>,
2409 ) -> Div {
2410 h_flex()
2411 .py_1()
2412 .pl_2()
2413 .pr_1()
2414 .gap_1()
2415 .justify_between()
2416 .flex_wrap()
2417 .border_t_1()
2418 .border_color(self.tool_card_border_color(cx))
2419 .child(
2420 div()
2421 .min_w(rems_from_px(145.))
2422 .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
2423 )
2424 .child(h_flex().gap_0p5().children(options.iter().map(|option| {
2425 let option_id = SharedString::from(option.id.0.clone());
2426 Button::new((option_id, entry_ix), option.name.clone())
2427 .map(|this| match option.kind {
2428 acp::PermissionOptionKind::AllowOnce => {
2429 this.icon(IconName::Check).icon_color(Color::Success)
2430 }
2431 acp::PermissionOptionKind::AllowAlways => {
2432 this.icon(IconName::CheckDouble).icon_color(Color::Success)
2433 }
2434 acp::PermissionOptionKind::RejectOnce => {
2435 this.icon(IconName::Close).icon_color(Color::Error)
2436 }
2437 acp::PermissionOptionKind::RejectAlways => {
2438 this.icon(IconName::Close).icon_color(Color::Error)
2439 }
2440 })
2441 .icon_position(IconPosition::Start)
2442 .icon_size(IconSize::XSmall)
2443 .label_size(LabelSize::Small)
2444 .on_click(cx.listener({
2445 let tool_call_id = tool_call_id.clone();
2446 let option_id = option.id.clone();
2447 let option_kind = option.kind;
2448 move |this, _, window, cx| {
2449 this.authorize_tool_call(
2450 tool_call_id.clone(),
2451 option_id.clone(),
2452 option_kind,
2453 window,
2454 cx,
2455 );
2456 }
2457 }))
2458 })))
2459 }
2460
2461 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2462 let bar = |n: u64, width_class: &str| {
2463 let bg_color = cx.theme().colors().element_active;
2464 let base = h_flex().h_1().rounded_full();
2465
2466 let modified = match width_class {
2467 "w_4_5" => base.w_3_4(),
2468 "w_1_4" => base.w_1_4(),
2469 "w_2_4" => base.w_2_4(),
2470 "w_3_5" => base.w_3_5(),
2471 "w_2_5" => base.w_2_5(),
2472 _ => base.w_1_2(),
2473 };
2474
2475 modified.with_animation(
2476 ElementId::Integer(n),
2477 Animation::new(Duration::from_secs(2)).repeat(),
2478 move |tab, delta| {
2479 let delta = (delta - 0.15 * n as f32) / 0.7;
2480 let delta = 1.0 - (0.5 - delta).abs() * 2.;
2481 let delta = ease_in_out(delta.clamp(0., 1.));
2482 let delta = 0.1 + 0.9 * delta;
2483
2484 tab.bg(bg_color.opacity(delta))
2485 },
2486 )
2487 };
2488
2489 v_flex()
2490 .p_3()
2491 .gap_1()
2492 .rounded_b_md()
2493 .bg(cx.theme().colors().editor_background)
2494 .child(bar(0, "w_4_5"))
2495 .child(bar(1, "w_1_4"))
2496 .child(bar(2, "w_2_4"))
2497 .child(bar(3, "w_3_5"))
2498 .child(bar(4, "w_2_5"))
2499 .into_any_element()
2500 }
2501
2502 fn render_diff_editor(
2503 &self,
2504 entry_ix: usize,
2505 diff: &Entity<acp_thread::Diff>,
2506 tool_call: &ToolCall,
2507 cx: &Context<Self>,
2508 ) -> AnyElement {
2509 let tool_progress = matches!(
2510 &tool_call.status,
2511 ToolCallStatus::InProgress | ToolCallStatus::Pending
2512 );
2513
2514 v_flex()
2515 .h_full()
2516 .border_t_1()
2517 .border_color(self.tool_card_border_color(cx))
2518 .child(
2519 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2520 && let Some(editor) = entry.editor_for_diff(diff)
2521 && diff.read(cx).has_revealed_range(cx)
2522 {
2523 editor.into_any_element()
2524 } else if tool_progress && self.as_native_connection(cx).is_some() {
2525 self.render_diff_loading(cx)
2526 } else {
2527 Empty.into_any()
2528 },
2529 )
2530 .into_any()
2531 }
2532
2533 fn render_terminal_tool_call(
2534 &self,
2535 entry_ix: usize,
2536 terminal: &Entity<acp_thread::Terminal>,
2537 tool_call: &ToolCall,
2538 window: &Window,
2539 cx: &Context<Self>,
2540 ) -> AnyElement {
2541 let terminal_data = terminal.read(cx);
2542 let working_dir = terminal_data.working_dir();
2543 let command = terminal_data.command();
2544 let started_at = terminal_data.started_at();
2545
2546 let tool_failed = matches!(
2547 &tool_call.status,
2548 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2549 );
2550
2551 let output = terminal_data.output();
2552 let command_finished = output.is_some();
2553 let truncated_output =
2554 output.is_some_and(|output| output.original_content_len > output.content.len());
2555 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2556
2557 let command_failed = command_finished
2558 && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2559
2560 let time_elapsed = if let Some(output) = output {
2561 output.ended_at.duration_since(started_at)
2562 } else {
2563 started_at.elapsed()
2564 };
2565
2566 let header_id =
2567 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2568 let header_group = SharedString::from(format!(
2569 "terminal-tool-header-group-{}",
2570 terminal.entity_id()
2571 ));
2572 let header_bg = cx
2573 .theme()
2574 .colors()
2575 .element_background
2576 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2577 let border_color = cx.theme().colors().border.opacity(0.6);
2578
2579 let working_dir = working_dir
2580 .as_ref()
2581 .map(|path| format!("{}", path.display()))
2582 .unwrap_or_else(|| "current directory".to_string());
2583
2584 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2585
2586 let header = h_flex()
2587 .id(header_id)
2588 .flex_none()
2589 .gap_1()
2590 .justify_between()
2591 .rounded_t_md()
2592 .child(
2593 div()
2594 .id(("command-target-path", terminal.entity_id()))
2595 .w_full()
2596 .max_w_full()
2597 .overflow_x_scroll()
2598 .child(
2599 Label::new(working_dir)
2600 .buffer_font(cx)
2601 .size(LabelSize::XSmall)
2602 .color(Color::Muted),
2603 ),
2604 )
2605 .when(!command_finished, |header| {
2606 header
2607 .gap_1p5()
2608 .child(
2609 Button::new(
2610 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2611 "Stop",
2612 )
2613 .icon(IconName::Stop)
2614 .icon_position(IconPosition::Start)
2615 .icon_size(IconSize::Small)
2616 .icon_color(Color::Error)
2617 .label_size(LabelSize::Small)
2618 .tooltip(move |window, cx| {
2619 Tooltip::with_meta(
2620 "Stop This Command",
2621 None,
2622 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2623 window,
2624 cx,
2625 )
2626 })
2627 .on_click({
2628 let terminal = terminal.clone();
2629 cx.listener(move |_this, _event, _window, cx| {
2630 let inner_terminal = terminal.read(cx).inner().clone();
2631 inner_terminal.update(cx, |inner_terminal, _cx| {
2632 inner_terminal.kill_active_task();
2633 });
2634 })
2635 }),
2636 )
2637 .child(Divider::vertical())
2638 .child(
2639 Icon::new(IconName::ArrowCircle)
2640 .size(IconSize::XSmall)
2641 .color(Color::Info)
2642 .with_rotate_animation(2)
2643 )
2644 })
2645 .when(truncated_output, |header| {
2646 let tooltip = if let Some(output) = output {
2647 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2648 format!("Output exceeded terminal max lines and was \
2649 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
2650 } else {
2651 format!(
2652 "Output is {} long, and to avoid unexpected token usage, \
2653 only {} was sent back to the agent.",
2654 format_file_size(output.original_content_len as u64, true),
2655 format_file_size(output.content.len() as u64, true)
2656 )
2657 }
2658 } else {
2659 "Output was truncated".to_string()
2660 };
2661
2662 header.child(
2663 h_flex()
2664 .id(("terminal-tool-truncated-label", terminal.entity_id()))
2665 .gap_1()
2666 .child(
2667 Icon::new(IconName::Info)
2668 .size(IconSize::XSmall)
2669 .color(Color::Ignored),
2670 )
2671 .child(
2672 Label::new("Truncated")
2673 .color(Color::Muted)
2674 .size(LabelSize::XSmall),
2675 )
2676 .tooltip(Tooltip::text(tooltip)),
2677 )
2678 })
2679 .when(time_elapsed > Duration::from_secs(10), |header| {
2680 header.child(
2681 Label::new(format!("({})", duration_alt_display(time_elapsed)))
2682 .buffer_font(cx)
2683 .color(Color::Muted)
2684 .size(LabelSize::XSmall),
2685 )
2686 })
2687 .when(tool_failed || command_failed, |header| {
2688 header.child(
2689 div()
2690 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2691 .child(
2692 Icon::new(IconName::Close)
2693 .size(IconSize::Small)
2694 .color(Color::Error),
2695 )
2696 .when_some(output.and_then(|o| o.exit_status), |this, status| {
2697 this.tooltip(Tooltip::text(format!(
2698 "Exited with code {}",
2699 status.code().unwrap_or(-1),
2700 )))
2701 }),
2702 )
2703 })
2704 .child(
2705 Disclosure::new(
2706 SharedString::from(format!(
2707 "terminal-tool-disclosure-{}",
2708 terminal.entity_id()
2709 )),
2710 is_expanded,
2711 )
2712 .opened_icon(IconName::ChevronUp)
2713 .closed_icon(IconName::ChevronDown)
2714 .visible_on_hover(&header_group)
2715 .on_click(cx.listener({
2716 let id = tool_call.id.clone();
2717 move |this, _event, _window, _cx| {
2718 if is_expanded {
2719 this.expanded_tool_calls.remove(&id);
2720 } else {
2721 this.expanded_tool_calls.insert(id.clone());
2722 }
2723 }
2724 })),
2725 );
2726
2727 let terminal_view = self
2728 .entry_view_state
2729 .read(cx)
2730 .entry(entry_ix)
2731 .and_then(|entry| entry.terminal(terminal));
2732 let show_output = is_expanded && terminal_view.is_some();
2733
2734 v_flex()
2735 .my_1p5()
2736 .mx_5()
2737 .border_1()
2738 .when(tool_failed || command_failed, |card| card.border_dashed())
2739 .border_color(border_color)
2740 .rounded_md()
2741 .overflow_hidden()
2742 .child(
2743 v_flex()
2744 .group(&header_group)
2745 .py_1p5()
2746 .pr_1p5()
2747 .pl_2()
2748 .gap_0p5()
2749 .bg(header_bg)
2750 .text_xs()
2751 .child(header)
2752 .child(
2753 MarkdownElement::new(
2754 command.clone(),
2755 terminal_command_markdown_style(window, cx),
2756 )
2757 .code_block_renderer(
2758 markdown::CodeBlockRenderer::Default {
2759 copy_button: false,
2760 copy_button_on_hover: true,
2761 border: false,
2762 },
2763 ),
2764 ),
2765 )
2766 .when(show_output, |this| {
2767 this.child(
2768 div()
2769 .pt_2()
2770 .border_t_1()
2771 .when(tool_failed || command_failed, |card| card.border_dashed())
2772 .border_color(border_color)
2773 .bg(cx.theme().colors().editor_background)
2774 .rounded_b_md()
2775 .text_ui_sm(cx)
2776 .h_full()
2777 .children(terminal_view.map(|terminal_view| {
2778 if terminal_view
2779 .read(cx)
2780 .content_mode(window, cx)
2781 .is_scrollable()
2782 {
2783 div().h_72().child(terminal_view).into_any_element()
2784 } else {
2785 terminal_view.into_any_element()
2786 }
2787 })),
2788 )
2789 })
2790 .into_any()
2791 }
2792
2793 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2794 let project_context = self
2795 .as_native_thread(cx)?
2796 .read(cx)
2797 .project_context()
2798 .read(cx);
2799
2800 let user_rules_text = if project_context.user_rules.is_empty() {
2801 None
2802 } else if project_context.user_rules.len() == 1 {
2803 let user_rules = &project_context.user_rules[0];
2804
2805 match user_rules.title.as_ref() {
2806 Some(title) => Some(format!("Using \"{title}\" user rule")),
2807 None => Some("Using user rule".into()),
2808 }
2809 } else {
2810 Some(format!(
2811 "Using {} user rules",
2812 project_context.user_rules.len()
2813 ))
2814 };
2815
2816 let first_user_rules_id = project_context
2817 .user_rules
2818 .first()
2819 .map(|user_rules| user_rules.uuid.0);
2820
2821 let rules_files = project_context
2822 .worktrees
2823 .iter()
2824 .filter_map(|worktree| worktree.rules_file.as_ref())
2825 .collect::<Vec<_>>();
2826
2827 let rules_file_text = match rules_files.as_slice() {
2828 &[] => None,
2829 &[rules_file] => Some(format!(
2830 "Using project {:?} file",
2831 rules_file.path_in_worktree
2832 )),
2833 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2834 };
2835
2836 if user_rules_text.is_none() && rules_file_text.is_none() {
2837 return None;
2838 }
2839
2840 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
2841
2842 Some(
2843 h_flex()
2844 .px_2p5()
2845 .child(
2846 Icon::new(IconName::Attach)
2847 .size(IconSize::XSmall)
2848 .color(Color::Disabled),
2849 )
2850 .when_some(user_rules_text, |parent, user_rules_text| {
2851 parent.child(
2852 h_flex()
2853 .id("user-rules")
2854 .ml_1()
2855 .mr_1p5()
2856 .child(
2857 Label::new(user_rules_text)
2858 .size(LabelSize::XSmall)
2859 .color(Color::Muted)
2860 .truncate(),
2861 )
2862 .hover(|s| s.bg(cx.theme().colors().element_hover))
2863 .tooltip(Tooltip::text("View User Rules"))
2864 .on_click(move |_event, window, cx| {
2865 window.dispatch_action(
2866 Box::new(OpenRulesLibrary {
2867 prompt_to_select: first_user_rules_id,
2868 }),
2869 cx,
2870 )
2871 }),
2872 )
2873 })
2874 .when(has_both, |this| {
2875 this.child(
2876 Label::new("•")
2877 .size(LabelSize::XSmall)
2878 .color(Color::Disabled),
2879 )
2880 })
2881 .when_some(rules_file_text, |parent, rules_file_text| {
2882 parent.child(
2883 h_flex()
2884 .id("project-rules")
2885 .ml_1p5()
2886 .child(
2887 Label::new(rules_file_text)
2888 .size(LabelSize::XSmall)
2889 .color(Color::Muted),
2890 )
2891 .hover(|s| s.bg(cx.theme().colors().element_hover))
2892 .tooltip(Tooltip::text("View Project Rules"))
2893 .on_click(cx.listener(Self::handle_open_rules)),
2894 )
2895 })
2896 .into_any(),
2897 )
2898 }
2899
2900 fn render_empty_state_section_header(
2901 &self,
2902 label: impl Into<SharedString>,
2903 action_slot: Option<AnyElement>,
2904 cx: &mut Context<Self>,
2905 ) -> impl IntoElement {
2906 div().pl_1().pr_1p5().child(
2907 h_flex()
2908 .mt_2()
2909 .pl_1p5()
2910 .pb_1()
2911 .w_full()
2912 .justify_between()
2913 .border_b_1()
2914 .border_color(cx.theme().colors().border_variant)
2915 .child(
2916 Label::new(label.into())
2917 .size(LabelSize::Small)
2918 .color(Color::Muted),
2919 )
2920 .children(action_slot),
2921 )
2922 }
2923
2924 fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2925 let render_history = self
2926 .agent
2927 .clone()
2928 .downcast::<agent2::NativeAgentServer>()
2929 .is_some()
2930 && self
2931 .history_store
2932 .update(cx, |history_store, cx| !history_store.is_empty(cx));
2933
2934 v_flex()
2935 .size_full()
2936 .when(render_history, |this| {
2937 let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
2938 history_store.entries().take(3).collect()
2939 });
2940 this.justify_end().child(
2941 v_flex()
2942 .child(
2943 self.render_empty_state_section_header(
2944 "Recent",
2945 Some(
2946 Button::new("view-history", "View All")
2947 .style(ButtonStyle::Subtle)
2948 .label_size(LabelSize::Small)
2949 .key_binding(
2950 KeyBinding::for_action_in(
2951 &OpenHistory,
2952 &self.focus_handle(cx),
2953 window,
2954 cx,
2955 )
2956 .map(|kb| kb.size(rems_from_px(12.))),
2957 )
2958 .on_click(move |_event, window, cx| {
2959 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2960 })
2961 .into_any_element(),
2962 ),
2963 cx,
2964 ),
2965 )
2966 .child(
2967 v_flex().p_1().pr_1p5().gap_1().children(
2968 recent_history
2969 .into_iter()
2970 .enumerate()
2971 .map(|(index, entry)| {
2972 // TODO: Add keyboard navigation.
2973 let is_hovered =
2974 self.hovered_recent_history_item == Some(index);
2975 crate::acp::thread_history::AcpHistoryEntryElement::new(
2976 entry,
2977 cx.entity().downgrade(),
2978 )
2979 .hovered(is_hovered)
2980 .on_hover(cx.listener(
2981 move |this, is_hovered, _window, cx| {
2982 if *is_hovered {
2983 this.hovered_recent_history_item = Some(index);
2984 } else if this.hovered_recent_history_item
2985 == Some(index)
2986 {
2987 this.hovered_recent_history_item = None;
2988 }
2989 cx.notify();
2990 },
2991 ))
2992 .into_any_element()
2993 }),
2994 ),
2995 ),
2996 )
2997 })
2998 .into_any()
2999 }
3000
3001 fn render_auth_required_state(
3002 &self,
3003 connection: &Rc<dyn AgentConnection>,
3004 description: Option<&Entity<Markdown>>,
3005 configuration_view: Option<&AnyView>,
3006 pending_auth_method: Option<&acp::AuthMethodId>,
3007 window: &mut Window,
3008 cx: &Context<Self>,
3009 ) -> Div {
3010 let show_description =
3011 configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3012
3013 let auth_methods = connection.auth_methods();
3014
3015 v_flex().flex_1().size_full().justify_end().child(
3016 v_flex()
3017 .p_2()
3018 .pr_3()
3019 .w_full()
3020 .gap_1()
3021 .border_t_1()
3022 .border_color(cx.theme().colors().border)
3023 .bg(cx.theme().status().warning.opacity(0.04))
3024 .child(
3025 h_flex()
3026 .gap_1p5()
3027 .child(
3028 Icon::new(IconName::Warning)
3029 .color(Color::Warning)
3030 .size(IconSize::Small),
3031 )
3032 .child(Label::new("Authentication Required").size(LabelSize::Small)),
3033 )
3034 .children(description.map(|desc| {
3035 div().text_ui(cx).child(self.render_markdown(
3036 desc.clone(),
3037 default_markdown_style(false, false, window, cx),
3038 ))
3039 }))
3040 .children(
3041 configuration_view
3042 .cloned()
3043 .map(|view| div().w_full().child(view)),
3044 )
3045 .when(show_description, |el| {
3046 el.child(
3047 Label::new(format!(
3048 "You are not currently authenticated with {}.{}",
3049 self.agent.name(),
3050 if auth_methods.len() > 1 {
3051 " Please choose one of the following options:"
3052 } else {
3053 ""
3054 }
3055 ))
3056 .size(LabelSize::Small)
3057 .color(Color::Muted)
3058 .mb_1()
3059 .ml_5(),
3060 )
3061 })
3062 .when_some(pending_auth_method, |el, _| {
3063 el.child(
3064 h_flex()
3065 .py_4()
3066 .w_full()
3067 .justify_center()
3068 .gap_1()
3069 .child(
3070 Icon::new(IconName::ArrowCircle)
3071 .size(IconSize::Small)
3072 .color(Color::Muted)
3073 .with_rotate_animation(2),
3074 )
3075 .child(Label::new("Authenticating…").size(LabelSize::Small)),
3076 )
3077 })
3078 .when(!auth_methods.is_empty(), |this| {
3079 this.child(
3080 h_flex()
3081 .justify_end()
3082 .flex_wrap()
3083 .gap_1()
3084 .when(!show_description, |this| {
3085 this.border_t_1()
3086 .mt_1()
3087 .pt_2()
3088 .border_color(cx.theme().colors().border.opacity(0.8))
3089 })
3090 .children(connection.auth_methods().iter().enumerate().rev().map(
3091 |(ix, method)| {
3092 Button::new(
3093 SharedString::from(method.id.0.clone()),
3094 method.name.clone(),
3095 )
3096 .when(ix == 0, |el| {
3097 el.style(ButtonStyle::Tinted(ui::TintColor::Warning))
3098 })
3099 .label_size(LabelSize::Small)
3100 .on_click({
3101 let method_id = method.id.clone();
3102 cx.listener(move |this, _, window, cx| {
3103 telemetry::event!(
3104 "Authenticate Agent Started",
3105 agent = this.agent.telemetry_id(),
3106 method = method_id
3107 );
3108
3109 this.authenticate(method_id.clone(), window, cx)
3110 })
3111 })
3112 },
3113 )),
3114 )
3115 }),
3116 )
3117 }
3118
3119 fn render_load_error(
3120 &self,
3121 e: &LoadError,
3122 window: &mut Window,
3123 cx: &mut Context<Self>,
3124 ) -> AnyElement {
3125 let (title, message, action_slot): (_, SharedString, _) = match e {
3126 LoadError::Unsupported {
3127 command: path,
3128 current_version,
3129 minimum_version,
3130 } => {
3131 return self.render_unsupported(path, current_version, minimum_version, window, cx);
3132 }
3133 LoadError::FailedToInstall(msg) => (
3134 "Failed to Install",
3135 msg.into(),
3136 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3137 ),
3138 LoadError::Exited { status } => (
3139 "Failed to Launch",
3140 format!("Server exited with status {status}").into(),
3141 None,
3142 ),
3143 LoadError::Other(msg) => (
3144 "Failed to Launch",
3145 msg.into(),
3146 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3147 ),
3148 };
3149
3150 Callout::new()
3151 .severity(Severity::Error)
3152 .icon(IconName::XCircleFilled)
3153 .title(title)
3154 .description(message)
3155 .actions_slot(div().children(action_slot))
3156 .into_any_element()
3157 }
3158
3159 fn render_unsupported(
3160 &self,
3161 path: &SharedString,
3162 version: &SharedString,
3163 minimum_version: &SharedString,
3164 _window: &mut Window,
3165 cx: &mut Context<Self>,
3166 ) -> AnyElement {
3167 let (heading_label, description_label) = (
3168 format!("Upgrade {} to work with Zed", self.agent.name()),
3169 if version.is_empty() {
3170 format!(
3171 "Currently using {}, which does not report a valid --version",
3172 path,
3173 )
3174 } else {
3175 format!(
3176 "Currently using {}, which is only version {} (need at least {minimum_version})",
3177 path, version
3178 )
3179 },
3180 );
3181
3182 v_flex()
3183 .w_full()
3184 .p_3p5()
3185 .gap_2p5()
3186 .border_t_1()
3187 .border_color(cx.theme().colors().border)
3188 .bg(linear_gradient(
3189 180.,
3190 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3191 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3192 ))
3193 .child(
3194 v_flex().gap_0p5().child(Label::new(heading_label)).child(
3195 Label::new(description_label)
3196 .size(LabelSize::Small)
3197 .color(Color::Muted),
3198 ),
3199 )
3200 .into_any_element()
3201 }
3202
3203 fn render_activity_bar(
3204 &self,
3205 thread_entity: &Entity<AcpThread>,
3206 window: &mut Window,
3207 cx: &Context<Self>,
3208 ) -> Option<AnyElement> {
3209 let thread = thread_entity.read(cx);
3210 let action_log = thread.action_log();
3211 let changed_buffers = action_log.read(cx).changed_buffers(cx);
3212 let plan = thread.plan();
3213
3214 if changed_buffers.is_empty() && plan.is_empty() {
3215 return None;
3216 }
3217
3218 let editor_bg_color = cx.theme().colors().editor_background;
3219 let active_color = cx.theme().colors().element_selected;
3220 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
3221
3222 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3223 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3224 // be, which blocks you from being able to accept or reject edits. This switches the
3225 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3226 // block you from using the panel.
3227 let pending_edits = false;
3228
3229 v_flex()
3230 .mt_1()
3231 .mx_2()
3232 .bg(bg_edit_files_disclosure)
3233 .border_1()
3234 .border_b_0()
3235 .border_color(cx.theme().colors().border)
3236 .rounded_t_md()
3237 .shadow(vec![gpui::BoxShadow {
3238 color: gpui::black().opacity(0.15),
3239 offset: point(px(1.), px(-1.)),
3240 blur_radius: px(3.),
3241 spread_radius: px(0.),
3242 }])
3243 .when(!plan.is_empty(), |this| {
3244 this.child(self.render_plan_summary(plan, window, cx))
3245 .when(self.plan_expanded, |parent| {
3246 parent.child(self.render_plan_entries(plan, window, cx))
3247 })
3248 })
3249 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3250 this.child(Divider::horizontal().color(DividerColor::Border))
3251 })
3252 .when(!changed_buffers.is_empty(), |this| {
3253 this.child(self.render_edits_summary(
3254 &changed_buffers,
3255 self.edits_expanded,
3256 pending_edits,
3257 window,
3258 cx,
3259 ))
3260 .when(self.edits_expanded, |parent| {
3261 parent.child(self.render_edited_files(
3262 action_log,
3263 &changed_buffers,
3264 pending_edits,
3265 cx,
3266 ))
3267 })
3268 })
3269 .into_any()
3270 .into()
3271 }
3272
3273 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3274 let stats = plan.stats();
3275
3276 let title = if let Some(entry) = stats.in_progress_entry
3277 && !self.plan_expanded
3278 {
3279 h_flex()
3280 .w_full()
3281 .cursor_default()
3282 .gap_1()
3283 .text_xs()
3284 .text_color(cx.theme().colors().text_muted)
3285 .justify_between()
3286 .child(
3287 h_flex()
3288 .gap_1()
3289 .child(
3290 Label::new("Current:")
3291 .size(LabelSize::Small)
3292 .color(Color::Muted),
3293 )
3294 .child(MarkdownElement::new(
3295 entry.content.clone(),
3296 plan_label_markdown_style(&entry.status, window, cx),
3297 )),
3298 )
3299 .when(stats.pending > 0, |this| {
3300 this.child(
3301 Label::new(format!("{} left", stats.pending))
3302 .size(LabelSize::Small)
3303 .color(Color::Muted)
3304 .mr_1(),
3305 )
3306 })
3307 } else {
3308 let status_label = if stats.pending == 0 {
3309 "All Done".to_string()
3310 } else if stats.completed == 0 {
3311 format!("{} Tasks", plan.entries.len())
3312 } else {
3313 format!("{}/{}", stats.completed, plan.entries.len())
3314 };
3315
3316 h_flex()
3317 .w_full()
3318 .gap_1()
3319 .justify_between()
3320 .child(
3321 Label::new("Plan")
3322 .size(LabelSize::Small)
3323 .color(Color::Muted),
3324 )
3325 .child(
3326 Label::new(status_label)
3327 .size(LabelSize::Small)
3328 .color(Color::Muted)
3329 .mr_1(),
3330 )
3331 };
3332
3333 h_flex()
3334 .p_1()
3335 .justify_between()
3336 .when(self.plan_expanded, |this| {
3337 this.border_b_1().border_color(cx.theme().colors().border)
3338 })
3339 .child(
3340 h_flex()
3341 .id("plan_summary")
3342 .w_full()
3343 .gap_1()
3344 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3345 .child(title)
3346 .on_click(cx.listener(|this, _, _, cx| {
3347 this.plan_expanded = !this.plan_expanded;
3348 cx.notify();
3349 })),
3350 )
3351 }
3352
3353 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3354 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3355 let element = h_flex()
3356 .py_1()
3357 .px_2()
3358 .gap_2()
3359 .justify_between()
3360 .bg(cx.theme().colors().editor_background)
3361 .when(index < plan.entries.len() - 1, |parent| {
3362 parent.border_color(cx.theme().colors().border).border_b_1()
3363 })
3364 .child(
3365 h_flex()
3366 .id(("plan_entry", index))
3367 .gap_1p5()
3368 .max_w_full()
3369 .overflow_x_scroll()
3370 .text_xs()
3371 .text_color(cx.theme().colors().text_muted)
3372 .child(match entry.status {
3373 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3374 .size(IconSize::Small)
3375 .color(Color::Muted)
3376 .into_any_element(),
3377 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3378 .size(IconSize::Small)
3379 .color(Color::Accent)
3380 .with_rotate_animation(2)
3381 .into_any_element(),
3382 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3383 .size(IconSize::Small)
3384 .color(Color::Success)
3385 .into_any_element(),
3386 })
3387 .child(MarkdownElement::new(
3388 entry.content.clone(),
3389 plan_label_markdown_style(&entry.status, window, cx),
3390 )),
3391 );
3392
3393 Some(element)
3394 }))
3395 }
3396
3397 fn render_edits_summary(
3398 &self,
3399 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3400 expanded: bool,
3401 pending_edits: bool,
3402 window: &mut Window,
3403 cx: &Context<Self>,
3404 ) -> Div {
3405 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3406
3407 let focus_handle = self.focus_handle(cx);
3408
3409 h_flex()
3410 .p_1()
3411 .justify_between()
3412 .flex_wrap()
3413 .when(expanded, |this| {
3414 this.border_b_1().border_color(cx.theme().colors().border)
3415 })
3416 .child(
3417 h_flex()
3418 .id("edits-container")
3419 .gap_1()
3420 .child(Disclosure::new("edits-disclosure", expanded))
3421 .map(|this| {
3422 if pending_edits {
3423 this.child(
3424 Label::new(format!(
3425 "Editing {} {}…",
3426 changed_buffers.len(),
3427 if changed_buffers.len() == 1 {
3428 "file"
3429 } else {
3430 "files"
3431 }
3432 ))
3433 .color(Color::Muted)
3434 .size(LabelSize::Small)
3435 .with_animation(
3436 "edit-label",
3437 Animation::new(Duration::from_secs(2))
3438 .repeat()
3439 .with_easing(pulsating_between(0.3, 0.7)),
3440 |label, delta| label.alpha(delta),
3441 ),
3442 )
3443 } else {
3444 this.child(
3445 Label::new("Edits")
3446 .size(LabelSize::Small)
3447 .color(Color::Muted),
3448 )
3449 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3450 .child(
3451 Label::new(format!(
3452 "{} {}",
3453 changed_buffers.len(),
3454 if changed_buffers.len() == 1 {
3455 "file"
3456 } else {
3457 "files"
3458 }
3459 ))
3460 .size(LabelSize::Small)
3461 .color(Color::Muted),
3462 )
3463 }
3464 })
3465 .on_click(cx.listener(|this, _, _, cx| {
3466 this.edits_expanded = !this.edits_expanded;
3467 cx.notify();
3468 })),
3469 )
3470 .child(
3471 h_flex()
3472 .gap_1()
3473 .child(
3474 IconButton::new("review-changes", IconName::ListTodo)
3475 .icon_size(IconSize::Small)
3476 .tooltip({
3477 let focus_handle = focus_handle.clone();
3478 move |window, cx| {
3479 Tooltip::for_action_in(
3480 "Review Changes",
3481 &OpenAgentDiff,
3482 &focus_handle,
3483 window,
3484 cx,
3485 )
3486 }
3487 })
3488 .on_click(cx.listener(|_, _, window, cx| {
3489 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3490 })),
3491 )
3492 .child(Divider::vertical().color(DividerColor::Border))
3493 .child(
3494 Button::new("reject-all-changes", "Reject All")
3495 .label_size(LabelSize::Small)
3496 .disabled(pending_edits)
3497 .when(pending_edits, |this| {
3498 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3499 })
3500 .key_binding(
3501 KeyBinding::for_action_in(
3502 &RejectAll,
3503 &focus_handle.clone(),
3504 window,
3505 cx,
3506 )
3507 .map(|kb| kb.size(rems_from_px(10.))),
3508 )
3509 .on_click(cx.listener(move |this, _, window, cx| {
3510 this.reject_all(&RejectAll, window, cx);
3511 })),
3512 )
3513 .child(
3514 Button::new("keep-all-changes", "Keep All")
3515 .label_size(LabelSize::Small)
3516 .disabled(pending_edits)
3517 .when(pending_edits, |this| {
3518 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3519 })
3520 .key_binding(
3521 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3522 .map(|kb| kb.size(rems_from_px(10.))),
3523 )
3524 .on_click(cx.listener(move |this, _, window, cx| {
3525 this.keep_all(&KeepAll, window, cx);
3526 })),
3527 ),
3528 )
3529 }
3530
3531 fn render_edited_files(
3532 &self,
3533 action_log: &Entity<ActionLog>,
3534 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3535 pending_edits: bool,
3536 cx: &Context<Self>,
3537 ) -> Div {
3538 let editor_bg_color = cx.theme().colors().editor_background;
3539
3540 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3541 |(index, (buffer, _diff))| {
3542 let file = buffer.read(cx).file()?;
3543 let path = file.path();
3544
3545 let file_path = path.parent().and_then(|parent| {
3546 let parent_str = parent.to_string_lossy();
3547
3548 if parent_str.is_empty() {
3549 None
3550 } else {
3551 Some(
3552 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3553 .color(Color::Muted)
3554 .size(LabelSize::XSmall)
3555 .buffer_font(cx),
3556 )
3557 }
3558 });
3559
3560 let file_name = path.file_name().map(|name| {
3561 Label::new(name.to_string_lossy().to_string())
3562 .size(LabelSize::XSmall)
3563 .buffer_font(cx)
3564 });
3565
3566 let file_icon = FileIcons::get_icon(path, cx)
3567 .map(Icon::from_path)
3568 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3569 .unwrap_or_else(|| {
3570 Icon::new(IconName::File)
3571 .color(Color::Muted)
3572 .size(IconSize::Small)
3573 });
3574
3575 let overlay_gradient = linear_gradient(
3576 90.,
3577 linear_color_stop(editor_bg_color, 1.),
3578 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3579 );
3580
3581 let element = h_flex()
3582 .group("edited-code")
3583 .id(("file-container", index))
3584 .py_1()
3585 .pl_2()
3586 .pr_1()
3587 .gap_2()
3588 .justify_between()
3589 .bg(editor_bg_color)
3590 .when(index < changed_buffers.len() - 1, |parent| {
3591 parent.border_color(cx.theme().colors().border).border_b_1()
3592 })
3593 .child(
3594 h_flex()
3595 .relative()
3596 .id(("file-name", index))
3597 .pr_8()
3598 .gap_1p5()
3599 .max_w_full()
3600 .overflow_x_scroll()
3601 .child(file_icon)
3602 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3603 .child(
3604 div()
3605 .absolute()
3606 .h_full()
3607 .w_12()
3608 .top_0()
3609 .bottom_0()
3610 .right_0()
3611 .bg(overlay_gradient),
3612 )
3613 .on_click({
3614 let buffer = buffer.clone();
3615 cx.listener(move |this, _, window, cx| {
3616 this.open_edited_buffer(&buffer, window, cx);
3617 })
3618 }),
3619 )
3620 .child(
3621 h_flex()
3622 .gap_1()
3623 .visible_on_hover("edited-code")
3624 .child(
3625 Button::new("review", "Review")
3626 .label_size(LabelSize::Small)
3627 .on_click({
3628 let buffer = buffer.clone();
3629 cx.listener(move |this, _, window, cx| {
3630 this.open_edited_buffer(&buffer, window, cx);
3631 })
3632 }),
3633 )
3634 .child(Divider::vertical().color(DividerColor::BorderVariant))
3635 .child(
3636 Button::new("reject-file", "Reject")
3637 .label_size(LabelSize::Small)
3638 .disabled(pending_edits)
3639 .on_click({
3640 let buffer = buffer.clone();
3641 let action_log = action_log.clone();
3642 move |_, _, cx| {
3643 action_log.update(cx, |action_log, cx| {
3644 action_log
3645 .reject_edits_in_ranges(
3646 buffer.clone(),
3647 vec![Anchor::MIN..Anchor::MAX],
3648 cx,
3649 )
3650 .detach_and_log_err(cx);
3651 })
3652 }
3653 }),
3654 )
3655 .child(
3656 Button::new("keep-file", "Keep")
3657 .label_size(LabelSize::Small)
3658 .disabled(pending_edits)
3659 .on_click({
3660 let buffer = buffer.clone();
3661 let action_log = action_log.clone();
3662 move |_, _, cx| {
3663 action_log.update(cx, |action_log, cx| {
3664 action_log.keep_edits_in_range(
3665 buffer.clone(),
3666 Anchor::MIN..Anchor::MAX,
3667 cx,
3668 );
3669 })
3670 }
3671 }),
3672 ),
3673 );
3674
3675 Some(element)
3676 },
3677 ))
3678 }
3679
3680 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3681 let focus_handle = self.message_editor.focus_handle(cx);
3682 let editor_bg_color = cx.theme().colors().editor_background;
3683 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3684 (IconName::Minimize, "Minimize Message Editor")
3685 } else {
3686 (IconName::Maximize, "Expand Message Editor")
3687 };
3688
3689 let backdrop = div()
3690 .size_full()
3691 .absolute()
3692 .inset_0()
3693 .bg(cx.theme().colors().panel_background)
3694 .opacity(0.8)
3695 .block_mouse_except_scroll();
3696
3697 let enable_editor = match self.thread_state {
3698 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3699 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3700 };
3701
3702 v_flex()
3703 .on_action(cx.listener(Self::expand_message_editor))
3704 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3705 if let Some(profile_selector) = this.profile_selector.as_ref() {
3706 profile_selector.read(cx).menu_handle().toggle(window, cx);
3707 }
3708 }))
3709 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3710 if let Some(model_selector) = this.model_selector.as_ref() {
3711 model_selector
3712 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3713 }
3714 }))
3715 .p_2()
3716 .gap_2()
3717 .border_t_1()
3718 .border_color(cx.theme().colors().border)
3719 .bg(editor_bg_color)
3720 .when(self.editor_expanded, |this| {
3721 this.h(vh(0.8, window)).size_full().justify_between()
3722 })
3723 .child(
3724 v_flex()
3725 .relative()
3726 .size_full()
3727 .pt_1()
3728 .pr_2p5()
3729 .child(self.message_editor.clone())
3730 .child(
3731 h_flex()
3732 .absolute()
3733 .top_0()
3734 .right_0()
3735 .opacity(0.5)
3736 .hover(|this| this.opacity(1.0))
3737 .child(
3738 IconButton::new("toggle-height", expand_icon)
3739 .icon_size(IconSize::Small)
3740 .icon_color(Color::Muted)
3741 .tooltip({
3742 move |window, cx| {
3743 Tooltip::for_action_in(
3744 expand_tooltip,
3745 &ExpandMessageEditor,
3746 &focus_handle,
3747 window,
3748 cx,
3749 )
3750 }
3751 })
3752 .on_click(cx.listener(|_, _, window, cx| {
3753 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3754 })),
3755 ),
3756 ),
3757 )
3758 .child(
3759 h_flex()
3760 .flex_none()
3761 .flex_wrap()
3762 .justify_between()
3763 .child(
3764 h_flex()
3765 .child(self.render_follow_toggle(cx))
3766 .children(self.render_burn_mode_toggle(cx)),
3767 )
3768 .child(
3769 h_flex()
3770 .gap_1()
3771 .children(self.render_token_usage(cx))
3772 .children(self.profile_selector.clone())
3773 .children(self.model_selector.clone())
3774 .child(self.render_send_button(cx)),
3775 ),
3776 )
3777 .when(!enable_editor, |this| this.child(backdrop))
3778 .into_any()
3779 }
3780
3781 pub(crate) fn as_native_connection(
3782 &self,
3783 cx: &App,
3784 ) -> Option<Rc<agent2::NativeAgentConnection>> {
3785 let acp_thread = self.thread()?.read(cx);
3786 acp_thread.connection().clone().downcast()
3787 }
3788
3789 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3790 let acp_thread = self.thread()?.read(cx);
3791 self.as_native_connection(cx)?
3792 .thread(acp_thread.session_id(), cx)
3793 }
3794
3795 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3796 self.as_native_thread(cx)
3797 .and_then(|thread| thread.read(cx).model())
3798 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3799 }
3800
3801 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3802 let thread = self.thread()?.read(cx);
3803 let usage = thread.token_usage()?;
3804 let is_generating = thread.status() != ThreadStatus::Idle;
3805
3806 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3807 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3808
3809 Some(
3810 h_flex()
3811 .flex_shrink_0()
3812 .gap_0p5()
3813 .mr_1p5()
3814 .child(
3815 Label::new(used)
3816 .size(LabelSize::Small)
3817 .color(Color::Muted)
3818 .map(|label| {
3819 if is_generating {
3820 label
3821 .with_animation(
3822 "used-tokens-label",
3823 Animation::new(Duration::from_secs(2))
3824 .repeat()
3825 .with_easing(pulsating_between(0.3, 0.8)),
3826 |label, delta| label.alpha(delta),
3827 )
3828 .into_any()
3829 } else {
3830 label.into_any_element()
3831 }
3832 }),
3833 )
3834 .child(
3835 Label::new("/")
3836 .size(LabelSize::Small)
3837 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3838 )
3839 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3840 )
3841 }
3842
3843 fn toggle_burn_mode(
3844 &mut self,
3845 _: &ToggleBurnMode,
3846 _window: &mut Window,
3847 cx: &mut Context<Self>,
3848 ) {
3849 let Some(thread) = self.as_native_thread(cx) else {
3850 return;
3851 };
3852
3853 thread.update(cx, |thread, cx| {
3854 let current_mode = thread.completion_mode();
3855 thread.set_completion_mode(
3856 match current_mode {
3857 CompletionMode::Burn => CompletionMode::Normal,
3858 CompletionMode::Normal => CompletionMode::Burn,
3859 },
3860 cx,
3861 );
3862 });
3863 }
3864
3865 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3866 let Some(thread) = self.thread() else {
3867 return;
3868 };
3869 let action_log = thread.read(cx).action_log().clone();
3870 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3871 }
3872
3873 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3874 let Some(thread) = self.thread() else {
3875 return;
3876 };
3877 let action_log = thread.read(cx).action_log().clone();
3878 action_log
3879 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3880 .detach();
3881 }
3882
3883 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3884 let thread = self.as_native_thread(cx)?.read(cx);
3885
3886 if thread
3887 .model()
3888 .is_none_or(|model| !model.supports_burn_mode())
3889 {
3890 return None;
3891 }
3892
3893 let active_completion_mode = thread.completion_mode();
3894 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3895 let icon = if burn_mode_enabled {
3896 IconName::ZedBurnModeOn
3897 } else {
3898 IconName::ZedBurnMode
3899 };
3900
3901 Some(
3902 IconButton::new("burn-mode", icon)
3903 .icon_size(IconSize::Small)
3904 .icon_color(Color::Muted)
3905 .toggle_state(burn_mode_enabled)
3906 .selected_icon_color(Color::Error)
3907 .on_click(cx.listener(|this, _event, window, cx| {
3908 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3909 }))
3910 .tooltip(move |_window, cx| {
3911 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3912 .into()
3913 })
3914 .into_any_element(),
3915 )
3916 }
3917
3918 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3919 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3920 let is_generating = self
3921 .thread()
3922 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3923
3924 if self.is_loading_contents {
3925 div()
3926 .id("loading-message-content")
3927 .px_1()
3928 .tooltip(Tooltip::text("Loading Added Context…"))
3929 .child(loading_contents_spinner(IconSize::default()))
3930 .into_any_element()
3931 } else if is_generating && is_editor_empty {
3932 IconButton::new("stop-generation", IconName::Stop)
3933 .icon_color(Color::Error)
3934 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3935 .tooltip(move |window, cx| {
3936 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3937 })
3938 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3939 .into_any_element()
3940 } else {
3941 let send_btn_tooltip = if is_editor_empty && !is_generating {
3942 "Type to Send"
3943 } else if is_generating {
3944 "Stop and Send Message"
3945 } else {
3946 "Send"
3947 };
3948
3949 IconButton::new("send-message", IconName::Send)
3950 .style(ButtonStyle::Filled)
3951 .map(|this| {
3952 if is_editor_empty && !is_generating {
3953 this.disabled(true).icon_color(Color::Muted)
3954 } else {
3955 this.icon_color(Color::Accent)
3956 }
3957 })
3958 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3959 .on_click(cx.listener(|this, _, window, cx| {
3960 this.send(window, cx);
3961 }))
3962 .into_any_element()
3963 }
3964 }
3965
3966 fn is_following(&self, cx: &App) -> bool {
3967 match self.thread().map(|thread| thread.read(cx).status()) {
3968 Some(ThreadStatus::Generating) => self
3969 .workspace
3970 .read_with(cx, |workspace, _| {
3971 workspace.is_being_followed(CollaboratorId::Agent)
3972 })
3973 .unwrap_or(false),
3974 _ => self.should_be_following,
3975 }
3976 }
3977
3978 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3979 let following = self.is_following(cx);
3980
3981 self.should_be_following = !following;
3982 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3983 self.workspace
3984 .update(cx, |workspace, cx| {
3985 if following {
3986 workspace.unfollow(CollaboratorId::Agent, window, cx);
3987 } else {
3988 workspace.follow(CollaboratorId::Agent, window, cx);
3989 }
3990 })
3991 .ok();
3992 }
3993
3994 telemetry::event!("Follow Agent Selected", following = !following);
3995 }
3996
3997 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3998 let following = self.is_following(cx);
3999
4000 let tooltip_label = if following {
4001 if self.agent.name() == "Zed Agent" {
4002 format!("Stop Following the {}", self.agent.name())
4003 } else {
4004 format!("Stop Following {}", self.agent.name())
4005 }
4006 } else {
4007 if self.agent.name() == "Zed Agent" {
4008 format!("Follow the {}", self.agent.name())
4009 } else {
4010 format!("Follow {}", self.agent.name())
4011 }
4012 };
4013
4014 IconButton::new("follow-agent", IconName::Crosshair)
4015 .icon_size(IconSize::Small)
4016 .icon_color(Color::Muted)
4017 .toggle_state(following)
4018 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4019 .tooltip(move |window, cx| {
4020 if following {
4021 Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
4022 } else {
4023 Tooltip::with_meta(
4024 tooltip_label.clone(),
4025 Some(&Follow),
4026 "Track the agent's location as it reads and edits files.",
4027 window,
4028 cx,
4029 )
4030 }
4031 })
4032 .on_click(cx.listener(move |this, _, window, cx| {
4033 this.toggle_following(window, cx);
4034 }))
4035 }
4036
4037 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4038 let workspace = self.workspace.clone();
4039 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4040 Self::open_link(text, &workspace, window, cx);
4041 })
4042 }
4043
4044 fn open_link(
4045 url: SharedString,
4046 workspace: &WeakEntity<Workspace>,
4047 window: &mut Window,
4048 cx: &mut App,
4049 ) {
4050 let Some(workspace) = workspace.upgrade() else {
4051 cx.open_url(&url);
4052 return;
4053 };
4054
4055 if let Some(mention) = MentionUri::parse(&url).log_err() {
4056 workspace.update(cx, |workspace, cx| match mention {
4057 MentionUri::File { abs_path } => {
4058 let project = workspace.project();
4059 let Some(path) =
4060 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4061 else {
4062 return;
4063 };
4064
4065 workspace
4066 .open_path(path, None, true, window, cx)
4067 .detach_and_log_err(cx);
4068 }
4069 MentionUri::PastedImage => {}
4070 MentionUri::Directory { abs_path } => {
4071 let project = workspace.project();
4072 let Some(entry) = project.update(cx, |project, cx| {
4073 let path = project.find_project_path(abs_path, cx)?;
4074 project.entry_for_path(&path, cx)
4075 }) else {
4076 return;
4077 };
4078
4079 project.update(cx, |_, cx| {
4080 cx.emit(project::Event::RevealInProjectPanel(entry.id));
4081 });
4082 }
4083 MentionUri::Symbol {
4084 abs_path: path,
4085 line_range,
4086 ..
4087 }
4088 | MentionUri::Selection {
4089 abs_path: Some(path),
4090 line_range,
4091 } => {
4092 let project = workspace.project();
4093 let Some((path, _)) = project.update(cx, |project, cx| {
4094 let path = project.find_project_path(path, cx)?;
4095 let entry = project.entry_for_path(&path, cx)?;
4096 Some((path, entry))
4097 }) else {
4098 return;
4099 };
4100
4101 let item = workspace.open_path(path, None, true, window, cx);
4102 window
4103 .spawn(cx, async move |cx| {
4104 let Some(editor) = item.await?.downcast::<Editor>() else {
4105 return Ok(());
4106 };
4107 let range = Point::new(*line_range.start(), 0)
4108 ..Point::new(*line_range.start(), 0);
4109 editor
4110 .update_in(cx, |editor, window, cx| {
4111 editor.change_selections(
4112 SelectionEffects::scroll(Autoscroll::center()),
4113 window,
4114 cx,
4115 |s| s.select_ranges(vec![range]),
4116 );
4117 })
4118 .ok();
4119 anyhow::Ok(())
4120 })
4121 .detach_and_log_err(cx);
4122 }
4123 MentionUri::Selection { abs_path: None, .. } => {}
4124 MentionUri::Thread { id, name } => {
4125 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4126 panel.update(cx, |panel, cx| {
4127 panel.load_agent_thread(
4128 DbThreadMetadata {
4129 id,
4130 title: name.into(),
4131 updated_at: Default::default(),
4132 },
4133 window,
4134 cx,
4135 )
4136 });
4137 }
4138 }
4139 MentionUri::TextThread { path, .. } => {
4140 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4141 panel.update(cx, |panel, cx| {
4142 panel
4143 .open_saved_prompt_editor(path.as_path().into(), window, cx)
4144 .detach_and_log_err(cx);
4145 });
4146 }
4147 }
4148 MentionUri::Rule { id, .. } => {
4149 let PromptId::User { uuid } = id else {
4150 return;
4151 };
4152 window.dispatch_action(
4153 Box::new(OpenRulesLibrary {
4154 prompt_to_select: Some(uuid.0),
4155 }),
4156 cx,
4157 )
4158 }
4159 MentionUri::Fetch { url } => {
4160 cx.open_url(url.as_str());
4161 }
4162 })
4163 } else {
4164 cx.open_url(&url);
4165 }
4166 }
4167
4168 fn open_tool_call_location(
4169 &self,
4170 entry_ix: usize,
4171 location_ix: usize,
4172 window: &mut Window,
4173 cx: &mut Context<Self>,
4174 ) -> Option<()> {
4175 let (tool_call_location, agent_location) = self
4176 .thread()?
4177 .read(cx)
4178 .entries()
4179 .get(entry_ix)?
4180 .location(location_ix)?;
4181
4182 let project_path = self
4183 .project
4184 .read(cx)
4185 .find_project_path(&tool_call_location.path, cx)?;
4186
4187 let open_task = self
4188 .workspace
4189 .update(cx, |workspace, cx| {
4190 workspace.open_path(project_path, None, true, window, cx)
4191 })
4192 .log_err()?;
4193 window
4194 .spawn(cx, async move |cx| {
4195 let item = open_task.await?;
4196
4197 let Some(active_editor) = item.downcast::<Editor>() else {
4198 return anyhow::Ok(());
4199 };
4200
4201 active_editor.update_in(cx, |editor, window, cx| {
4202 let multibuffer = editor.buffer().read(cx);
4203 let buffer = multibuffer.as_singleton();
4204 if agent_location.buffer.upgrade() == buffer {
4205 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4206 let anchor = editor::Anchor::in_buffer(
4207 excerpt_id.unwrap(),
4208 buffer.unwrap().read(cx).remote_id(),
4209 agent_location.position,
4210 );
4211 editor.change_selections(Default::default(), window, cx, |selections| {
4212 selections.select_anchor_ranges([anchor..anchor]);
4213 })
4214 } else {
4215 let row = tool_call_location.line.unwrap_or_default();
4216 editor.change_selections(Default::default(), window, cx, |selections| {
4217 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4218 })
4219 }
4220 })?;
4221
4222 anyhow::Ok(())
4223 })
4224 .detach_and_log_err(cx);
4225
4226 None
4227 }
4228
4229 pub fn open_thread_as_markdown(
4230 &self,
4231 workspace: Entity<Workspace>,
4232 window: &mut Window,
4233 cx: &mut App,
4234 ) -> Task<Result<()>> {
4235 let markdown_language_task = workspace
4236 .read(cx)
4237 .app_state()
4238 .languages
4239 .language_for_name("Markdown");
4240
4241 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4242 let thread = thread.read(cx);
4243 (thread.title().to_string(), thread.to_markdown(cx))
4244 } else {
4245 return Task::ready(Ok(()));
4246 };
4247
4248 window.spawn(cx, async move |cx| {
4249 let markdown_language = markdown_language_task.await?;
4250
4251 workspace.update_in(cx, |workspace, window, cx| {
4252 let project = workspace.project().clone();
4253
4254 if !project.read(cx).is_local() {
4255 bail!("failed to open active thread as markdown in remote project");
4256 }
4257
4258 let buffer = project.update(cx, |project, cx| {
4259 project.create_local_buffer(&markdown, Some(markdown_language), cx)
4260 });
4261 let buffer = cx.new(|cx| {
4262 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4263 });
4264
4265 workspace.add_item_to_active_pane(
4266 Box::new(cx.new(|cx| {
4267 let mut editor =
4268 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4269 editor.set_breadcrumb_header(thread_summary);
4270 editor
4271 })),
4272 None,
4273 true,
4274 window,
4275 cx,
4276 );
4277
4278 anyhow::Ok(())
4279 })??;
4280 anyhow::Ok(())
4281 })
4282 }
4283
4284 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4285 self.list_state.scroll_to(ListOffset::default());
4286 cx.notify();
4287 }
4288
4289 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4290 if let Some(thread) = self.thread() {
4291 let entry_count = thread.read(cx).entries().len();
4292 self.list_state.reset(entry_count);
4293 cx.notify();
4294 }
4295 }
4296
4297 fn notify_with_sound(
4298 &mut self,
4299 caption: impl Into<SharedString>,
4300 icon: IconName,
4301 window: &mut Window,
4302 cx: &mut Context<Self>,
4303 ) {
4304 self.play_notification_sound(window, cx);
4305 self.show_notification(caption, icon, window, cx);
4306 }
4307
4308 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4309 let settings = AgentSettings::get_global(cx);
4310 if settings.play_sound_when_agent_done && !window.is_window_active() {
4311 Audio::play_sound(Sound::AgentDone, cx);
4312 }
4313 }
4314
4315 fn show_notification(
4316 &mut self,
4317 caption: impl Into<SharedString>,
4318 icon: IconName,
4319 window: &mut Window,
4320 cx: &mut Context<Self>,
4321 ) {
4322 if window.is_window_active() || !self.notifications.is_empty() {
4323 return;
4324 }
4325
4326 // TODO: Change this once we have title summarization for external agents.
4327 let title = self.agent.name();
4328
4329 match AgentSettings::get_global(cx).notify_when_agent_waiting {
4330 NotifyWhenAgentWaiting::PrimaryScreen => {
4331 if let Some(primary) = cx.primary_display() {
4332 self.pop_up(icon, caption.into(), title, window, primary, cx);
4333 }
4334 }
4335 NotifyWhenAgentWaiting::AllScreens => {
4336 let caption = caption.into();
4337 for screen in cx.displays() {
4338 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4339 }
4340 }
4341 NotifyWhenAgentWaiting::Never => {
4342 // Don't show anything
4343 }
4344 }
4345 }
4346
4347 fn pop_up(
4348 &mut self,
4349 icon: IconName,
4350 caption: SharedString,
4351 title: SharedString,
4352 window: &mut Window,
4353 screen: Rc<dyn PlatformDisplay>,
4354 cx: &mut Context<Self>,
4355 ) {
4356 let options = AgentNotification::window_options(screen, cx);
4357
4358 let project_name = self.workspace.upgrade().and_then(|workspace| {
4359 workspace
4360 .read(cx)
4361 .project()
4362 .read(cx)
4363 .visible_worktrees(cx)
4364 .next()
4365 .map(|worktree| worktree.read(cx).root_name().to_string())
4366 });
4367
4368 if let Some(screen_window) = cx
4369 .open_window(options, |_, cx| {
4370 cx.new(|_| {
4371 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4372 })
4373 })
4374 .log_err()
4375 && let Some(pop_up) = screen_window.entity(cx).log_err()
4376 {
4377 self.notification_subscriptions
4378 .entry(screen_window)
4379 .or_insert_with(Vec::new)
4380 .push(cx.subscribe_in(&pop_up, window, {
4381 |this, _, event, window, cx| match event {
4382 AgentNotificationEvent::Accepted => {
4383 let handle = window.window_handle();
4384 cx.activate(true);
4385
4386 let workspace_handle = this.workspace.clone();
4387
4388 // If there are multiple Zed windows, activate the correct one.
4389 cx.defer(move |cx| {
4390 handle
4391 .update(cx, |_view, window, _cx| {
4392 window.activate_window();
4393
4394 if let Some(workspace) = workspace_handle.upgrade() {
4395 workspace.update(_cx, |workspace, cx| {
4396 workspace.focus_panel::<AgentPanel>(window, cx);
4397 });
4398 }
4399 })
4400 .log_err();
4401 });
4402
4403 this.dismiss_notifications(cx);
4404 }
4405 AgentNotificationEvent::Dismissed => {
4406 this.dismiss_notifications(cx);
4407 }
4408 }
4409 }));
4410
4411 self.notifications.push(screen_window);
4412
4413 // If the user manually refocuses the original window, dismiss the popup.
4414 self.notification_subscriptions
4415 .entry(screen_window)
4416 .or_insert_with(Vec::new)
4417 .push({
4418 let pop_up_weak = pop_up.downgrade();
4419
4420 cx.observe_window_activation(window, move |_, window, cx| {
4421 if window.is_window_active()
4422 && let Some(pop_up) = pop_up_weak.upgrade()
4423 {
4424 pop_up.update(cx, |_, cx| {
4425 cx.emit(AgentNotificationEvent::Dismissed);
4426 });
4427 }
4428 })
4429 });
4430 }
4431 }
4432
4433 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4434 for window in self.notifications.drain(..) {
4435 window
4436 .update(cx, |_, window, _| {
4437 window.remove_window();
4438 })
4439 .ok();
4440
4441 self.notification_subscriptions.remove(&window);
4442 }
4443 }
4444
4445 fn render_thread_controls(
4446 &self,
4447 thread: &Entity<AcpThread>,
4448 cx: &Context<Self>,
4449 ) -> impl IntoElement {
4450 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4451 if is_generating {
4452 return h_flex().id("thread-controls-container").child(
4453 div()
4454 .py_2()
4455 .px(rems_from_px(22.))
4456 .child(SpinnerLabel::new().size(LabelSize::Small)),
4457 );
4458 }
4459
4460 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4461 .shape(ui::IconButtonShape::Square)
4462 .icon_size(IconSize::Small)
4463 .icon_color(Color::Ignored)
4464 .tooltip(Tooltip::text("Open Thread as Markdown"))
4465 .on_click(cx.listener(move |this, _, window, cx| {
4466 if let Some(workspace) = this.workspace.upgrade() {
4467 this.open_thread_as_markdown(workspace, window, cx)
4468 .detach_and_log_err(cx);
4469 }
4470 }));
4471
4472 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4473 .shape(ui::IconButtonShape::Square)
4474 .icon_size(IconSize::Small)
4475 .icon_color(Color::Ignored)
4476 .tooltip(Tooltip::text("Scroll To Top"))
4477 .on_click(cx.listener(move |this, _, _, cx| {
4478 this.scroll_to_top(cx);
4479 }));
4480
4481 let mut container = h_flex()
4482 .id("thread-controls-container")
4483 .group("thread-controls-container")
4484 .w_full()
4485 .py_2()
4486 .px_5()
4487 .gap_px()
4488 .opacity(0.6)
4489 .hover(|style| style.opacity(1.))
4490 .flex_wrap()
4491 .justify_end();
4492
4493 if AgentSettings::get_global(cx).enable_feedback
4494 && self
4495 .thread()
4496 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4497 {
4498 let feedback = self.thread_feedback.feedback;
4499
4500 container = container
4501 .child(
4502 div().visible_on_hover("thread-controls-container").child(
4503 Label::new(match feedback {
4504 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4505 Some(ThreadFeedback::Negative) => {
4506 "We appreciate your feedback and will use it to improve."
4507 }
4508 None => {
4509 "Rating the thread sends all of your current conversation to the Zed team."
4510 }
4511 })
4512 .color(Color::Muted)
4513 .size(LabelSize::XSmall)
4514 .truncate(),
4515 ),
4516 )
4517 .child(
4518 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4519 .shape(ui::IconButtonShape::Square)
4520 .icon_size(IconSize::Small)
4521 .icon_color(match feedback {
4522 Some(ThreadFeedback::Positive) => Color::Accent,
4523 _ => Color::Ignored,
4524 })
4525 .tooltip(Tooltip::text("Helpful Response"))
4526 .on_click(cx.listener(move |this, _, window, cx| {
4527 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4528 })),
4529 )
4530 .child(
4531 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4532 .shape(ui::IconButtonShape::Square)
4533 .icon_size(IconSize::Small)
4534 .icon_color(match feedback {
4535 Some(ThreadFeedback::Negative) => Color::Accent,
4536 _ => Color::Ignored,
4537 })
4538 .tooltip(Tooltip::text("Not Helpful"))
4539 .on_click(cx.listener(move |this, _, window, cx| {
4540 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4541 })),
4542 );
4543 }
4544
4545 container.child(open_as_markdown).child(scroll_to_top)
4546 }
4547
4548 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4549 h_flex()
4550 .key_context("AgentFeedbackMessageEditor")
4551 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4552 this.thread_feedback.dismiss_comments();
4553 cx.notify();
4554 }))
4555 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4556 this.submit_feedback_message(cx);
4557 }))
4558 .p_2()
4559 .mb_2()
4560 .mx_5()
4561 .gap_1()
4562 .rounded_md()
4563 .border_1()
4564 .border_color(cx.theme().colors().border)
4565 .bg(cx.theme().colors().editor_background)
4566 .child(div().w_full().child(editor))
4567 .child(
4568 h_flex()
4569 .child(
4570 IconButton::new("dismiss-feedback-message", IconName::Close)
4571 .icon_color(Color::Error)
4572 .icon_size(IconSize::XSmall)
4573 .shape(ui::IconButtonShape::Square)
4574 .on_click(cx.listener(move |this, _, _window, cx| {
4575 this.thread_feedback.dismiss_comments();
4576 cx.notify();
4577 })),
4578 )
4579 .child(
4580 IconButton::new("submit-feedback-message", IconName::Return)
4581 .icon_size(IconSize::XSmall)
4582 .shape(ui::IconButtonShape::Square)
4583 .on_click(cx.listener(move |this, _, _window, cx| {
4584 this.submit_feedback_message(cx);
4585 })),
4586 ),
4587 )
4588 }
4589
4590 fn handle_feedback_click(
4591 &mut self,
4592 feedback: ThreadFeedback,
4593 window: &mut Window,
4594 cx: &mut Context<Self>,
4595 ) {
4596 let Some(thread) = self.thread().cloned() else {
4597 return;
4598 };
4599
4600 self.thread_feedback.submit(thread, feedback, window, cx);
4601 cx.notify();
4602 }
4603
4604 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4605 let Some(thread) = self.thread().cloned() else {
4606 return;
4607 };
4608
4609 self.thread_feedback.submit_comments(thread, cx);
4610 cx.notify();
4611 }
4612
4613 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4614 div()
4615 .id("acp-thread-scrollbar")
4616 .occlude()
4617 .on_mouse_move(cx.listener(|_, _, _, cx| {
4618 cx.notify();
4619 cx.stop_propagation()
4620 }))
4621 .on_hover(|_, _, cx| {
4622 cx.stop_propagation();
4623 })
4624 .on_any_mouse_down(|_, _, cx| {
4625 cx.stop_propagation();
4626 })
4627 .on_mouse_up(
4628 MouseButton::Left,
4629 cx.listener(|_, _, _, cx| {
4630 cx.stop_propagation();
4631 }),
4632 )
4633 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4634 cx.notify();
4635 }))
4636 .h_full()
4637 .absolute()
4638 .right_1()
4639 .top_1()
4640 .bottom_0()
4641 .w(px(12.))
4642 .cursor_default()
4643 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4644 }
4645
4646 fn render_token_limit_callout(
4647 &self,
4648 line_height: Pixels,
4649 cx: &mut Context<Self>,
4650 ) -> Option<Callout> {
4651 let token_usage = self.thread()?.read(cx).token_usage()?;
4652 let ratio = token_usage.ratio();
4653
4654 let (severity, title) = match ratio {
4655 acp_thread::TokenUsageRatio::Normal => return None,
4656 acp_thread::TokenUsageRatio::Warning => {
4657 (Severity::Warning, "Thread reaching the token limit soon")
4658 }
4659 acp_thread::TokenUsageRatio::Exceeded => {
4660 (Severity::Error, "Thread reached the token limit")
4661 }
4662 };
4663
4664 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4665 thread.read(cx).completion_mode() == CompletionMode::Normal
4666 && thread
4667 .read(cx)
4668 .model()
4669 .is_some_and(|model| model.supports_burn_mode())
4670 });
4671
4672 let description = if burn_mode_available {
4673 "To continue, start a new thread from a summary or turn Burn Mode on."
4674 } else {
4675 "To continue, start a new thread from a summary."
4676 };
4677
4678 Some(
4679 Callout::new()
4680 .severity(severity)
4681 .line_height(line_height)
4682 .title(title)
4683 .description(description)
4684 .actions_slot(
4685 h_flex()
4686 .gap_0p5()
4687 .child(
4688 Button::new("start-new-thread", "Start New Thread")
4689 .label_size(LabelSize::Small)
4690 .on_click(cx.listener(|this, _, window, cx| {
4691 let Some(thread) = this.thread() else {
4692 return;
4693 };
4694 let session_id = thread.read(cx).session_id().clone();
4695 window.dispatch_action(
4696 crate::NewNativeAgentThreadFromSummary {
4697 from_session_id: session_id,
4698 }
4699 .boxed_clone(),
4700 cx,
4701 );
4702 })),
4703 )
4704 .when(burn_mode_available, |this| {
4705 this.child(
4706 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4707 .icon_size(IconSize::XSmall)
4708 .on_click(cx.listener(|this, _event, window, cx| {
4709 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4710 })),
4711 )
4712 }),
4713 ),
4714 )
4715 }
4716
4717 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4718 if !self.is_using_zed_ai_models(cx) {
4719 return None;
4720 }
4721
4722 let user_store = self.project.read(cx).user_store().read(cx);
4723 if user_store.is_usage_based_billing_enabled() {
4724 return None;
4725 }
4726
4727 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4728
4729 let usage = user_store.model_request_usage()?;
4730
4731 Some(
4732 div()
4733 .child(UsageCallout::new(plan, usage))
4734 .line_height(line_height),
4735 )
4736 }
4737
4738 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4739 self.entry_view_state.update(cx, |entry_view_state, cx| {
4740 entry_view_state.settings_changed(cx);
4741 });
4742 }
4743
4744 pub(crate) fn insert_dragged_files(
4745 &self,
4746 paths: Vec<project::ProjectPath>,
4747 added_worktrees: Vec<Entity<project::Worktree>>,
4748 window: &mut Window,
4749 cx: &mut Context<Self>,
4750 ) {
4751 self.message_editor.update(cx, |message_editor, cx| {
4752 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4753 })
4754 }
4755
4756 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4757 self.message_editor.update(cx, |message_editor, cx| {
4758 message_editor.insert_selections(window, cx);
4759 })
4760 }
4761
4762 fn render_thread_retry_status_callout(
4763 &self,
4764 _window: &mut Window,
4765 _cx: &mut Context<Self>,
4766 ) -> Option<Callout> {
4767 let state = self.thread_retry_status.as_ref()?;
4768
4769 let next_attempt_in = state
4770 .duration
4771 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4772 if next_attempt_in.is_zero() {
4773 return None;
4774 }
4775
4776 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4777
4778 let retry_message = if state.max_attempts == 1 {
4779 if next_attempt_in_secs == 1 {
4780 "Retrying. Next attempt in 1 second.".to_string()
4781 } else {
4782 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4783 }
4784 } else if next_attempt_in_secs == 1 {
4785 format!(
4786 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4787 state.attempt, state.max_attempts,
4788 )
4789 } else {
4790 format!(
4791 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4792 state.attempt, state.max_attempts,
4793 )
4794 };
4795
4796 Some(
4797 Callout::new()
4798 .severity(Severity::Warning)
4799 .title(state.last_error.clone())
4800 .description(retry_message),
4801 )
4802 }
4803
4804 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4805 let content = match self.thread_error.as_ref()? {
4806 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4807 ThreadError::Refusal => self.render_refusal_error(cx),
4808 ThreadError::AuthenticationRequired(error) => {
4809 self.render_authentication_required_error(error.clone(), cx)
4810 }
4811 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4812 ThreadError::ModelRequestLimitReached(plan) => {
4813 self.render_model_request_limit_reached_error(*plan, cx)
4814 }
4815 ThreadError::ToolUseLimitReached => {
4816 self.render_tool_use_limit_reached_error(window, cx)?
4817 }
4818 };
4819
4820 Some(div().child(content))
4821 }
4822
4823 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
4824 v_flex().w_full().justify_end().child(
4825 h_flex()
4826 .p_2()
4827 .pr_3()
4828 .w_full()
4829 .gap_1p5()
4830 .border_t_1()
4831 .border_color(cx.theme().colors().border)
4832 .bg(cx.theme().colors().element_background)
4833 .child(
4834 h_flex()
4835 .flex_1()
4836 .gap_1p5()
4837 .child(
4838 Icon::new(IconName::Download)
4839 .color(Color::Accent)
4840 .size(IconSize::Small),
4841 )
4842 .child(Label::new("New version available").size(LabelSize::Small)),
4843 )
4844 .child(
4845 Button::new("update-button", format!("Update to v{}", version))
4846 .label_size(LabelSize::Small)
4847 .style(ButtonStyle::Tinted(TintColor::Accent))
4848 .on_click(cx.listener(|this, _, window, cx| {
4849 this.reset(window, cx);
4850 })),
4851 ),
4852 )
4853 }
4854
4855 fn get_current_model_name(&self, cx: &App) -> SharedString {
4856 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
4857 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
4858 // This provides better clarity about what refused the request
4859 if self
4860 .agent
4861 .clone()
4862 .downcast::<agent2::NativeAgentServer>()
4863 .is_some()
4864 {
4865 // Native agent - use the model name
4866 self.model_selector
4867 .as_ref()
4868 .and_then(|selector| selector.read(cx).active_model_name(cx))
4869 .unwrap_or_else(|| SharedString::from("The model"))
4870 } else {
4871 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
4872 self.agent.name()
4873 }
4874 }
4875
4876 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
4877 let model_or_agent_name = self.get_current_model_name(cx);
4878 let refusal_message = format!(
4879 "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
4880 model_or_agent_name
4881 );
4882
4883 Callout::new()
4884 .severity(Severity::Error)
4885 .title("Request Refused")
4886 .icon(IconName::XCircle)
4887 .description(refusal_message.clone())
4888 .actions_slot(self.create_copy_button(&refusal_message))
4889 .dismiss_action(self.dismiss_error_button(cx))
4890 }
4891
4892 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4893 let can_resume = self
4894 .thread()
4895 .map_or(false, |thread| thread.read(cx).can_resume(cx));
4896
4897 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4898 let thread = thread.read(cx);
4899 let supports_burn_mode = thread
4900 .model()
4901 .map_or(false, |model| model.supports_burn_mode());
4902 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4903 });
4904
4905 Callout::new()
4906 .severity(Severity::Error)
4907 .title("Error")
4908 .icon(IconName::XCircle)
4909 .description(error.clone())
4910 .actions_slot(
4911 h_flex()
4912 .gap_0p5()
4913 .when(can_resume && can_enable_burn_mode, |this| {
4914 this.child(
4915 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4916 .icon(IconName::ZedBurnMode)
4917 .icon_position(IconPosition::Start)
4918 .icon_size(IconSize::Small)
4919 .label_size(LabelSize::Small)
4920 .on_click(cx.listener(|this, _, window, cx| {
4921 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4922 this.resume_chat(cx);
4923 })),
4924 )
4925 })
4926 .when(can_resume, |this| {
4927 this.child(
4928 Button::new("retry", "Retry")
4929 .icon(IconName::RotateCw)
4930 .icon_position(IconPosition::Start)
4931 .icon_size(IconSize::Small)
4932 .label_size(LabelSize::Small)
4933 .on_click(cx.listener(|this, _, _window, cx| {
4934 this.resume_chat(cx);
4935 })),
4936 )
4937 })
4938 .child(self.create_copy_button(error.to_string())),
4939 )
4940 .dismiss_action(self.dismiss_error_button(cx))
4941 }
4942
4943 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4944 const ERROR_MESSAGE: &str =
4945 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4946
4947 Callout::new()
4948 .severity(Severity::Error)
4949 .icon(IconName::XCircle)
4950 .title("Free Usage Exceeded")
4951 .description(ERROR_MESSAGE)
4952 .actions_slot(
4953 h_flex()
4954 .gap_0p5()
4955 .child(self.upgrade_button(cx))
4956 .child(self.create_copy_button(ERROR_MESSAGE)),
4957 )
4958 .dismiss_action(self.dismiss_error_button(cx))
4959 }
4960
4961 fn render_authentication_required_error(
4962 &self,
4963 error: SharedString,
4964 cx: &mut Context<Self>,
4965 ) -> Callout {
4966 Callout::new()
4967 .severity(Severity::Error)
4968 .title("Authentication Required")
4969 .icon(IconName::XCircle)
4970 .description(error.clone())
4971 .actions_slot(
4972 h_flex()
4973 .gap_0p5()
4974 .child(self.authenticate_button(cx))
4975 .child(self.create_copy_button(error)),
4976 )
4977 .dismiss_action(self.dismiss_error_button(cx))
4978 }
4979
4980 fn render_model_request_limit_reached_error(
4981 &self,
4982 plan: cloud_llm_client::Plan,
4983 cx: &mut Context<Self>,
4984 ) -> Callout {
4985 let error_message = match plan {
4986 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4987 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4988 "Upgrade to Zed Pro for more prompts."
4989 }
4990 };
4991
4992 Callout::new()
4993 .severity(Severity::Error)
4994 .title("Model Prompt Limit Reached")
4995 .icon(IconName::XCircle)
4996 .description(error_message)
4997 .actions_slot(
4998 h_flex()
4999 .gap_0p5()
5000 .child(self.upgrade_button(cx))
5001 .child(self.create_copy_button(error_message)),
5002 )
5003 .dismiss_action(self.dismiss_error_button(cx))
5004 }
5005
5006 fn render_tool_use_limit_reached_error(
5007 &self,
5008 window: &mut Window,
5009 cx: &mut Context<Self>,
5010 ) -> Option<Callout> {
5011 let thread = self.as_native_thread(cx)?;
5012 let supports_burn_mode = thread
5013 .read(cx)
5014 .model()
5015 .is_some_and(|model| model.supports_burn_mode());
5016
5017 let focus_handle = self.focus_handle(cx);
5018
5019 Some(
5020 Callout::new()
5021 .icon(IconName::Info)
5022 .title("Consecutive tool use limit reached.")
5023 .actions_slot(
5024 h_flex()
5025 .gap_0p5()
5026 .when(supports_burn_mode, |this| {
5027 this.child(
5028 Button::new("continue-burn-mode", "Continue with Burn Mode")
5029 .style(ButtonStyle::Filled)
5030 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5031 .layer(ElevationIndex::ModalSurface)
5032 .label_size(LabelSize::Small)
5033 .key_binding(
5034 KeyBinding::for_action_in(
5035 &ContinueWithBurnMode,
5036 &focus_handle,
5037 window,
5038 cx,
5039 )
5040 .map(|kb| kb.size(rems_from_px(10.))),
5041 )
5042 .tooltip(Tooltip::text(
5043 "Enable Burn Mode for unlimited tool use.",
5044 ))
5045 .on_click({
5046 cx.listener(move |this, _, _window, cx| {
5047 thread.update(cx, |thread, cx| {
5048 thread
5049 .set_completion_mode(CompletionMode::Burn, cx);
5050 });
5051 this.resume_chat(cx);
5052 })
5053 }),
5054 )
5055 })
5056 .child(
5057 Button::new("continue-conversation", "Continue")
5058 .layer(ElevationIndex::ModalSurface)
5059 .label_size(LabelSize::Small)
5060 .key_binding(
5061 KeyBinding::for_action_in(
5062 &ContinueThread,
5063 &focus_handle,
5064 window,
5065 cx,
5066 )
5067 .map(|kb| kb.size(rems_from_px(10.))),
5068 )
5069 .on_click(cx.listener(|this, _, _window, cx| {
5070 this.resume_chat(cx);
5071 })),
5072 ),
5073 ),
5074 )
5075 }
5076
5077 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5078 let message = message.into();
5079
5080 IconButton::new("copy", IconName::Copy)
5081 .icon_size(IconSize::Small)
5082 .icon_color(Color::Muted)
5083 .tooltip(Tooltip::text("Copy Error Message"))
5084 .on_click(move |_, _, cx| {
5085 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5086 })
5087 }
5088
5089 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5090 IconButton::new("dismiss", IconName::Close)
5091 .icon_size(IconSize::Small)
5092 .icon_color(Color::Muted)
5093 .tooltip(Tooltip::text("Dismiss Error"))
5094 .on_click(cx.listener({
5095 move |this, _, _, cx| {
5096 this.clear_thread_error(cx);
5097 cx.notify();
5098 }
5099 }))
5100 }
5101
5102 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5103 Button::new("authenticate", "Authenticate")
5104 .label_size(LabelSize::Small)
5105 .style(ButtonStyle::Filled)
5106 .on_click(cx.listener({
5107 move |this, _, window, cx| {
5108 let agent = this.agent.clone();
5109 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5110 return;
5111 };
5112
5113 let connection = thread.read(cx).connection().clone();
5114 let err = AuthRequired {
5115 description: None,
5116 provider_id: None,
5117 };
5118 this.clear_thread_error(cx);
5119 let this = cx.weak_entity();
5120 window.defer(cx, |window, cx| {
5121 Self::handle_auth_required(this, err, agent, connection, window, cx);
5122 })
5123 }
5124 }))
5125 }
5126
5127 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5128 let agent = self.agent.clone();
5129 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5130 return;
5131 };
5132
5133 let connection = thread.read(cx).connection().clone();
5134 let err = AuthRequired {
5135 description: None,
5136 provider_id: None,
5137 };
5138 self.clear_thread_error(cx);
5139 let this = cx.weak_entity();
5140 window.defer(cx, |window, cx| {
5141 Self::handle_auth_required(this, err, agent, connection, window, cx);
5142 })
5143 }
5144
5145 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5146 Button::new("upgrade", "Upgrade")
5147 .label_size(LabelSize::Small)
5148 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5149 .on_click(cx.listener({
5150 move |this, _, _, cx| {
5151 this.clear_thread_error(cx);
5152 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5153 }
5154 }))
5155 }
5156
5157 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5158 let task = match entry {
5159 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5160 history.delete_thread(thread.id.clone(), cx)
5161 }),
5162 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
5163 history.delete_text_thread(context.path.clone(), cx)
5164 }),
5165 };
5166 task.detach_and_log_err(cx);
5167 }
5168}
5169
5170fn loading_contents_spinner(size: IconSize) -> AnyElement {
5171 Icon::new(IconName::LoadCircle)
5172 .size(size)
5173 .color(Color::Accent)
5174 .with_rotate_animation(3)
5175 .into_any_element()
5176}
5177
5178impl Focusable for AcpThreadView {
5179 fn focus_handle(&self, cx: &App) -> FocusHandle {
5180 match self.thread_state {
5181 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5182 self.message_editor.focus_handle(cx)
5183 }
5184 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5185 self.focus_handle.clone()
5186 }
5187 }
5188 }
5189}
5190
5191impl Render for AcpThreadView {
5192 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5193 let has_messages = self.list_state.item_count() > 0;
5194 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5195
5196 v_flex()
5197 .size_full()
5198 .key_context("AcpThread")
5199 .on_action(cx.listener(Self::open_agent_diff))
5200 .on_action(cx.listener(Self::toggle_burn_mode))
5201 .on_action(cx.listener(Self::keep_all))
5202 .on_action(cx.listener(Self::reject_all))
5203 .track_focus(&self.focus_handle)
5204 .bg(cx.theme().colors().panel_background)
5205 .child(match &self.thread_state {
5206 ThreadState::Unauthenticated {
5207 connection,
5208 description,
5209 configuration_view,
5210 pending_auth_method,
5211 ..
5212 } => self.render_auth_required_state(
5213 connection,
5214 description.as_ref(),
5215 configuration_view.as_ref(),
5216 pending_auth_method.as_ref(),
5217 window,
5218 cx,
5219 ),
5220 ThreadState::Loading { .. } => v_flex()
5221 .flex_1()
5222 .child(self.render_recent_history(window, cx)),
5223 ThreadState::LoadError(e) => v_flex()
5224 .flex_1()
5225 .size_full()
5226 .items_center()
5227 .justify_end()
5228 .child(self.render_load_error(e, window, cx)),
5229 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5230 if has_messages {
5231 this.child(
5232 list(
5233 self.list_state.clone(),
5234 cx.processor(|this, index: usize, window, cx| {
5235 let Some((entry, len)) = this.thread().and_then(|thread| {
5236 let entries = &thread.read(cx).entries();
5237 Some((entries.get(index)?, entries.len()))
5238 }) else {
5239 return Empty.into_any();
5240 };
5241 this.render_entry(index, len, entry, window, cx)
5242 }),
5243 )
5244 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5245 .flex_grow()
5246 .into_any(),
5247 )
5248 .child(self.render_vertical_scrollbar(cx))
5249 } else {
5250 this.child(self.render_recent_history(window, cx))
5251 }
5252 }),
5253 })
5254 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5255 // above so that the scrollbar doesn't render behind it. The current setup allows
5256 // the scrollbar to stop exactly at the activity bar start.
5257 .when(has_messages, |this| match &self.thread_state {
5258 ThreadState::Ready { thread, .. } => {
5259 this.children(self.render_activity_bar(thread, window, cx))
5260 }
5261 _ => this,
5262 })
5263 .children(self.render_thread_retry_status_callout(window, cx))
5264 .children(self.render_thread_error(window, cx))
5265 .when_some(
5266 self.new_server_version_available.as_ref().filter(|_| {
5267 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5268 }),
5269 |this, version| this.child(self.render_new_version_callout(&version, cx)),
5270 )
5271 .children(
5272 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5273 Some(usage_callout.into_any_element())
5274 } else {
5275 self.render_token_limit_callout(line_height, cx)
5276 .map(|token_limit_callout| token_limit_callout.into_any_element())
5277 },
5278 )
5279 .child(self.render_message_editor(window, cx))
5280 }
5281}
5282
5283fn default_markdown_style(
5284 buffer_font: bool,
5285 muted_text: bool,
5286 window: &Window,
5287 cx: &App,
5288) -> MarkdownStyle {
5289 let theme_settings = ThemeSettings::get_global(cx);
5290 let colors = cx.theme().colors();
5291
5292 let buffer_font_size = TextSize::Small.rems(cx);
5293
5294 let mut text_style = window.text_style();
5295 let line_height = buffer_font_size * 1.75;
5296
5297 let font_family = if buffer_font {
5298 theme_settings.buffer_font.family.clone()
5299 } else {
5300 theme_settings.ui_font.family.clone()
5301 };
5302
5303 let font_size = if buffer_font {
5304 TextSize::Small.rems(cx)
5305 } else {
5306 TextSize::Default.rems(cx)
5307 };
5308
5309 let text_color = if muted_text {
5310 colors.text_muted
5311 } else {
5312 colors.text
5313 };
5314
5315 text_style.refine(&TextStyleRefinement {
5316 font_family: Some(font_family),
5317 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5318 font_features: Some(theme_settings.ui_font.features.clone()),
5319 font_size: Some(font_size.into()),
5320 line_height: Some(line_height.into()),
5321 color: Some(text_color),
5322 ..Default::default()
5323 });
5324
5325 MarkdownStyle {
5326 base_text_style: text_style.clone(),
5327 syntax: cx.theme().syntax().clone(),
5328 selection_background_color: colors.element_selection_background,
5329 code_block_overflow_x_scroll: true,
5330 table_overflow_x_scroll: true,
5331 heading_level_styles: Some(HeadingLevelStyles {
5332 h1: Some(TextStyleRefinement {
5333 font_size: Some(rems(1.15).into()),
5334 ..Default::default()
5335 }),
5336 h2: Some(TextStyleRefinement {
5337 font_size: Some(rems(1.1).into()),
5338 ..Default::default()
5339 }),
5340 h3: Some(TextStyleRefinement {
5341 font_size: Some(rems(1.05).into()),
5342 ..Default::default()
5343 }),
5344 h4: Some(TextStyleRefinement {
5345 font_size: Some(rems(1.).into()),
5346 ..Default::default()
5347 }),
5348 h5: Some(TextStyleRefinement {
5349 font_size: Some(rems(0.95).into()),
5350 ..Default::default()
5351 }),
5352 h6: Some(TextStyleRefinement {
5353 font_size: Some(rems(0.875).into()),
5354 ..Default::default()
5355 }),
5356 }),
5357 code_block: StyleRefinement {
5358 padding: EdgesRefinement {
5359 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5360 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5361 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5362 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5363 },
5364 margin: EdgesRefinement {
5365 top: Some(Length::Definite(Pixels(8.).into())),
5366 left: Some(Length::Definite(Pixels(0.).into())),
5367 right: Some(Length::Definite(Pixels(0.).into())),
5368 bottom: Some(Length::Definite(Pixels(12.).into())),
5369 },
5370 border_style: Some(BorderStyle::Solid),
5371 border_widths: EdgesRefinement {
5372 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5373 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5374 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5375 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5376 },
5377 border_color: Some(colors.border_variant),
5378 background: Some(colors.editor_background.into()),
5379 text: Some(TextStyleRefinement {
5380 font_family: Some(theme_settings.buffer_font.family.clone()),
5381 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5382 font_features: Some(theme_settings.buffer_font.features.clone()),
5383 font_size: Some(buffer_font_size.into()),
5384 ..Default::default()
5385 }),
5386 ..Default::default()
5387 },
5388 inline_code: TextStyleRefinement {
5389 font_family: Some(theme_settings.buffer_font.family.clone()),
5390 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5391 font_features: Some(theme_settings.buffer_font.features.clone()),
5392 font_size: Some(buffer_font_size.into()),
5393 background_color: Some(colors.editor_foreground.opacity(0.08)),
5394 ..Default::default()
5395 },
5396 link: TextStyleRefinement {
5397 background_color: Some(colors.editor_foreground.opacity(0.025)),
5398 underline: Some(UnderlineStyle {
5399 color: Some(colors.text_accent.opacity(0.5)),
5400 thickness: px(1.),
5401 ..Default::default()
5402 }),
5403 ..Default::default()
5404 },
5405 ..Default::default()
5406 }
5407}
5408
5409fn plan_label_markdown_style(
5410 status: &acp::PlanEntryStatus,
5411 window: &Window,
5412 cx: &App,
5413) -> MarkdownStyle {
5414 let default_md_style = default_markdown_style(false, false, window, cx);
5415
5416 MarkdownStyle {
5417 base_text_style: TextStyle {
5418 color: cx.theme().colors().text_muted,
5419 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5420 Some(gpui::StrikethroughStyle {
5421 thickness: px(1.),
5422 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5423 })
5424 } else {
5425 None
5426 },
5427 ..default_md_style.base_text_style
5428 },
5429 ..default_md_style
5430 }
5431}
5432
5433fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5434 let default_md_style = default_markdown_style(true, false, window, cx);
5435
5436 MarkdownStyle {
5437 base_text_style: TextStyle {
5438 ..default_md_style.base_text_style
5439 },
5440 selection_background_color: cx.theme().colors().element_selection_background,
5441 ..Default::default()
5442 }
5443}
5444
5445#[cfg(test)]
5446pub(crate) mod tests {
5447 use acp_thread::StubAgentConnection;
5448 use agent_client_protocol::SessionId;
5449 use assistant_context::ContextStore;
5450 use editor::EditorSettings;
5451 use fs::FakeFs;
5452 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5453 use project::Project;
5454 use serde_json::json;
5455 use settings::SettingsStore;
5456 use std::any::Any;
5457 use std::path::Path;
5458 use workspace::Item;
5459
5460 use super::*;
5461
5462 #[gpui::test]
5463 async fn test_drop(cx: &mut TestAppContext) {
5464 init_test(cx);
5465
5466 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5467 let weak_view = thread_view.downgrade();
5468 drop(thread_view);
5469 assert!(!weak_view.is_upgradable());
5470 }
5471
5472 #[gpui::test]
5473 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5474 init_test(cx);
5475
5476 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5477
5478 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5479 message_editor.update_in(cx, |editor, window, cx| {
5480 editor.set_text("Hello", window, cx);
5481 });
5482
5483 cx.deactivate_window();
5484
5485 thread_view.update_in(cx, |thread_view, window, cx| {
5486 thread_view.send(window, cx);
5487 });
5488
5489 cx.run_until_parked();
5490
5491 assert!(
5492 cx.windows()
5493 .iter()
5494 .any(|window| window.downcast::<AgentNotification>().is_some())
5495 );
5496 }
5497
5498 #[gpui::test]
5499 async fn test_notification_for_error(cx: &mut TestAppContext) {
5500 init_test(cx);
5501
5502 let (thread_view, cx) =
5503 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5504
5505 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5506 message_editor.update_in(cx, |editor, window, cx| {
5507 editor.set_text("Hello", window, cx);
5508 });
5509
5510 cx.deactivate_window();
5511
5512 thread_view.update_in(cx, |thread_view, window, cx| {
5513 thread_view.send(window, cx);
5514 });
5515
5516 cx.run_until_parked();
5517
5518 assert!(
5519 cx.windows()
5520 .iter()
5521 .any(|window| window.downcast::<AgentNotification>().is_some())
5522 );
5523 }
5524
5525 #[gpui::test]
5526 async fn test_refusal_handling(cx: &mut TestAppContext) {
5527 init_test(cx);
5528
5529 let (thread_view, cx) =
5530 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
5531
5532 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5533 message_editor.update_in(cx, |editor, window, cx| {
5534 editor.set_text("Do something harmful", window, cx);
5535 });
5536
5537 thread_view.update_in(cx, |thread_view, window, cx| {
5538 thread_view.send(window, cx);
5539 });
5540
5541 cx.run_until_parked();
5542
5543 // Check that the refusal error is set
5544 thread_view.read_with(cx, |thread_view, _cx| {
5545 assert!(
5546 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
5547 "Expected refusal error to be set"
5548 );
5549 });
5550 }
5551
5552 #[gpui::test]
5553 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5554 init_test(cx);
5555
5556 let tool_call_id = acp::ToolCallId("1".into());
5557 let tool_call = acp::ToolCall {
5558 id: tool_call_id.clone(),
5559 title: "Label".into(),
5560 kind: acp::ToolKind::Edit,
5561 status: acp::ToolCallStatus::Pending,
5562 content: vec!["hi".into()],
5563 locations: vec![],
5564 raw_input: None,
5565 raw_output: None,
5566 };
5567 let connection =
5568 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5569 tool_call_id,
5570 vec![acp::PermissionOption {
5571 id: acp::PermissionOptionId("1".into()),
5572 name: "Allow".into(),
5573 kind: acp::PermissionOptionKind::AllowOnce,
5574 }],
5575 )]));
5576
5577 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5578
5579 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5580
5581 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5582 message_editor.update_in(cx, |editor, window, cx| {
5583 editor.set_text("Hello", window, cx);
5584 });
5585
5586 cx.deactivate_window();
5587
5588 thread_view.update_in(cx, |thread_view, window, cx| {
5589 thread_view.send(window, cx);
5590 });
5591
5592 cx.run_until_parked();
5593
5594 assert!(
5595 cx.windows()
5596 .iter()
5597 .any(|window| window.downcast::<AgentNotification>().is_some())
5598 );
5599 }
5600
5601 async fn setup_thread_view(
5602 agent: impl AgentServer + 'static,
5603 cx: &mut TestAppContext,
5604 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5605 let fs = FakeFs::new(cx.executor());
5606 let project = Project::test(fs, [], cx).await;
5607 let (workspace, cx) =
5608 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5609
5610 let context_store =
5611 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5612 let history_store =
5613 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5614
5615 let thread_view = cx.update(|window, cx| {
5616 cx.new(|cx| {
5617 AcpThreadView::new(
5618 Rc::new(agent),
5619 None,
5620 None,
5621 workspace.downgrade(),
5622 project,
5623 history_store,
5624 None,
5625 window,
5626 cx,
5627 )
5628 })
5629 });
5630 cx.run_until_parked();
5631 (thread_view, cx)
5632 }
5633
5634 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5635 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5636
5637 workspace
5638 .update_in(cx, |workspace, window, cx| {
5639 workspace.add_item_to_active_pane(
5640 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5641 None,
5642 true,
5643 window,
5644 cx,
5645 );
5646 })
5647 .unwrap();
5648 }
5649
5650 struct ThreadViewItem(Entity<AcpThreadView>);
5651
5652 impl Item for ThreadViewItem {
5653 type Event = ();
5654
5655 fn include_in_nav_history() -> bool {
5656 false
5657 }
5658
5659 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5660 "Test".into()
5661 }
5662 }
5663
5664 impl EventEmitter<()> for ThreadViewItem {}
5665
5666 impl Focusable for ThreadViewItem {
5667 fn focus_handle(&self, cx: &App) -> FocusHandle {
5668 self.0.read(cx).focus_handle(cx)
5669 }
5670 }
5671
5672 impl Render for ThreadViewItem {
5673 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5674 self.0.clone().into_any_element()
5675 }
5676 }
5677
5678 struct StubAgentServer<C> {
5679 connection: C,
5680 }
5681
5682 impl<C> StubAgentServer<C> {
5683 fn new(connection: C) -> Self {
5684 Self { connection }
5685 }
5686 }
5687
5688 impl StubAgentServer<StubAgentConnection> {
5689 fn default_response() -> Self {
5690 let conn = StubAgentConnection::new();
5691 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5692 content: "Default response".into(),
5693 }]);
5694 Self::new(conn)
5695 }
5696 }
5697
5698 impl<C> AgentServer for StubAgentServer<C>
5699 where
5700 C: 'static + AgentConnection + Send + Clone,
5701 {
5702 fn telemetry_id(&self) -> &'static str {
5703 "test"
5704 }
5705
5706 fn logo(&self) -> ui::IconName {
5707 ui::IconName::Ai
5708 }
5709
5710 fn name(&self) -> SharedString {
5711 "Test".into()
5712 }
5713
5714 fn connect(
5715 &self,
5716 _root_dir: &Path,
5717 _delegate: AgentServerDelegate,
5718 _cx: &mut App,
5719 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5720 Task::ready(Ok(Rc::new(self.connection.clone())))
5721 }
5722
5723 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5724 self
5725 }
5726 }
5727
5728 #[derive(Clone)]
5729 struct SaboteurAgentConnection;
5730
5731 impl AgentConnection for SaboteurAgentConnection {
5732 fn new_thread(
5733 self: Rc<Self>,
5734 project: Entity<Project>,
5735 _cwd: &Path,
5736 cx: &mut gpui::App,
5737 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5738 Task::ready(Ok(cx.new(|cx| {
5739 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5740 AcpThread::new(
5741 "SaboteurAgentConnection",
5742 self,
5743 project,
5744 action_log,
5745 SessionId("test".into()),
5746 watch::Receiver::constant(acp::PromptCapabilities {
5747 image: true,
5748 audio: true,
5749 embedded_context: true,
5750 }),
5751 cx,
5752 )
5753 })))
5754 }
5755
5756 fn auth_methods(&self) -> &[acp::AuthMethod] {
5757 &[]
5758 }
5759
5760 fn authenticate(
5761 &self,
5762 _method_id: acp::AuthMethodId,
5763 _cx: &mut App,
5764 ) -> Task<gpui::Result<()>> {
5765 unimplemented!()
5766 }
5767
5768 fn prompt(
5769 &self,
5770 _id: Option<acp_thread::UserMessageId>,
5771 _params: acp::PromptRequest,
5772 _cx: &mut App,
5773 ) -> Task<gpui::Result<acp::PromptResponse>> {
5774 Task::ready(Err(anyhow::anyhow!("Error prompting")))
5775 }
5776
5777 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5778 unimplemented!()
5779 }
5780
5781 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5782 self
5783 }
5784 }
5785
5786 /// Simulates a model which always returns a refusal response
5787 #[derive(Clone)]
5788 struct RefusalAgentConnection;
5789
5790 impl AgentConnection for RefusalAgentConnection {
5791 fn new_thread(
5792 self: Rc<Self>,
5793 project: Entity<Project>,
5794 _cwd: &Path,
5795 cx: &mut gpui::App,
5796 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5797 Task::ready(Ok(cx.new(|cx| {
5798 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5799 AcpThread::new(
5800 "RefusalAgentConnection",
5801 self,
5802 project,
5803 action_log,
5804 SessionId("test".into()),
5805 watch::Receiver::constant(acp::PromptCapabilities {
5806 image: true,
5807 audio: true,
5808 embedded_context: true,
5809 }),
5810 cx,
5811 )
5812 })))
5813 }
5814
5815 fn auth_methods(&self) -> &[acp::AuthMethod] {
5816 &[]
5817 }
5818
5819 fn authenticate(
5820 &self,
5821 _method_id: acp::AuthMethodId,
5822 _cx: &mut App,
5823 ) -> Task<gpui::Result<()>> {
5824 unimplemented!()
5825 }
5826
5827 fn prompt(
5828 &self,
5829 _id: Option<acp_thread::UserMessageId>,
5830 _params: acp::PromptRequest,
5831 _cx: &mut App,
5832 ) -> Task<gpui::Result<acp::PromptResponse>> {
5833 Task::ready(Ok(acp::PromptResponse {
5834 stop_reason: acp::StopReason::Refusal,
5835 }))
5836 }
5837
5838 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5839 unimplemented!()
5840 }
5841
5842 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5843 self
5844 }
5845 }
5846
5847 pub(crate) fn init_test(cx: &mut TestAppContext) {
5848 cx.update(|cx| {
5849 let settings_store = SettingsStore::test(cx);
5850 cx.set_global(settings_store);
5851 language::init(cx);
5852 Project::init_settings(cx);
5853 AgentSettings::register(cx);
5854 workspace::init_settings(cx);
5855 ThemeSettings::register(cx);
5856 release_channel::init(SemanticVersion::default(), cx);
5857 EditorSettings::register(cx);
5858 prompt_store::init(cx)
5859 });
5860 }
5861
5862 #[gpui::test]
5863 async fn test_rewind_views(cx: &mut TestAppContext) {
5864 init_test(cx);
5865
5866 let fs = FakeFs::new(cx.executor());
5867 fs.insert_tree(
5868 "/project",
5869 json!({
5870 "test1.txt": "old content 1",
5871 "test2.txt": "old content 2"
5872 }),
5873 )
5874 .await;
5875 let project = Project::test(fs, [Path::new("/project")], cx).await;
5876 let (workspace, cx) =
5877 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5878
5879 let context_store =
5880 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5881 let history_store =
5882 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5883
5884 let connection = Rc::new(StubAgentConnection::new());
5885 let thread_view = cx.update(|window, cx| {
5886 cx.new(|cx| {
5887 AcpThreadView::new(
5888 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5889 None,
5890 None,
5891 workspace.downgrade(),
5892 project.clone(),
5893 history_store.clone(),
5894 None,
5895 window,
5896 cx,
5897 )
5898 })
5899 });
5900
5901 cx.run_until_parked();
5902
5903 let thread = thread_view
5904 .read_with(cx, |view, _| view.thread().cloned())
5905 .unwrap();
5906
5907 // First user message
5908 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5909 id: acp::ToolCallId("tool1".into()),
5910 title: "Edit file 1".into(),
5911 kind: acp::ToolKind::Edit,
5912 status: acp::ToolCallStatus::Completed,
5913 content: vec![acp::ToolCallContent::Diff {
5914 diff: acp::Diff {
5915 path: "/project/test1.txt".into(),
5916 old_text: Some("old content 1".into()),
5917 new_text: "new content 1".into(),
5918 },
5919 }],
5920 locations: vec![],
5921 raw_input: None,
5922 raw_output: None,
5923 })]);
5924
5925 thread
5926 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5927 .await
5928 .unwrap();
5929 cx.run_until_parked();
5930
5931 thread.read_with(cx, |thread, _| {
5932 assert_eq!(thread.entries().len(), 2);
5933 });
5934
5935 thread_view.read_with(cx, |view, cx| {
5936 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5937 assert!(
5938 entry_view_state
5939 .entry(0)
5940 .unwrap()
5941 .message_editor()
5942 .is_some()
5943 );
5944 assert!(entry_view_state.entry(1).unwrap().has_content());
5945 });
5946 });
5947
5948 // Second user message
5949 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5950 id: acp::ToolCallId("tool2".into()),
5951 title: "Edit file 2".into(),
5952 kind: acp::ToolKind::Edit,
5953 status: acp::ToolCallStatus::Completed,
5954 content: vec![acp::ToolCallContent::Diff {
5955 diff: acp::Diff {
5956 path: "/project/test2.txt".into(),
5957 old_text: Some("old content 2".into()),
5958 new_text: "new content 2".into(),
5959 },
5960 }],
5961 locations: vec![],
5962 raw_input: None,
5963 raw_output: None,
5964 })]);
5965
5966 thread
5967 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5968 .await
5969 .unwrap();
5970 cx.run_until_parked();
5971
5972 let second_user_message_id = thread.read_with(cx, |thread, _| {
5973 assert_eq!(thread.entries().len(), 4);
5974 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5975 panic!();
5976 };
5977 user_message.id.clone().unwrap()
5978 });
5979
5980 thread_view.read_with(cx, |view, cx| {
5981 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5982 assert!(
5983 entry_view_state
5984 .entry(0)
5985 .unwrap()
5986 .message_editor()
5987 .is_some()
5988 );
5989 assert!(entry_view_state.entry(1).unwrap().has_content());
5990 assert!(
5991 entry_view_state
5992 .entry(2)
5993 .unwrap()
5994 .message_editor()
5995 .is_some()
5996 );
5997 assert!(entry_view_state.entry(3).unwrap().has_content());
5998 });
5999 });
6000
6001 // Rewind to first message
6002 thread
6003 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6004 .await
6005 .unwrap();
6006
6007 cx.run_until_parked();
6008
6009 thread.read_with(cx, |thread, _| {
6010 assert_eq!(thread.entries().len(), 2);
6011 });
6012
6013 thread_view.read_with(cx, |view, cx| {
6014 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6015 assert!(
6016 entry_view_state
6017 .entry(0)
6018 .unwrap()
6019 .message_editor()
6020 .is_some()
6021 );
6022 assert!(entry_view_state.entry(1).unwrap().has_content());
6023
6024 // Old views should be dropped
6025 assert!(entry_view_state.entry(2).is_none());
6026 assert!(entry_view_state.entry(3).is_none());
6027 });
6028 });
6029 }
6030
6031 #[gpui::test]
6032 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6033 init_test(cx);
6034
6035 let connection = StubAgentConnection::new();
6036
6037 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6038 content: acp::ContentBlock::Text(acp::TextContent {
6039 text: "Response".into(),
6040 annotations: None,
6041 }),
6042 }]);
6043
6044 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6045 add_to_workspace(thread_view.clone(), cx);
6046
6047 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6048 message_editor.update_in(cx, |editor, window, cx| {
6049 editor.set_text("Original message to edit", window, cx);
6050 });
6051 thread_view.update_in(cx, |thread_view, window, cx| {
6052 thread_view.send(window, cx);
6053 });
6054
6055 cx.run_until_parked();
6056
6057 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6058 assert_eq!(view.editing_message, None);
6059
6060 view.entry_view_state
6061 .read(cx)
6062 .entry(0)
6063 .unwrap()
6064 .message_editor()
6065 .unwrap()
6066 .clone()
6067 });
6068
6069 // Focus
6070 cx.focus(&user_message_editor);
6071 thread_view.read_with(cx, |view, _cx| {
6072 assert_eq!(view.editing_message, Some(0));
6073 });
6074
6075 // Edit
6076 user_message_editor.update_in(cx, |editor, window, cx| {
6077 editor.set_text("Edited message content", window, cx);
6078 });
6079
6080 // Cancel
6081 user_message_editor.update_in(cx, |_editor, window, cx| {
6082 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6083 });
6084
6085 thread_view.read_with(cx, |view, _cx| {
6086 assert_eq!(view.editing_message, None);
6087 });
6088
6089 user_message_editor.read_with(cx, |editor, cx| {
6090 assert_eq!(editor.text(cx), "Original message to edit");
6091 });
6092 }
6093
6094 #[gpui::test]
6095 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6096 init_test(cx);
6097
6098 let connection = StubAgentConnection::new();
6099
6100 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6101 add_to_workspace(thread_view.clone(), cx);
6102
6103 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6104 let mut events = cx.events(&message_editor);
6105 message_editor.update_in(cx, |editor, window, cx| {
6106 editor.set_text("", window, cx);
6107 });
6108
6109 message_editor.update_in(cx, |_editor, window, cx| {
6110 window.dispatch_action(Box::new(Chat), cx);
6111 });
6112 cx.run_until_parked();
6113 // We shouldn't have received any messages
6114 assert!(matches!(
6115 events.try_next(),
6116 Err(futures::channel::mpsc::TryRecvError { .. })
6117 ));
6118 }
6119
6120 #[gpui::test]
6121 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6122 init_test(cx);
6123
6124 let connection = StubAgentConnection::new();
6125
6126 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6127 content: acp::ContentBlock::Text(acp::TextContent {
6128 text: "Response".into(),
6129 annotations: None,
6130 }),
6131 }]);
6132
6133 let (thread_view, cx) =
6134 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6135 add_to_workspace(thread_view.clone(), cx);
6136
6137 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6138 message_editor.update_in(cx, |editor, window, cx| {
6139 editor.set_text("Original message to edit", window, cx);
6140 });
6141 thread_view.update_in(cx, |thread_view, window, cx| {
6142 thread_view.send(window, cx);
6143 });
6144
6145 cx.run_until_parked();
6146
6147 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6148 assert_eq!(view.editing_message, None);
6149 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6150
6151 view.entry_view_state
6152 .read(cx)
6153 .entry(0)
6154 .unwrap()
6155 .message_editor()
6156 .unwrap()
6157 .clone()
6158 });
6159
6160 // Focus
6161 cx.focus(&user_message_editor);
6162
6163 // Edit
6164 user_message_editor.update_in(cx, |editor, window, cx| {
6165 editor.set_text("Edited message content", window, cx);
6166 });
6167
6168 // Send
6169 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6170 content: acp::ContentBlock::Text(acp::TextContent {
6171 text: "New Response".into(),
6172 annotations: None,
6173 }),
6174 }]);
6175
6176 user_message_editor.update_in(cx, |_editor, window, cx| {
6177 window.dispatch_action(Box::new(Chat), cx);
6178 });
6179
6180 cx.run_until_parked();
6181
6182 thread_view.read_with(cx, |view, cx| {
6183 assert_eq!(view.editing_message, None);
6184
6185 let entries = view.thread().unwrap().read(cx).entries();
6186 assert_eq!(entries.len(), 2);
6187 assert_eq!(
6188 entries[0].to_markdown(cx),
6189 "## User\n\nEdited message content\n\n"
6190 );
6191 assert_eq!(
6192 entries[1].to_markdown(cx),
6193 "## Assistant\n\nNew Response\n\n"
6194 );
6195
6196 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6197 assert!(!state.entry(1).unwrap().has_content());
6198 state.entry(0).unwrap().message_editor().unwrap().clone()
6199 });
6200
6201 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6202 })
6203 }
6204
6205 #[gpui::test]
6206 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6207 init_test(cx);
6208
6209 let connection = StubAgentConnection::new();
6210
6211 let (thread_view, cx) =
6212 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6213 add_to_workspace(thread_view.clone(), cx);
6214
6215 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6216 message_editor.update_in(cx, |editor, window, cx| {
6217 editor.set_text("Original message to edit", window, cx);
6218 });
6219 thread_view.update_in(cx, |thread_view, window, cx| {
6220 thread_view.send(window, cx);
6221 });
6222
6223 cx.run_until_parked();
6224
6225 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6226 let thread = view.thread().unwrap().read(cx);
6227 assert_eq!(thread.entries().len(), 1);
6228
6229 let editor = view
6230 .entry_view_state
6231 .read(cx)
6232 .entry(0)
6233 .unwrap()
6234 .message_editor()
6235 .unwrap()
6236 .clone();
6237
6238 (editor, thread.session_id().clone())
6239 });
6240
6241 // Focus
6242 cx.focus(&user_message_editor);
6243
6244 thread_view.read_with(cx, |view, _cx| {
6245 assert_eq!(view.editing_message, Some(0));
6246 });
6247
6248 // Edit
6249 user_message_editor.update_in(cx, |editor, window, cx| {
6250 editor.set_text("Edited message content", window, cx);
6251 });
6252
6253 thread_view.read_with(cx, |view, _cx| {
6254 assert_eq!(view.editing_message, Some(0));
6255 });
6256
6257 // Finish streaming response
6258 cx.update(|_, cx| {
6259 connection.send_update(
6260 session_id.clone(),
6261 acp::SessionUpdate::AgentMessageChunk {
6262 content: acp::ContentBlock::Text(acp::TextContent {
6263 text: "Response".into(),
6264 annotations: None,
6265 }),
6266 },
6267 cx,
6268 );
6269 connection.end_turn(session_id, acp::StopReason::EndTurn);
6270 });
6271
6272 thread_view.read_with(cx, |view, _cx| {
6273 assert_eq!(view.editing_message, Some(0));
6274 });
6275
6276 cx.run_until_parked();
6277
6278 // Should still be editing
6279 cx.update(|window, cx| {
6280 assert!(user_message_editor.focus_handle(cx).is_focused(window));
6281 assert_eq!(thread_view.read(cx).editing_message, Some(0));
6282 assert_eq!(
6283 user_message_editor.read(cx).text(cx),
6284 "Edited message content"
6285 );
6286 });
6287 }
6288
6289 #[gpui::test]
6290 async fn test_interrupt(cx: &mut TestAppContext) {
6291 init_test(cx);
6292
6293 let connection = StubAgentConnection::new();
6294
6295 let (thread_view, cx) =
6296 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6297 add_to_workspace(thread_view.clone(), cx);
6298
6299 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6300 message_editor.update_in(cx, |editor, window, cx| {
6301 editor.set_text("Message 1", window, cx);
6302 });
6303 thread_view.update_in(cx, |thread_view, window, cx| {
6304 thread_view.send(window, cx);
6305 });
6306
6307 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6308 let thread = view.thread().unwrap();
6309
6310 (thread.clone(), thread.read(cx).session_id().clone())
6311 });
6312
6313 cx.run_until_parked();
6314
6315 cx.update(|_, cx| {
6316 connection.send_update(
6317 session_id.clone(),
6318 acp::SessionUpdate::AgentMessageChunk {
6319 content: "Message 1 resp".into(),
6320 },
6321 cx,
6322 );
6323 });
6324
6325 cx.run_until_parked();
6326
6327 thread.read_with(cx, |thread, cx| {
6328 assert_eq!(
6329 thread.to_markdown(cx),
6330 indoc::indoc! {"
6331 ## User
6332
6333 Message 1
6334
6335 ## Assistant
6336
6337 Message 1 resp
6338
6339 "}
6340 )
6341 });
6342
6343 message_editor.update_in(cx, |editor, window, cx| {
6344 editor.set_text("Message 2", window, cx);
6345 });
6346 thread_view.update_in(cx, |thread_view, window, cx| {
6347 thread_view.send(window, cx);
6348 });
6349
6350 cx.update(|_, cx| {
6351 // Simulate a response sent after beginning to cancel
6352 connection.send_update(
6353 session_id.clone(),
6354 acp::SessionUpdate::AgentMessageChunk {
6355 content: "onse".into(),
6356 },
6357 cx,
6358 );
6359 });
6360
6361 cx.run_until_parked();
6362
6363 // Last Message 1 response should appear before Message 2
6364 thread.read_with(cx, |thread, cx| {
6365 assert_eq!(
6366 thread.to_markdown(cx),
6367 indoc::indoc! {"
6368 ## User
6369
6370 Message 1
6371
6372 ## Assistant
6373
6374 Message 1 response
6375
6376 ## User
6377
6378 Message 2
6379
6380 "}
6381 )
6382 });
6383
6384 cx.update(|_, cx| {
6385 connection.send_update(
6386 session_id.clone(),
6387 acp::SessionUpdate::AgentMessageChunk {
6388 content: "Message 2 response".into(),
6389 },
6390 cx,
6391 );
6392 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6393 });
6394
6395 cx.run_until_parked();
6396
6397 thread.read_with(cx, |thread, cx| {
6398 assert_eq!(
6399 thread.to_markdown(cx),
6400 indoc::indoc! {"
6401 ## User
6402
6403 Message 1
6404
6405 ## Assistant
6406
6407 Message 1 response
6408
6409 ## User
6410
6411 Message 2
6412
6413 ## Assistant
6414
6415 Message 2 response
6416
6417 "}
6418 )
6419 });
6420 }
6421}