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