thread_view.rs

   1use acp_thread::{
   2    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
   3    LoadError, MentionUri, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus, UserMessageId,
   4};
   5use acp_thread::{AgentConnection, Plan};
   6use action_log::ActionLog;
   7use agent::{TextThreadStore, ThreadStore};
   8use agent_client_protocol::{self as acp};
   9use agent_servers::AgentServer;
  10use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, NotifyWhenAgentWaiting};
  11use anyhow::bail;
  12use audio::{Audio, Sound};
  13use buffer_diff::BufferDiff;
  14use client::zed_urls;
  15use collections::{HashMap, HashSet};
  16use editor::scroll::Autoscroll;
  17use editor::{Editor, EditorMode, MultiBuffer, PathKey, SelectionEffects};
  18use file_icons::FileIcons;
  19use fs::Fs;
  20use gpui::{
  21    Action, Animation, AnimationExt, App, BorderStyle, ClickEvent, ClipboardItem, EdgesRefinement,
  22    Empty, Entity, FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, MouseButton,
  23    PlatformDisplay, SharedString, Stateful, StyleRefinement, Subscription, Task, TextStyle,
  24    TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity, Window, WindowHandle, div,
  25    linear_color_stop, linear_gradient, list, percentage, point, prelude::*, pulsating_between,
  26};
  27use language::Buffer;
  28use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  29use project::Project;
  30use prompt_store::PromptId;
  31use rope::Point;
  32use settings::{Settings as _, SettingsStore};
  33use std::sync::Arc;
  34use std::{collections::BTreeMap, process::ExitStatus, rc::Rc, time::Duration};
  35use text::Anchor;
  36use theme::ThemeSettings;
  37use ui::{
  38    Callout, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding, PopoverMenuHandle,
  39    Scrollbar, ScrollbarState, Tooltip, prelude::*,
  40};
  41use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  42use workspace::{CollaboratorId, Workspace};
  43use zed_actions::agent::{Chat, ToggleModelSelector};
  44use zed_actions::assistant::OpenRulesLibrary;
  45
  46use super::entry_view_state::EntryViewState;
  47use crate::acp::AcpModelSelectorPopover;
  48use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
  49use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
  50use crate::agent_diff::AgentDiff;
  51use crate::profile_selector::{ProfileProvider, ProfileSelector};
  52use crate::ui::{AgentNotification, AgentNotificationEvent, BurnModeTooltip};
  53use crate::{
  54    AgentDiffPane, AgentPanel, ContinueThread, ContinueWithBurnMode, ExpandMessageEditor, Follow,
  55    KeepAll, OpenAgentDiff, RejectAll, ToggleBurnMode, ToggleProfileSelector,
  56};
  57
  58const RESPONSE_PADDING_X: Pixels = px(19.);
  59pub const MIN_EDITOR_LINES: usize = 4;
  60pub const MAX_EDITOR_LINES: usize = 8;
  61
  62enum ThreadError {
  63    PaymentRequired,
  64    ModelRequestLimitReached(cloud_llm_client::Plan),
  65    ToolUseLimitReached,
  66    Other(SharedString),
  67}
  68
  69impl ThreadError {
  70    fn from_err(error: anyhow::Error) -> Self {
  71        if error.is::<language_model::PaymentRequiredError>() {
  72            Self::PaymentRequired
  73        } else if error.is::<language_model::ToolUseLimitReachedError>() {
  74            Self::ToolUseLimitReached
  75        } else if let Some(error) =
  76            error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
  77        {
  78            Self::ModelRequestLimitReached(error.plan)
  79        } else {
  80            Self::Other(error.to_string().into())
  81        }
  82    }
  83}
  84
  85impl ProfileProvider for Entity<agent2::Thread> {
  86    fn profile_id(&self, cx: &App) -> AgentProfileId {
  87        self.read(cx).profile().clone()
  88    }
  89
  90    fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
  91        self.update(cx, |thread, _cx| {
  92            thread.set_profile(profile_id);
  93        });
  94    }
  95
  96    fn profiles_supported(&self, cx: &App) -> bool {
  97        self.read(cx)
  98            .model()
  99            .map_or(false, |model| model.supports_tools())
 100    }
 101}
 102
 103pub struct AcpThreadView {
 104    agent: Rc<dyn AgentServer>,
 105    workspace: WeakEntity<Workspace>,
 106    project: Entity<Project>,
 107    thread_state: ThreadState,
 108    entry_view_state: Entity<EntryViewState>,
 109    message_editor: Entity<MessageEditor>,
 110    model_selector: Option<Entity<AcpModelSelectorPopover>>,
 111    profile_selector: Option<Entity<ProfileSelector>>,
 112    notifications: Vec<WindowHandle<AgentNotification>>,
 113    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
 114    thread_error: Option<ThreadError>,
 115    list_state: ListState,
 116    scrollbar_state: ScrollbarState,
 117    auth_task: Option<Task<()>>,
 118    expanded_tool_calls: HashSet<acp::ToolCallId>,
 119    expanded_thinking_blocks: HashSet<(usize, usize)>,
 120    edits_expanded: bool,
 121    plan_expanded: bool,
 122    editor_expanded: bool,
 123    terminal_expanded: bool,
 124    editing_message: Option<usize>,
 125    _cancel_task: Option<Task<()>>,
 126    _subscriptions: [Subscription; 3],
 127}
 128
 129enum ThreadState {
 130    Loading {
 131        _task: Task<()>,
 132    },
 133    Ready {
 134        thread: Entity<AcpThread>,
 135        _subscription: [Subscription; 2],
 136    },
 137    LoadError(LoadError),
 138    Unauthenticated {
 139        connection: Rc<dyn AgentConnection>,
 140    },
 141    ServerExited {
 142        status: ExitStatus,
 143    },
 144}
 145
 146impl AcpThreadView {
 147    pub fn new(
 148        agent: Rc<dyn AgentServer>,
 149        workspace: WeakEntity<Workspace>,
 150        project: Entity<Project>,
 151        thread_store: Entity<ThreadStore>,
 152        text_thread_store: Entity<TextThreadStore>,
 153        window: &mut Window,
 154        cx: &mut Context<Self>,
 155    ) -> Self {
 156        let message_editor = cx.new(|cx| {
 157            MessageEditor::new(
 158                workspace.clone(),
 159                project.clone(),
 160                thread_store.clone(),
 161                text_thread_store.clone(),
 162                "Message the agent - @ to include context",
 163                editor::EditorMode::AutoHeight {
 164                    min_lines: MIN_EDITOR_LINES,
 165                    max_lines: Some(MAX_EDITOR_LINES),
 166                },
 167                window,
 168                cx,
 169            )
 170        });
 171
 172        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 173
 174        let entry_view_state = cx.new(|_| {
 175            EntryViewState::new(
 176                workspace.clone(),
 177                project.clone(),
 178                thread_store.clone(),
 179                text_thread_store.clone(),
 180            )
 181        });
 182
 183        let subscriptions = [
 184            cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 185            cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
 186            cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
 187        ];
 188
 189        Self {
 190            agent: agent.clone(),
 191            workspace: workspace.clone(),
 192            project: project.clone(),
 193            entry_view_state,
 194            thread_state: Self::initial_state(agent, workspace, project, window, cx),
 195            message_editor,
 196            model_selector: None,
 197            profile_selector: None,
 198            notifications: Vec::new(),
 199            notification_subscriptions: HashMap::default(),
 200            list_state: list_state.clone(),
 201            scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
 202            thread_error: None,
 203            auth_task: None,
 204            expanded_tool_calls: HashSet::default(),
 205            expanded_thinking_blocks: HashSet::default(),
 206            editing_message: None,
 207            edits_expanded: false,
 208            plan_expanded: false,
 209            editor_expanded: false,
 210            terminal_expanded: true,
 211            _subscriptions: subscriptions,
 212            _cancel_task: None,
 213        }
 214    }
 215
 216    fn initial_state(
 217        agent: Rc<dyn AgentServer>,
 218        workspace: WeakEntity<Workspace>,
 219        project: Entity<Project>,
 220        window: &mut Window,
 221        cx: &mut Context<Self>,
 222    ) -> ThreadState {
 223        let root_dir = project
 224            .read(cx)
 225            .visible_worktrees(cx)
 226            .next()
 227            .map(|worktree| worktree.read(cx).abs_path())
 228            .unwrap_or_else(|| paths::home_dir().as_path().into());
 229
 230        let connect_task = agent.connect(&root_dir, &project, cx);
 231        let load_task = cx.spawn_in(window, async move |this, cx| {
 232            let connection = match connect_task.await {
 233                Ok(connection) => connection,
 234                Err(err) => {
 235                    this.update(cx, |this, cx| {
 236                        this.handle_load_error(err, cx);
 237                        cx.notify();
 238                    })
 239                    .log_err();
 240                    return;
 241                }
 242            };
 243
 244            // this.update_in(cx, |_this, _window, cx| {
 245            //     let status = connection.exit_status(cx);
 246            //     cx.spawn(async move |this, cx| {
 247            //         let status = status.await.ok();
 248            //         this.update(cx, |this, cx| {
 249            //             this.thread_state = ThreadState::ServerExited { status };
 250            //             cx.notify();
 251            //         })
 252            //         .ok();
 253            //     })
 254            //     .detach();
 255            // })
 256            // .ok();
 257
 258            let Some(result) = cx
 259                .update(|_, cx| {
 260                    connection
 261                        .clone()
 262                        .new_thread(project.clone(), &root_dir, cx)
 263                })
 264                .log_err()
 265            else {
 266                return;
 267            };
 268
 269            let result = match result.await {
 270                Err(e) => {
 271                    let mut cx = cx.clone();
 272                    if e.is::<acp_thread::AuthRequired>() {
 273                        this.update(&mut cx, |this, cx| {
 274                            this.thread_state = ThreadState::Unauthenticated { connection };
 275                            cx.notify();
 276                        })
 277                        .ok();
 278                        return;
 279                    } else {
 280                        Err(e)
 281                    }
 282                }
 283                Ok(thread) => Ok(thread),
 284            };
 285
 286            this.update_in(cx, |this, window, cx| {
 287                match result {
 288                    Ok(thread) => {
 289                        let thread_subscription =
 290                            cx.subscribe_in(&thread, window, Self::handle_thread_event);
 291
 292                        let action_log = thread.read(cx).action_log().clone();
 293                        let action_log_subscription =
 294                            cx.observe(&action_log, |_, _, cx| cx.notify());
 295
 296                        this.list_state
 297                            .splice(0..0, thread.read(cx).entries().len());
 298
 299                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 300
 301                        this.model_selector =
 302                            thread
 303                                .read(cx)
 304                                .connection()
 305                                .model_selector()
 306                                .map(|selector| {
 307                                    cx.new(|cx| {
 308                                        AcpModelSelectorPopover::new(
 309                                            thread.read(cx).session_id().clone(),
 310                                            selector,
 311                                            PopoverMenuHandle::default(),
 312                                            this.focus_handle(cx),
 313                                            window,
 314                                            cx,
 315                                        )
 316                                    })
 317                                });
 318
 319                        this.thread_state = ThreadState::Ready {
 320                            thread,
 321                            _subscription: [thread_subscription, action_log_subscription],
 322                        };
 323
 324                        this.profile_selector = this.as_native_thread(cx).map(|thread| {
 325                            cx.new(|cx| {
 326                                ProfileSelector::new(
 327                                    <dyn Fs>::global(cx),
 328                                    Arc::new(thread.clone()),
 329                                    this.focus_handle(cx),
 330                                    cx,
 331                                )
 332                            })
 333                        });
 334
 335                        cx.notify();
 336                    }
 337                    Err(err) => {
 338                        this.handle_load_error(err, cx);
 339                    }
 340                };
 341            })
 342            .log_err();
 343        });
 344
 345        ThreadState::Loading { _task: load_task }
 346    }
 347
 348    fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
 349        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 350            self.thread_state = ThreadState::LoadError(load_err.clone());
 351        } else {
 352            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 353        }
 354        cx.notify();
 355    }
 356
 357    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 358        match &self.thread_state {
 359            ThreadState::Ready { thread, .. } => Some(thread),
 360            ThreadState::Unauthenticated { .. }
 361            | ThreadState::Loading { .. }
 362            | ThreadState::LoadError(..)
 363            | ThreadState::ServerExited { .. } => None,
 364        }
 365    }
 366
 367    pub fn title(&self, cx: &App) -> SharedString {
 368        match &self.thread_state {
 369            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
 370            ThreadState::Loading { .. } => "Loading…".into(),
 371            ThreadState::LoadError(_) => "Failed to load".into(),
 372            ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
 373            ThreadState::ServerExited { .. } => "Server exited unexpectedly".into(),
 374        }
 375    }
 376
 377    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
 378        self.thread_error.take();
 379
 380        if let Some(thread) = self.thread() {
 381            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 382        }
 383    }
 384
 385    pub fn expand_message_editor(
 386        &mut self,
 387        _: &ExpandMessageEditor,
 388        _window: &mut Window,
 389        cx: &mut Context<Self>,
 390    ) {
 391        self.set_editor_is_expanded(!self.editor_expanded, cx);
 392        cx.notify();
 393    }
 394
 395    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 396        self.editor_expanded = is_expanded;
 397        self.message_editor.update(cx, |editor, cx| {
 398            if is_expanded {
 399                editor.set_mode(
 400                    EditorMode::Full {
 401                        scale_ui_elements_with_buffer_font_size: false,
 402                        show_active_line_background: false,
 403                        sized_by_content: false,
 404                    },
 405                    cx,
 406                )
 407            } else {
 408                editor.set_mode(
 409                    EditorMode::AutoHeight {
 410                        min_lines: MIN_EDITOR_LINES,
 411                        max_lines: Some(MAX_EDITOR_LINES),
 412                    },
 413                    cx,
 414                )
 415            }
 416        });
 417        cx.notify();
 418    }
 419
 420    pub fn handle_message_editor_event(
 421        &mut self,
 422        _: &Entity<MessageEditor>,
 423        event: &MessageEditorEvent,
 424        window: &mut Window,
 425        cx: &mut Context<Self>,
 426    ) {
 427        match event {
 428            MessageEditorEvent::Send => self.send(window, cx),
 429            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 430            MessageEditorEvent::Focus => {
 431                self.cancel_editing(&Default::default(), window, cx);
 432            }
 433        }
 434    }
 435
 436    pub fn handle_entry_view_event(
 437        &mut self,
 438        _: &Entity<EntryViewState>,
 439        event: &EntryViewEvent,
 440        window: &mut Window,
 441        cx: &mut Context<Self>,
 442    ) {
 443        match &event.view_event {
 444            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 445                self.editing_message = Some(event.entry_index);
 446                cx.notify();
 447            }
 448            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 449                self.regenerate(event.entry_index, editor, window, cx);
 450            }
 451            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 452                self.cancel_editing(&Default::default(), window, cx);
 453            }
 454        }
 455    }
 456
 457    fn resume_chat(&mut self, cx: &mut Context<Self>) {
 458        self.thread_error.take();
 459        let Some(thread) = self.thread() else {
 460            return;
 461        };
 462
 463        let task = thread.update(cx, |thread, cx| thread.resume(cx));
 464        cx.spawn(async move |this, cx| {
 465            let result = task.await;
 466
 467            this.update(cx, |this, cx| {
 468                if let Err(err) = result {
 469                    this.handle_thread_error(err, cx);
 470                }
 471            })
 472        })
 473        .detach();
 474    }
 475
 476    fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 477        if let Some(thread) = self.thread() {
 478            if thread.read(cx).status() != ThreadStatus::Idle {
 479                self.stop_current_and_send_new_message(window, cx);
 480                return;
 481            }
 482        }
 483
 484        let contents = self
 485            .message_editor
 486            .update(cx, |message_editor, cx| message_editor.contents(window, cx));
 487        self.send_impl(contents, window, cx)
 488    }
 489
 490    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 491        let Some(thread) = self.thread().cloned() else {
 492            return;
 493        };
 494
 495        let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
 496
 497        let contents = self
 498            .message_editor
 499            .update(cx, |message_editor, cx| message_editor.contents(window, cx));
 500
 501        cx.spawn_in(window, async move |this, cx| {
 502            cancelled.await;
 503
 504            this.update_in(cx, |this, window, cx| {
 505                this.send_impl(contents, window, cx);
 506            })
 507            .ok();
 508        })
 509        .detach();
 510    }
 511
 512    fn send_impl(
 513        &mut self,
 514        contents: Task<anyhow::Result<Vec<acp::ContentBlock>>>,
 515        window: &mut Window,
 516        cx: &mut Context<Self>,
 517    ) {
 518        self.thread_error.take();
 519        self.editing_message.take();
 520
 521        let Some(thread) = self.thread().cloned() else {
 522            return;
 523        };
 524        let task = cx.spawn_in(window, async move |this, cx| {
 525            let contents = contents.await?;
 526
 527            if contents.is_empty() {
 528                return Ok(());
 529            }
 530
 531            this.update_in(cx, |this, window, cx| {
 532                this.set_editor_is_expanded(false, cx);
 533                this.scroll_to_bottom(cx);
 534                this.message_editor.update(cx, |message_editor, cx| {
 535                    message_editor.clear(window, cx);
 536                });
 537            })?;
 538            let send = thread.update(cx, |thread, cx| thread.send(contents, cx))?;
 539            send.await
 540        });
 541
 542        cx.spawn(async move |this, cx| {
 543            if let Err(err) = task.await {
 544                this.update(cx, |this, cx| {
 545                    this.handle_thread_error(err, cx);
 546                })
 547                .ok();
 548            }
 549        })
 550        .detach();
 551    }
 552
 553    fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
 554        let Some(thread) = self.thread().cloned() else {
 555            return;
 556        };
 557
 558        if let Some(index) = self.editing_message.take() {
 559            if let Some(editor) = self
 560                .entry_view_state
 561                .read(cx)
 562                .entry(index)
 563                .and_then(|e| e.message_editor())
 564                .cloned()
 565            {
 566                editor.update(cx, |editor, cx| {
 567                    if let Some(user_message) = thread
 568                        .read(cx)
 569                        .entries()
 570                        .get(index)
 571                        .and_then(|e| e.user_message())
 572                    {
 573                        editor.set_message(user_message.chunks.clone(), window, cx);
 574                    }
 575                })
 576            }
 577        };
 578        self.focus_handle(cx).focus(window);
 579        cx.notify();
 580    }
 581
 582    fn regenerate(
 583        &mut self,
 584        entry_ix: usize,
 585        message_editor: &Entity<MessageEditor>,
 586        window: &mut Window,
 587        cx: &mut Context<Self>,
 588    ) {
 589        let Some(thread) = self.thread().cloned() else {
 590            return;
 591        };
 592
 593        let Some(rewind) = thread.update(cx, |thread, cx| {
 594            let user_message_id = thread.entries().get(entry_ix)?.user_message()?.id.clone()?;
 595            Some(thread.rewind(user_message_id, cx))
 596        }) else {
 597            return;
 598        };
 599
 600        let contents =
 601            message_editor.update(cx, |message_editor, cx| message_editor.contents(window, cx));
 602
 603        let task = cx.foreground_executor().spawn(async move {
 604            rewind.await?;
 605            contents.await
 606        });
 607        self.send_impl(task, window, cx);
 608    }
 609
 610    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
 611        if let Some(thread) = self.thread() {
 612            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
 613        }
 614    }
 615
 616    fn open_edited_buffer(
 617        &mut self,
 618        buffer: &Entity<Buffer>,
 619        window: &mut Window,
 620        cx: &mut Context<Self>,
 621    ) {
 622        let Some(thread) = self.thread() else {
 623            return;
 624        };
 625
 626        let Some(diff) =
 627            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
 628        else {
 629            return;
 630        };
 631
 632        diff.update(cx, |diff, cx| {
 633            diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
 634        })
 635    }
 636
 637    fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
 638        self.thread_error = Some(ThreadError::from_err(error));
 639        cx.notify();
 640    }
 641
 642    fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
 643        self.thread_error = None;
 644        cx.notify();
 645    }
 646
 647    fn handle_thread_event(
 648        &mut self,
 649        thread: &Entity<AcpThread>,
 650        event: &AcpThreadEvent,
 651        window: &mut Window,
 652        cx: &mut Context<Self>,
 653    ) {
 654        match event {
 655            AcpThreadEvent::NewEntry => {
 656                let len = thread.read(cx).entries().len();
 657                let index = len - 1;
 658                self.entry_view_state.update(cx, |view_state, cx| {
 659                    view_state.sync_entry(index, &thread, window, cx)
 660                });
 661                self.list_state.splice(index..index, 1);
 662            }
 663            AcpThreadEvent::EntryUpdated(index) => {
 664                self.entry_view_state.update(cx, |view_state, cx| {
 665                    view_state.sync_entry(*index, &thread, window, cx)
 666                });
 667                self.list_state.splice(*index..index + 1, 1);
 668            }
 669            AcpThreadEvent::EntriesRemoved(range) => {
 670                self.entry_view_state
 671                    .update(cx, |view_state, _cx| view_state.remove(range.clone()));
 672                self.list_state.splice(range.clone(), 0);
 673            }
 674            AcpThreadEvent::ToolAuthorizationRequired => {
 675                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
 676            }
 677            AcpThreadEvent::Stopped => {
 678                let used_tools = thread.read(cx).used_tools_since_last_user_message();
 679                self.notify_with_sound(
 680                    if used_tools {
 681                        "Finished running tools"
 682                    } else {
 683                        "New message"
 684                    },
 685                    IconName::ZedAssistant,
 686                    window,
 687                    cx,
 688                );
 689            }
 690            AcpThreadEvent::Error => {
 691                self.notify_with_sound(
 692                    "Agent stopped due to an error",
 693                    IconName::Warning,
 694                    window,
 695                    cx,
 696                );
 697            }
 698            AcpThreadEvent::ServerExited(status) => {
 699                self.thread_state = ThreadState::ServerExited { status: *status };
 700            }
 701        }
 702        cx.notify();
 703    }
 704
 705    fn authenticate(
 706        &mut self,
 707        method: acp::AuthMethodId,
 708        window: &mut Window,
 709        cx: &mut Context<Self>,
 710    ) {
 711        let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
 712            return;
 713        };
 714
 715        self.thread_error.take();
 716        let authenticate = connection.authenticate(method, cx);
 717        self.auth_task = Some(cx.spawn_in(window, {
 718            let project = self.project.clone();
 719            let agent = self.agent.clone();
 720            async move |this, cx| {
 721                let result = authenticate.await;
 722
 723                this.update_in(cx, |this, window, cx| {
 724                    if let Err(err) = result {
 725                        this.handle_thread_error(err, cx);
 726                    } else {
 727                        this.thread_state = Self::initial_state(
 728                            agent,
 729                            this.workspace.clone(),
 730                            project.clone(),
 731                            window,
 732                            cx,
 733                        )
 734                    }
 735                    this.auth_task.take()
 736                })
 737                .ok();
 738            }
 739        }));
 740    }
 741
 742    fn authorize_tool_call(
 743        &mut self,
 744        tool_call_id: acp::ToolCallId,
 745        option_id: acp::PermissionOptionId,
 746        option_kind: acp::PermissionOptionKind,
 747        cx: &mut Context<Self>,
 748    ) {
 749        let Some(thread) = self.thread() else {
 750            return;
 751        };
 752        thread.update(cx, |thread, cx| {
 753            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
 754        });
 755        cx.notify();
 756    }
 757
 758    fn rewind(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
 759        let Some(thread) = self.thread() else {
 760            return;
 761        };
 762        thread
 763            .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
 764            .detach_and_log_err(cx);
 765        cx.notify();
 766    }
 767
 768    fn render_entry(
 769        &self,
 770        entry_ix: usize,
 771        total_entries: usize,
 772        entry: &AgentThreadEntry,
 773        window: &mut Window,
 774        cx: &Context<Self>,
 775    ) -> AnyElement {
 776        let primary = match &entry {
 777            AgentThreadEntry::UserMessage(message) => {
 778                let Some(editor) = self
 779                    .entry_view_state
 780                    .read(cx)
 781                    .entry(entry_ix)
 782                    .and_then(|entry| entry.message_editor())
 783                    .cloned()
 784                else {
 785                    return Empty.into_any_element();
 786                };
 787
 788                let editing = self.editing_message == Some(entry_ix);
 789                let editor_focus = editor.focus_handle(cx).is_focused(window);
 790                let focus_border = cx.theme().colors().border_focused;
 791
 792                div()
 793                    .id(("user_message", entry_ix))
 794                    .py_4()
 795                    .px_2()
 796                    .children(message.id.clone().and_then(|message_id| {
 797                        message.checkpoint.as_ref()?.show.then(|| {
 798                            Button::new("restore-checkpoint", "Restore Checkpoint")
 799                                .icon(IconName::Undo)
 800                                .icon_size(IconSize::XSmall)
 801                                .icon_position(IconPosition::Start)
 802                                .label_size(LabelSize::XSmall)
 803                                .on_click(cx.listener(move |this, _, _window, cx| {
 804                                    this.rewind(&message_id, cx);
 805                                }))
 806                        })
 807                    }))
 808                    .child(
 809                        div()
 810                            .relative()
 811                            .child(
 812                                div()
 813                                    .p_3()
 814                                    .rounded_lg()
 815                                    .shadow_md()
 816                                    .bg(cx.theme().colors().editor_background)
 817                                    .border_1()
 818                                    .when(editing && !editor_focus, |this| this.border_dashed())
 819                                    .border_color(cx.theme().colors().border)
 820                                    .map(|this|{
 821                                        if editor_focus {
 822                                            this.border_color(focus_border)
 823                                        } else {
 824                                            this.hover(|s| s.border_color(focus_border.opacity(0.8)))
 825                                        }
 826                                    })
 827                                    .text_xs()
 828                                    .child(editor.clone().into_any_element()),
 829                            )
 830                            .when(editor_focus, |this|
 831                                this.child(
 832                                    h_flex()
 833                                        .absolute()
 834                                        .top_neg_3p5()
 835                                        .right_3()
 836                                        .gap_1()
 837                                        .rounded_sm()
 838                                        .border_1()
 839                                        .border_color(cx.theme().colors().border)
 840                                        .bg(cx.theme().colors().editor_background)
 841                                        .overflow_hidden()
 842                                        .child(
 843                                            IconButton::new("cancel", IconName::Close)
 844                                                .icon_color(Color::Error)
 845                                                .icon_size(IconSize::XSmall)
 846                                                .on_click(cx.listener(Self::cancel_editing))
 847                                        )
 848                                        .child(
 849                                            IconButton::new("regenerate", IconName::Return)
 850                                                .icon_color(Color::Muted)
 851                                                .icon_size(IconSize::XSmall)
 852                                                .tooltip(Tooltip::text(
 853                                                    "Editing will restart the thread from this point."
 854                                                ))
 855                                                .on_click(cx.listener({
 856                                                    let editor = editor.clone();
 857                                                    move |this, _, window, cx| {
 858                                                        this.regenerate(
 859                                                            entry_ix, &editor, window, cx,
 860                                                        );
 861                                                    }
 862                                                })),
 863                                        )
 864                                )
 865                            ),
 866                    )
 867                    .into_any()
 868            }
 869            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
 870                let style = default_markdown_style(false, window, cx);
 871                let message_body = v_flex()
 872                    .w_full()
 873                    .gap_2p5()
 874                    .children(chunks.iter().enumerate().filter_map(
 875                        |(chunk_ix, chunk)| match chunk {
 876                            AssistantMessageChunk::Message { block } => {
 877                                block.markdown().map(|md| {
 878                                    self.render_markdown(md.clone(), style.clone())
 879                                        .into_any_element()
 880                                })
 881                            }
 882                            AssistantMessageChunk::Thought { block } => {
 883                                block.markdown().map(|md| {
 884                                    self.render_thinking_block(
 885                                        entry_ix,
 886                                        chunk_ix,
 887                                        md.clone(),
 888                                        window,
 889                                        cx,
 890                                    )
 891                                    .into_any_element()
 892                                })
 893                            }
 894                        },
 895                    ))
 896                    .into_any();
 897
 898                v_flex()
 899                    .px_5()
 900                    .py_1()
 901                    .when(entry_ix + 1 == total_entries, |this| this.pb_4())
 902                    .w_full()
 903                    .text_ui(cx)
 904                    .child(message_body)
 905                    .into_any()
 906            }
 907            AgentThreadEntry::ToolCall(tool_call) => {
 908                let has_terminals = tool_call.terminals().next().is_some();
 909
 910                div().w_full().py_1p5().px_5().map(|this| {
 911                    if has_terminals {
 912                        this.children(tool_call.terminals().map(|terminal| {
 913                            self.render_terminal_tool_call(
 914                                entry_ix, terminal, tool_call, window, cx,
 915                            )
 916                        }))
 917                    } else {
 918                        this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
 919                    }
 920                })
 921            }
 922            .into_any(),
 923        };
 924
 925        let Some(thread) = self.thread() else {
 926            return primary;
 927        };
 928
 929        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
 930        let primary = if entry_ix == total_entries - 1 && !is_generating {
 931            v_flex()
 932                .w_full()
 933                .child(primary)
 934                .child(self.render_thread_controls(cx))
 935                .into_any_element()
 936        } else {
 937            primary
 938        };
 939
 940        if let Some(editing_index) = self.editing_message.as_ref()
 941            && *editing_index < entry_ix
 942        {
 943            div()
 944                .child(primary)
 945                .opacity(0.2)
 946                .block_mouse_except_scroll()
 947                .id("overlay")
 948                .on_click(cx.listener(Self::cancel_editing))
 949                .into_any_element()
 950        } else {
 951            primary
 952        }
 953    }
 954
 955    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
 956        cx.theme()
 957            .colors()
 958            .element_background
 959            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
 960    }
 961
 962    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
 963        cx.theme().colors().border.opacity(0.6)
 964    }
 965
 966    fn tool_name_font_size(&self) -> Rems {
 967        rems_from_px(13.)
 968    }
 969
 970    fn render_thinking_block(
 971        &self,
 972        entry_ix: usize,
 973        chunk_ix: usize,
 974        chunk: Entity<Markdown>,
 975        window: &Window,
 976        cx: &Context<Self>,
 977    ) -> AnyElement {
 978        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
 979        let card_header_id = SharedString::from("inner-card-header");
 980        let key = (entry_ix, chunk_ix);
 981        let is_open = self.expanded_thinking_blocks.contains(&key);
 982
 983        v_flex()
 984            .child(
 985                h_flex()
 986                    .id(header_id)
 987                    .group(&card_header_id)
 988                    .relative()
 989                    .w_full()
 990                    .gap_1p5()
 991                    .opacity(0.8)
 992                    .hover(|style| style.opacity(1.))
 993                    .child(
 994                        h_flex()
 995                            .size_4()
 996                            .justify_center()
 997                            .child(
 998                                div()
 999                                    .group_hover(&card_header_id, |s| s.invisible().w_0())
1000                                    .child(
1001                                        Icon::new(IconName::ToolThink)
1002                                            .size(IconSize::Small)
1003                                            .color(Color::Muted),
1004                                    ),
1005                            )
1006                            .child(
1007                                h_flex()
1008                                    .absolute()
1009                                    .inset_0()
1010                                    .invisible()
1011                                    .justify_center()
1012                                    .group_hover(&card_header_id, |s| s.visible())
1013                                    .child(
1014                                        Disclosure::new(("expand", entry_ix), is_open)
1015                                            .opened_icon(IconName::ChevronUp)
1016                                            .closed_icon(IconName::ChevronRight)
1017                                            .on_click(cx.listener({
1018                                                move |this, _event, _window, cx| {
1019                                                    if is_open {
1020                                                        this.expanded_thinking_blocks.remove(&key);
1021                                                    } else {
1022                                                        this.expanded_thinking_blocks.insert(key);
1023                                                    }
1024                                                    cx.notify();
1025                                                }
1026                                            })),
1027                                    ),
1028                            ),
1029                    )
1030                    .child(
1031                        div()
1032                            .text_size(self.tool_name_font_size())
1033                            .child("Thinking"),
1034                    )
1035                    .on_click(cx.listener({
1036                        move |this, _event, _window, cx| {
1037                            if is_open {
1038                                this.expanded_thinking_blocks.remove(&key);
1039                            } else {
1040                                this.expanded_thinking_blocks.insert(key);
1041                            }
1042                            cx.notify();
1043                        }
1044                    })),
1045            )
1046            .when(is_open, |this| {
1047                this.child(
1048                    div()
1049                        .relative()
1050                        .mt_1p5()
1051                        .ml(px(7.))
1052                        .pl_4()
1053                        .border_l_1()
1054                        .border_color(self.tool_card_border_color(cx))
1055                        .text_ui_sm(cx)
1056                        .child(
1057                            self.render_markdown(chunk, default_markdown_style(false, window, cx)),
1058                        ),
1059                )
1060            })
1061            .into_any_element()
1062    }
1063
1064    fn render_tool_call_icon(
1065        &self,
1066        group_name: SharedString,
1067        entry_ix: usize,
1068        is_collapsible: bool,
1069        is_open: bool,
1070        tool_call: &ToolCall,
1071        cx: &Context<Self>,
1072    ) -> Div {
1073        let tool_icon = Icon::new(match tool_call.kind {
1074            acp::ToolKind::Read => IconName::ToolRead,
1075            acp::ToolKind::Edit => IconName::ToolPencil,
1076            acp::ToolKind::Delete => IconName::ToolDeleteFile,
1077            acp::ToolKind::Move => IconName::ArrowRightLeft,
1078            acp::ToolKind::Search => IconName::ToolSearch,
1079            acp::ToolKind::Execute => IconName::ToolTerminal,
1080            acp::ToolKind::Think => IconName::ToolThink,
1081            acp::ToolKind::Fetch => IconName::ToolWeb,
1082            acp::ToolKind::Other => IconName::ToolHammer,
1083        })
1084        .size(IconSize::Small)
1085        .color(Color::Muted);
1086
1087        let base_container = h_flex().size_4().justify_center();
1088
1089        if is_collapsible {
1090            base_container
1091                .child(
1092                    div()
1093                        .group_hover(&group_name, |s| s.invisible().w_0())
1094                        .child(tool_icon),
1095                )
1096                .child(
1097                    h_flex()
1098                        .absolute()
1099                        .inset_0()
1100                        .invisible()
1101                        .justify_center()
1102                        .group_hover(&group_name, |s| s.visible())
1103                        .child(
1104                            Disclosure::new(("expand", entry_ix), is_open)
1105                                .opened_icon(IconName::ChevronUp)
1106                                .closed_icon(IconName::ChevronRight)
1107                                .on_click(cx.listener({
1108                                    let id = tool_call.id.clone();
1109                                    move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1110                                        if is_open {
1111                                            this.expanded_tool_calls.remove(&id);
1112                                        } else {
1113                                            this.expanded_tool_calls.insert(id.clone());
1114                                        }
1115                                        cx.notify();
1116                                    }
1117                                })),
1118                        ),
1119                )
1120        } else {
1121            base_container.child(tool_icon)
1122        }
1123    }
1124
1125    fn render_tool_call(
1126        &self,
1127        entry_ix: usize,
1128        tool_call: &ToolCall,
1129        window: &Window,
1130        cx: &Context<Self>,
1131    ) -> Div {
1132        let header_id = SharedString::from(format!("outer-tool-call-header-{}", entry_ix));
1133        let card_header_id = SharedString::from("inner-tool-call-header");
1134
1135        let status_icon = match &tool_call.status {
1136            ToolCallStatus::Pending
1137            | ToolCallStatus::WaitingForConfirmation { .. }
1138            | ToolCallStatus::Completed => None,
1139            ToolCallStatus::InProgress => Some(
1140                Icon::new(IconName::ArrowCircle)
1141                    .color(Color::Accent)
1142                    .size(IconSize::Small)
1143                    .with_animation(
1144                        "running",
1145                        Animation::new(Duration::from_secs(2)).repeat(),
1146                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1147                    )
1148                    .into_any(),
1149            ),
1150            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => Some(
1151                Icon::new(IconName::Close)
1152                    .color(Color::Error)
1153                    .size(IconSize::Small)
1154                    .into_any_element(),
1155            ),
1156        };
1157
1158        let needs_confirmation = matches!(
1159            tool_call.status,
1160            ToolCallStatus::WaitingForConfirmation { .. }
1161        );
1162        let is_edit = matches!(tool_call.kind, acp::ToolKind::Edit);
1163        let has_diff = tool_call
1164            .content
1165            .iter()
1166            .any(|content| matches!(content, ToolCallContent::Diff { .. }));
1167        let has_nonempty_diff = tool_call.content.iter().any(|content| match content {
1168            ToolCallContent::Diff(diff) => diff.read(cx).has_revealed_range(cx),
1169            _ => false,
1170        });
1171        let use_card_layout = needs_confirmation || is_edit || has_diff;
1172
1173        let is_collapsible = !tool_call.content.is_empty() && !use_card_layout;
1174
1175        let is_open = tool_call.content.is_empty()
1176            || needs_confirmation
1177            || has_nonempty_diff
1178            || self.expanded_tool_calls.contains(&tool_call.id);
1179
1180        let gradient_overlay = |color: Hsla| {
1181            div()
1182                .absolute()
1183                .top_0()
1184                .right_0()
1185                .w_12()
1186                .h_full()
1187                .bg(linear_gradient(
1188                    90.,
1189                    linear_color_stop(color, 1.),
1190                    linear_color_stop(color.opacity(0.2), 0.),
1191                ))
1192        };
1193        let gradient_color = if use_card_layout {
1194            self.tool_card_header_bg(cx)
1195        } else {
1196            cx.theme().colors().panel_background
1197        };
1198
1199        let tool_output_display = match &tool_call.status {
1200            ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
1201                .w_full()
1202                .children(tool_call.content.iter().map(|content| {
1203                    div()
1204                        .child(
1205                            self.render_tool_call_content(entry_ix, content, tool_call, window, cx),
1206                        )
1207                        .into_any_element()
1208                }))
1209                .child(self.render_permission_buttons(
1210                    options,
1211                    entry_ix,
1212                    tool_call.id.clone(),
1213                    tool_call.content.is_empty(),
1214                    cx,
1215                )),
1216            ToolCallStatus::Pending
1217            | ToolCallStatus::InProgress
1218            | ToolCallStatus::Completed
1219            | ToolCallStatus::Failed
1220            | ToolCallStatus::Canceled => {
1221                v_flex()
1222                    .w_full()
1223                    .children(tool_call.content.iter().map(|content| {
1224                        div()
1225                            .child(
1226                                self.render_tool_call_content(
1227                                    entry_ix, content, tool_call, window, cx,
1228                                ),
1229                            )
1230                            .into_any_element()
1231                    }))
1232            }
1233            ToolCallStatus::Rejected => v_flex().size_0(),
1234        };
1235
1236        v_flex()
1237            .when(use_card_layout, |this| {
1238                this.rounded_lg()
1239                    .border_1()
1240                    .border_color(self.tool_card_border_color(cx))
1241                    .bg(cx.theme().colors().editor_background)
1242                    .overflow_hidden()
1243            })
1244            .child(
1245                h_flex()
1246                    .id(header_id)
1247                    .w_full()
1248                    .gap_1()
1249                    .justify_between()
1250                    .map(|this| {
1251                        if use_card_layout {
1252                            this.pl_2()
1253                                .pr_1()
1254                                .py_1()
1255                                .rounded_t_md()
1256                                .bg(self.tool_card_header_bg(cx))
1257                        } else {
1258                            this.opacity(0.8).hover(|style| style.opacity(1.))
1259                        }
1260                    })
1261                    .child(
1262                        h_flex()
1263                            .group(&card_header_id)
1264                            .relative()
1265                            .w_full()
1266                            .text_size(self.tool_name_font_size())
1267                            .child(self.render_tool_call_icon(
1268                                card_header_id,
1269                                entry_ix,
1270                                is_collapsible,
1271                                is_open,
1272                                tool_call,
1273                                cx,
1274                            ))
1275                            .child(if tool_call.locations.len() == 1 {
1276                                let name = tool_call.locations[0]
1277                                    .path
1278                                    .file_name()
1279                                    .unwrap_or_default()
1280                                    .display()
1281                                    .to_string();
1282
1283                                h_flex()
1284                                    .id(("open-tool-call-location", entry_ix))
1285                                    .w_full()
1286                                    .max_w_full()
1287                                    .px_1p5()
1288                                    .rounded_sm()
1289                                    .overflow_x_scroll()
1290                                    .opacity(0.8)
1291                                    .hover(|label| {
1292                                        label.opacity(1.).bg(cx
1293                                            .theme()
1294                                            .colors()
1295                                            .element_hover
1296                                            .opacity(0.5))
1297                                    })
1298                                    .child(name)
1299                                    .tooltip(Tooltip::text("Jump to File"))
1300                                    .on_click(cx.listener(move |this, _, window, cx| {
1301                                        this.open_tool_call_location(entry_ix, 0, window, cx);
1302                                    }))
1303                                    .into_any_element()
1304                            } else {
1305                                h_flex()
1306                                    .id("non-card-label-container")
1307                                    .w_full()
1308                                    .relative()
1309                                    .ml_1p5()
1310                                    .overflow_hidden()
1311                                    .child(
1312                                        h_flex()
1313                                            .id("non-card-label")
1314                                            .pr_8()
1315                                            .w_full()
1316                                            .overflow_x_scroll()
1317                                            .child(self.render_markdown(
1318                                                tool_call.label.clone(),
1319                                                default_markdown_style(
1320                                                    needs_confirmation || is_edit || has_diff,
1321                                                    window,
1322                                                    cx,
1323                                                ),
1324                                            )),
1325                                    )
1326                                    .child(gradient_overlay(gradient_color))
1327                                    .on_click(cx.listener({
1328                                        let id = tool_call.id.clone();
1329                                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1330                                            if is_open {
1331                                                this.expanded_tool_calls.remove(&id);
1332                                            } else {
1333                                                this.expanded_tool_calls.insert(id.clone());
1334                                            }
1335                                            cx.notify();
1336                                        }
1337                                    }))
1338                                    .into_any()
1339                            }),
1340                    )
1341                    .children(status_icon),
1342            )
1343            .when(is_open, |this| this.child(tool_output_display))
1344    }
1345
1346    fn render_tool_call_content(
1347        &self,
1348        entry_ix: usize,
1349        content: &ToolCallContent,
1350        tool_call: &ToolCall,
1351        window: &Window,
1352        cx: &Context<Self>,
1353    ) -> AnyElement {
1354        match content {
1355            ToolCallContent::ContentBlock(content) => {
1356                if let Some(resource_link) = content.resource_link() {
1357                    self.render_resource_link(resource_link, cx)
1358                } else if let Some(markdown) = content.markdown() {
1359                    self.render_markdown_output(markdown.clone(), tool_call.id.clone(), window, cx)
1360                } else {
1361                    Empty.into_any_element()
1362                }
1363            }
1364            ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, &diff, cx),
1365            ToolCallContent::Terminal(terminal) => {
1366                self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
1367            }
1368        }
1369    }
1370
1371    fn render_markdown_output(
1372        &self,
1373        markdown: Entity<Markdown>,
1374        tool_call_id: acp::ToolCallId,
1375        window: &Window,
1376        cx: &Context<Self>,
1377    ) -> AnyElement {
1378        let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id.clone()));
1379
1380        v_flex()
1381            .mt_1p5()
1382            .ml(px(7.))
1383            .px_3p5()
1384            .gap_2()
1385            .border_l_1()
1386            .border_color(self.tool_card_border_color(cx))
1387            .text_sm()
1388            .text_color(cx.theme().colors().text_muted)
1389            .child(self.render_markdown(markdown, default_markdown_style(false, window, cx)))
1390            .child(
1391                Button::new(button_id, "Collapse Output")
1392                    .full_width()
1393                    .style(ButtonStyle::Outlined)
1394                    .label_size(LabelSize::Small)
1395                    .icon(IconName::ChevronUp)
1396                    .icon_color(Color::Muted)
1397                    .icon_position(IconPosition::Start)
1398                    .on_click(cx.listener({
1399                        let id = tool_call_id.clone();
1400                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1401                            this.expanded_tool_calls.remove(&id);
1402                            cx.notify();
1403                        }
1404                    })),
1405            )
1406            .into_any_element()
1407    }
1408
1409    fn render_resource_link(
1410        &self,
1411        resource_link: &acp::ResourceLink,
1412        cx: &Context<Self>,
1413    ) -> AnyElement {
1414        let uri: SharedString = resource_link.uri.clone().into();
1415
1416        let label: SharedString = if let Some(path) = resource_link.uri.strip_prefix("file://") {
1417            path.to_string().into()
1418        } else {
1419            uri.clone()
1420        };
1421
1422        let button_id = SharedString::from(format!("item-{}", uri.clone()));
1423
1424        div()
1425            .ml(px(7.))
1426            .pl_2p5()
1427            .border_l_1()
1428            .border_color(self.tool_card_border_color(cx))
1429            .overflow_hidden()
1430            .child(
1431                Button::new(button_id, label)
1432                    .label_size(LabelSize::Small)
1433                    .color(Color::Muted)
1434                    .icon(IconName::ArrowUpRight)
1435                    .icon_size(IconSize::XSmall)
1436                    .icon_color(Color::Muted)
1437                    .truncate(true)
1438                    .on_click(cx.listener({
1439                        let workspace = self.workspace.clone();
1440                        move |_, _, window, cx: &mut Context<Self>| {
1441                            Self::open_link(uri.clone(), &workspace, window, cx);
1442                        }
1443                    })),
1444            )
1445            .into_any_element()
1446    }
1447
1448    fn render_permission_buttons(
1449        &self,
1450        options: &[acp::PermissionOption],
1451        entry_ix: usize,
1452        tool_call_id: acp::ToolCallId,
1453        empty_content: bool,
1454        cx: &Context<Self>,
1455    ) -> Div {
1456        h_flex()
1457            .py_1()
1458            .pl_2()
1459            .pr_1()
1460            .gap_1()
1461            .justify_between()
1462            .flex_wrap()
1463            .when(!empty_content, |this| {
1464                this.border_t_1()
1465                    .border_color(self.tool_card_border_color(cx))
1466            })
1467            .child(
1468                div()
1469                    .min_w(rems_from_px(145.))
1470                    .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
1471            )
1472            .child(h_flex().gap_0p5().children(options.iter().map(|option| {
1473                let option_id = SharedString::from(option.id.0.clone());
1474                Button::new((option_id, entry_ix), option.name.clone())
1475                    .map(|this| match option.kind {
1476                        acp::PermissionOptionKind::AllowOnce => {
1477                            this.icon(IconName::Check).icon_color(Color::Success)
1478                        }
1479                        acp::PermissionOptionKind::AllowAlways => {
1480                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1481                        }
1482                        acp::PermissionOptionKind::RejectOnce => {
1483                            this.icon(IconName::Close).icon_color(Color::Error)
1484                        }
1485                        acp::PermissionOptionKind::RejectAlways => {
1486                            this.icon(IconName::Close).icon_color(Color::Error)
1487                        }
1488                    })
1489                    .icon_position(IconPosition::Start)
1490                    .icon_size(IconSize::XSmall)
1491                    .label_size(LabelSize::Small)
1492                    .on_click(cx.listener({
1493                        let tool_call_id = tool_call_id.clone();
1494                        let option_id = option.id.clone();
1495                        let option_kind = option.kind;
1496                        move |this, _, _, cx| {
1497                            this.authorize_tool_call(
1498                                tool_call_id.clone(),
1499                                option_id.clone(),
1500                                option_kind,
1501                                cx,
1502                            );
1503                        }
1504                    }))
1505            })))
1506    }
1507
1508    fn render_diff_editor(
1509        &self,
1510        entry_ix: usize,
1511        diff: &Entity<acp_thread::Diff>,
1512        cx: &Context<Self>,
1513    ) -> AnyElement {
1514        v_flex()
1515            .h_full()
1516            .border_t_1()
1517            .border_color(self.tool_card_border_color(cx))
1518            .child(
1519                if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
1520                    && let Some(editor) = entry.editor_for_diff(&diff)
1521                {
1522                    editor.clone().into_any_element()
1523                } else {
1524                    Empty.into_any()
1525                },
1526            )
1527            .into_any()
1528    }
1529
1530    fn render_terminal_tool_call(
1531        &self,
1532        entry_ix: usize,
1533        terminal: &Entity<acp_thread::Terminal>,
1534        tool_call: &ToolCall,
1535        window: &Window,
1536        cx: &Context<Self>,
1537    ) -> AnyElement {
1538        let terminal_data = terminal.read(cx);
1539        let working_dir = terminal_data.working_dir();
1540        let command = terminal_data.command();
1541        let started_at = terminal_data.started_at();
1542
1543        let tool_failed = matches!(
1544            &tool_call.status,
1545            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
1546        );
1547
1548        let output = terminal_data.output();
1549        let command_finished = output.is_some();
1550        let truncated_output = output.is_some_and(|output| output.was_content_truncated);
1551        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
1552
1553        let command_failed = command_finished
1554            && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
1555
1556        let time_elapsed = if let Some(output) = output {
1557            output.ended_at.duration_since(started_at)
1558        } else {
1559            started_at.elapsed()
1560        };
1561
1562        let header_bg = cx
1563            .theme()
1564            .colors()
1565            .element_background
1566            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1567        let border_color = cx.theme().colors().border.opacity(0.6);
1568
1569        let working_dir = working_dir
1570            .as_ref()
1571            .map(|path| format!("{}", path.display()))
1572            .unwrap_or_else(|| "current directory".to_string());
1573
1574        let header = h_flex()
1575            .id(SharedString::from(format!(
1576                "terminal-tool-header-{}",
1577                terminal.entity_id()
1578            )))
1579            .flex_none()
1580            .gap_1()
1581            .justify_between()
1582            .rounded_t_md()
1583            .child(
1584                div()
1585                    .id(("command-target-path", terminal.entity_id()))
1586                    .w_full()
1587                    .max_w_full()
1588                    .overflow_x_scroll()
1589                    .child(
1590                        Label::new(working_dir)
1591                            .buffer_font(cx)
1592                            .size(LabelSize::XSmall)
1593                            .color(Color::Muted),
1594                    ),
1595            )
1596            .when(!command_finished, |header| {
1597                header
1598                    .gap_1p5()
1599                    .child(
1600                        Button::new(
1601                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
1602                            "Stop",
1603                        )
1604                        .icon(IconName::Stop)
1605                        .icon_position(IconPosition::Start)
1606                        .icon_size(IconSize::Small)
1607                        .icon_color(Color::Error)
1608                        .label_size(LabelSize::Small)
1609                        .tooltip(move |window, cx| {
1610                            Tooltip::with_meta(
1611                                "Stop This Command",
1612                                None,
1613                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
1614                                window,
1615                                cx,
1616                            )
1617                        })
1618                        .on_click({
1619                            let terminal = terminal.clone();
1620                            cx.listener(move |_this, _event, _window, cx| {
1621                                let inner_terminal = terminal.read(cx).inner().clone();
1622                                inner_terminal.update(cx, |inner_terminal, _cx| {
1623                                    inner_terminal.kill_active_task();
1624                                });
1625                            })
1626                        }),
1627                    )
1628                    .child(Divider::vertical())
1629                    .child(
1630                        Icon::new(IconName::ArrowCircle)
1631                            .size(IconSize::XSmall)
1632                            .color(Color::Info)
1633                            .with_animation(
1634                                "arrow-circle",
1635                                Animation::new(Duration::from_secs(2)).repeat(),
1636                                |icon, delta| {
1637                                    icon.transform(Transformation::rotate(percentage(delta)))
1638                                },
1639                            ),
1640                    )
1641            })
1642            .when(tool_failed || command_failed, |header| {
1643                header.child(
1644                    div()
1645                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
1646                        .child(
1647                            Icon::new(IconName::Close)
1648                                .size(IconSize::Small)
1649                                .color(Color::Error),
1650                        )
1651                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
1652                            this.tooltip(Tooltip::text(format!(
1653                                "Exited with code {}",
1654                                status.code().unwrap_or(-1),
1655                            )))
1656                        }),
1657                )
1658            })
1659            .when(truncated_output, |header| {
1660                let tooltip = if let Some(output) = output {
1661                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
1662                        "Output exceeded terminal max lines and was \
1663                            truncated, the model received the first 16 KB."
1664                            .to_string()
1665                    } else {
1666                        format!(
1667                            "Output is {} long—to avoid unexpected token usage, \
1668                                only 16 KB was sent back to the model.",
1669                            format_file_size(output.original_content_len as u64, true),
1670                        )
1671                    }
1672                } else {
1673                    "Output was truncated".to_string()
1674                };
1675
1676                header.child(
1677                    h_flex()
1678                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
1679                        .gap_1()
1680                        .child(
1681                            Icon::new(IconName::Info)
1682                                .size(IconSize::XSmall)
1683                                .color(Color::Ignored),
1684                        )
1685                        .child(
1686                            Label::new("Truncated")
1687                                .color(Color::Muted)
1688                                .size(LabelSize::XSmall),
1689                        )
1690                        .tooltip(Tooltip::text(tooltip)),
1691                )
1692            })
1693            .when(time_elapsed > Duration::from_secs(10), |header| {
1694                header.child(
1695                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
1696                        .buffer_font(cx)
1697                        .color(Color::Muted)
1698                        .size(LabelSize::XSmall),
1699                )
1700            })
1701            .child(
1702                Disclosure::new(
1703                    SharedString::from(format!(
1704                        "terminal-tool-disclosure-{}",
1705                        terminal.entity_id()
1706                    )),
1707                    self.terminal_expanded,
1708                )
1709                .opened_icon(IconName::ChevronUp)
1710                .closed_icon(IconName::ChevronDown)
1711                .on_click(cx.listener(move |this, _event, _window, _cx| {
1712                    this.terminal_expanded = !this.terminal_expanded;
1713                })),
1714            );
1715
1716        let terminal_view = self
1717            .entry_view_state
1718            .read(cx)
1719            .entry(entry_ix)
1720            .and_then(|entry| entry.terminal(&terminal));
1721        let show_output = self.terminal_expanded && terminal_view.is_some();
1722
1723        v_flex()
1724            .mb_2()
1725            .border_1()
1726            .when(tool_failed || command_failed, |card| card.border_dashed())
1727            .border_color(border_color)
1728            .rounded_lg()
1729            .overflow_hidden()
1730            .child(
1731                v_flex()
1732                    .py_1p5()
1733                    .pl_2()
1734                    .pr_1p5()
1735                    .gap_0p5()
1736                    .bg(header_bg)
1737                    .text_xs()
1738                    .child(header)
1739                    .child(
1740                        MarkdownElement::new(
1741                            command.clone(),
1742                            terminal_command_markdown_style(window, cx),
1743                        )
1744                        .code_block_renderer(
1745                            markdown::CodeBlockRenderer::Default {
1746                                copy_button: false,
1747                                copy_button_on_hover: true,
1748                                border: false,
1749                            },
1750                        ),
1751                    ),
1752            )
1753            .when(show_output, |this| {
1754                this.child(
1755                    div()
1756                        .pt_2()
1757                        .border_t_1()
1758                        .when(tool_failed || command_failed, |card| card.border_dashed())
1759                        .border_color(border_color)
1760                        .bg(cx.theme().colors().editor_background)
1761                        .rounded_b_md()
1762                        .text_ui_sm(cx)
1763                        .children(terminal_view.clone()),
1764                )
1765            })
1766            .into_any()
1767    }
1768
1769    fn render_agent_logo(&self) -> AnyElement {
1770        Icon::new(self.agent.logo())
1771            .color(Color::Muted)
1772            .size(IconSize::XLarge)
1773            .into_any_element()
1774    }
1775
1776    fn render_error_agent_logo(&self) -> AnyElement {
1777        let logo = Icon::new(self.agent.logo())
1778            .color(Color::Muted)
1779            .size(IconSize::XLarge)
1780            .into_any_element();
1781
1782        h_flex()
1783            .relative()
1784            .justify_center()
1785            .child(div().opacity(0.3).child(logo))
1786            .child(
1787                h_flex().absolute().right_1().bottom_0().child(
1788                    Icon::new(IconName::XCircle)
1789                        .color(Color::Error)
1790                        .size(IconSize::Small),
1791                ),
1792            )
1793            .into_any_element()
1794    }
1795
1796    fn render_empty_state(&self, cx: &App) -> AnyElement {
1797        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1798
1799        v_flex()
1800            .size_full()
1801            .items_center()
1802            .justify_center()
1803            .child(if loading {
1804                h_flex()
1805                    .justify_center()
1806                    .child(self.render_agent_logo())
1807                    .with_animation(
1808                        "pulsating_icon",
1809                        Animation::new(Duration::from_secs(2))
1810                            .repeat()
1811                            .with_easing(pulsating_between(0.4, 1.0)),
1812                        |icon, delta| icon.opacity(delta),
1813                    )
1814                    .into_any()
1815            } else {
1816                self.render_agent_logo().into_any_element()
1817            })
1818            .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1819                div()
1820                    .child(LoadingLabel::new("").size(LabelSize::Large))
1821                    .into_any_element()
1822            } else {
1823                Headline::new(self.agent.empty_state_headline())
1824                    .size(HeadlineSize::Medium)
1825                    .into_any_element()
1826            }))
1827            .child(
1828                div()
1829                    .max_w_1_2()
1830                    .text_sm()
1831                    .text_center()
1832                    .map(|this| {
1833                        if loading {
1834                            this.invisible()
1835                        } else {
1836                            this.text_color(cx.theme().colors().text_muted)
1837                        }
1838                    })
1839                    .child(self.agent.empty_state_message()),
1840            )
1841            .into_any()
1842    }
1843
1844    fn render_pending_auth_state(&self) -> AnyElement {
1845        v_flex()
1846            .items_center()
1847            .justify_center()
1848            .child(self.render_error_agent_logo())
1849            .child(
1850                h_flex()
1851                    .mt_4()
1852                    .mb_1()
1853                    .justify_center()
1854                    .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1855            )
1856            .into_any()
1857    }
1858
1859    fn render_server_exited(&self, status: ExitStatus, _cx: &Context<Self>) -> AnyElement {
1860        v_flex()
1861            .items_center()
1862            .justify_center()
1863            .child(self.render_error_agent_logo())
1864            .child(
1865                v_flex()
1866                    .mt_4()
1867                    .mb_2()
1868                    .gap_0p5()
1869                    .text_center()
1870                    .items_center()
1871                    .child(Headline::new("Server exited unexpectedly").size(HeadlineSize::Medium))
1872                    .child(
1873                        Label::new(format!("Exit status: {}", status.code().unwrap_or(-127)))
1874                            .size(LabelSize::Small)
1875                            .color(Color::Muted),
1876                    ),
1877            )
1878            .into_any_element()
1879    }
1880
1881    fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1882        let mut container = v_flex()
1883            .items_center()
1884            .justify_center()
1885            .child(self.render_error_agent_logo())
1886            .child(
1887                v_flex()
1888                    .mt_4()
1889                    .mb_2()
1890                    .gap_0p5()
1891                    .text_center()
1892                    .items_center()
1893                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1894                    .child(
1895                        Label::new(e.to_string())
1896                            .size(LabelSize::Small)
1897                            .color(Color::Muted),
1898                    ),
1899            );
1900
1901        if let LoadError::Unsupported {
1902            upgrade_message,
1903            upgrade_command,
1904            ..
1905        } = &e
1906        {
1907            let upgrade_message = upgrade_message.clone();
1908            let upgrade_command = upgrade_command.clone();
1909            container = container.child(Button::new("upgrade", upgrade_message).on_click(
1910                cx.listener(move |this, _, window, cx| {
1911                    this.workspace
1912                        .update(cx, |workspace, cx| {
1913                            let project = workspace.project().read(cx);
1914                            let cwd = project.first_project_directory(cx);
1915                            let shell = project.terminal_settings(&cwd, cx).shell.clone();
1916                            let spawn_in_terminal = task::SpawnInTerminal {
1917                                id: task::TaskId("install".to_string()),
1918                                full_label: upgrade_command.clone(),
1919                                label: upgrade_command.clone(),
1920                                command: Some(upgrade_command.clone()),
1921                                args: Vec::new(),
1922                                command_label: upgrade_command.clone(),
1923                                cwd,
1924                                env: Default::default(),
1925                                use_new_terminal: true,
1926                                allow_concurrent_runs: true,
1927                                reveal: Default::default(),
1928                                reveal_target: Default::default(),
1929                                hide: Default::default(),
1930                                shell,
1931                                show_summary: true,
1932                                show_command: true,
1933                                show_rerun: false,
1934                            };
1935                            workspace
1936                                .spawn_in_terminal(spawn_in_terminal, window, cx)
1937                                .detach();
1938                        })
1939                        .ok();
1940                }),
1941            ));
1942        }
1943
1944        container.into_any()
1945    }
1946
1947    fn render_activity_bar(
1948        &self,
1949        thread_entity: &Entity<AcpThread>,
1950        window: &mut Window,
1951        cx: &Context<Self>,
1952    ) -> Option<AnyElement> {
1953        let thread = thread_entity.read(cx);
1954        let action_log = thread.action_log();
1955        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1956        let plan = thread.plan();
1957
1958        if changed_buffers.is_empty() && plan.is_empty() {
1959            return None;
1960        }
1961
1962        let editor_bg_color = cx.theme().colors().editor_background;
1963        let active_color = cx.theme().colors().element_selected;
1964        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1965
1966        let pending_edits = thread.has_pending_edit_tool_calls();
1967
1968        v_flex()
1969            .mt_1()
1970            .mx_2()
1971            .bg(bg_edit_files_disclosure)
1972            .border_1()
1973            .border_b_0()
1974            .border_color(cx.theme().colors().border)
1975            .rounded_t_md()
1976            .shadow(vec![gpui::BoxShadow {
1977                color: gpui::black().opacity(0.15),
1978                offset: point(px(1.), px(-1.)),
1979                blur_radius: px(3.),
1980                spread_radius: px(0.),
1981            }])
1982            .when(!plan.is_empty(), |this| {
1983                this.child(self.render_plan_summary(plan, window, cx))
1984                    .when(self.plan_expanded, |parent| {
1985                        parent.child(self.render_plan_entries(plan, window, cx))
1986                    })
1987            })
1988            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
1989                this.child(Divider::horizontal().color(DividerColor::Border))
1990            })
1991            .when(!changed_buffers.is_empty(), |this| {
1992                this.child(self.render_edits_summary(
1993                    action_log,
1994                    &changed_buffers,
1995                    self.edits_expanded,
1996                    pending_edits,
1997                    window,
1998                    cx,
1999                ))
2000                .when(self.edits_expanded, |parent| {
2001                    parent.child(self.render_edited_files(
2002                        action_log,
2003                        &changed_buffers,
2004                        pending_edits,
2005                        cx,
2006                    ))
2007                })
2008            })
2009            .into_any()
2010            .into()
2011    }
2012
2013    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2014        let stats = plan.stats();
2015
2016        let title = if let Some(entry) = stats.in_progress_entry
2017            && !self.plan_expanded
2018        {
2019            h_flex()
2020                .w_full()
2021                .cursor_default()
2022                .gap_1()
2023                .text_xs()
2024                .text_color(cx.theme().colors().text_muted)
2025                .justify_between()
2026                .child(
2027                    h_flex()
2028                        .gap_1()
2029                        .child(
2030                            Label::new("Current:")
2031                                .size(LabelSize::Small)
2032                                .color(Color::Muted),
2033                        )
2034                        .child(MarkdownElement::new(
2035                            entry.content.clone(),
2036                            plan_label_markdown_style(&entry.status, window, cx),
2037                        )),
2038                )
2039                .when(stats.pending > 0, |this| {
2040                    this.child(
2041                        Label::new(format!("{} left", stats.pending))
2042                            .size(LabelSize::Small)
2043                            .color(Color::Muted)
2044                            .mr_1(),
2045                    )
2046                })
2047        } else {
2048            let status_label = if stats.pending == 0 {
2049                "All Done".to_string()
2050            } else if stats.completed == 0 {
2051                format!("{} Tasks", plan.entries.len())
2052            } else {
2053                format!("{}/{}", stats.completed, plan.entries.len())
2054            };
2055
2056            h_flex()
2057                .w_full()
2058                .gap_1()
2059                .justify_between()
2060                .child(
2061                    Label::new("Plan")
2062                        .size(LabelSize::Small)
2063                        .color(Color::Muted),
2064                )
2065                .child(
2066                    Label::new(status_label)
2067                        .size(LabelSize::Small)
2068                        .color(Color::Muted)
2069                        .mr_1(),
2070                )
2071        };
2072
2073        h_flex()
2074            .p_1()
2075            .justify_between()
2076            .when(self.plan_expanded, |this| {
2077                this.border_b_1().border_color(cx.theme().colors().border)
2078            })
2079            .child(
2080                h_flex()
2081                    .id("plan_summary")
2082                    .w_full()
2083                    .gap_1()
2084                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
2085                    .child(title)
2086                    .on_click(cx.listener(|this, _, _, cx| {
2087                        this.plan_expanded = !this.plan_expanded;
2088                        cx.notify();
2089                    })),
2090            )
2091    }
2092
2093    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2094        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2095            let element = h_flex()
2096                .py_1()
2097                .px_2()
2098                .gap_2()
2099                .justify_between()
2100                .bg(cx.theme().colors().editor_background)
2101                .when(index < plan.entries.len() - 1, |parent| {
2102                    parent.border_color(cx.theme().colors().border).border_b_1()
2103                })
2104                .child(
2105                    h_flex()
2106                        .id(("plan_entry", index))
2107                        .gap_1p5()
2108                        .max_w_full()
2109                        .overflow_x_scroll()
2110                        .text_xs()
2111                        .text_color(cx.theme().colors().text_muted)
2112                        .child(match entry.status {
2113                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
2114                                .size(IconSize::Small)
2115                                .color(Color::Muted)
2116                                .into_any_element(),
2117                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
2118                                .size(IconSize::Small)
2119                                .color(Color::Accent)
2120                                .with_animation(
2121                                    "running",
2122                                    Animation::new(Duration::from_secs(2)).repeat(),
2123                                    |icon, delta| {
2124                                        icon.transform(Transformation::rotate(percentage(delta)))
2125                                    },
2126                                )
2127                                .into_any_element(),
2128                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
2129                                .size(IconSize::Small)
2130                                .color(Color::Success)
2131                                .into_any_element(),
2132                        })
2133                        .child(MarkdownElement::new(
2134                            entry.content.clone(),
2135                            plan_label_markdown_style(&entry.status, window, cx),
2136                        )),
2137                );
2138
2139            Some(element)
2140        }))
2141    }
2142
2143    fn render_edits_summary(
2144        &self,
2145        action_log: &Entity<ActionLog>,
2146        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2147        expanded: bool,
2148        pending_edits: bool,
2149        window: &mut Window,
2150        cx: &Context<Self>,
2151    ) -> Div {
2152        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2153
2154        let focus_handle = self.focus_handle(cx);
2155
2156        h_flex()
2157            .p_1()
2158            .justify_between()
2159            .when(expanded, |this| {
2160                this.border_b_1().border_color(cx.theme().colors().border)
2161            })
2162            .child(
2163                h_flex()
2164                    .id("edits-container")
2165                    .w_full()
2166                    .gap_1()
2167                    .child(Disclosure::new("edits-disclosure", expanded))
2168                    .map(|this| {
2169                        if pending_edits {
2170                            this.child(
2171                                Label::new(format!(
2172                                    "Editing {} {}",
2173                                    changed_buffers.len(),
2174                                    if changed_buffers.len() == 1 {
2175                                        "file"
2176                                    } else {
2177                                        "files"
2178                                    }
2179                                ))
2180                                .color(Color::Muted)
2181                                .size(LabelSize::Small)
2182                                .with_animation(
2183                                    "edit-label",
2184                                    Animation::new(Duration::from_secs(2))
2185                                        .repeat()
2186                                        .with_easing(pulsating_between(0.3, 0.7)),
2187                                    |label, delta| label.alpha(delta),
2188                                ),
2189                            )
2190                        } else {
2191                            this.child(
2192                                Label::new("Edits")
2193                                    .size(LabelSize::Small)
2194                                    .color(Color::Muted),
2195                            )
2196                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
2197                            .child(
2198                                Label::new(format!(
2199                                    "{} {}",
2200                                    changed_buffers.len(),
2201                                    if changed_buffers.len() == 1 {
2202                                        "file"
2203                                    } else {
2204                                        "files"
2205                                    }
2206                                ))
2207                                .size(LabelSize::Small)
2208                                .color(Color::Muted),
2209                            )
2210                        }
2211                    })
2212                    .on_click(cx.listener(|this, _, _, cx| {
2213                        this.edits_expanded = !this.edits_expanded;
2214                        cx.notify();
2215                    })),
2216            )
2217            .child(
2218                h_flex()
2219                    .gap_1()
2220                    .child(
2221                        IconButton::new("review-changes", IconName::ListTodo)
2222                            .icon_size(IconSize::Small)
2223                            .tooltip({
2224                                let focus_handle = focus_handle.clone();
2225                                move |window, cx| {
2226                                    Tooltip::for_action_in(
2227                                        "Review Changes",
2228                                        &OpenAgentDiff,
2229                                        &focus_handle,
2230                                        window,
2231                                        cx,
2232                                    )
2233                                }
2234                            })
2235                            .on_click(cx.listener(|_, _, window, cx| {
2236                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
2237                            })),
2238                    )
2239                    .child(Divider::vertical().color(DividerColor::Border))
2240                    .child(
2241                        Button::new("reject-all-changes", "Reject All")
2242                            .label_size(LabelSize::Small)
2243                            .disabled(pending_edits)
2244                            .when(pending_edits, |this| {
2245                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2246                            })
2247                            .key_binding(
2248                                KeyBinding::for_action_in(
2249                                    &RejectAll,
2250                                    &focus_handle.clone(),
2251                                    window,
2252                                    cx,
2253                                )
2254                                .map(|kb| kb.size(rems_from_px(10.))),
2255                            )
2256                            .on_click({
2257                                let action_log = action_log.clone();
2258                                cx.listener(move |_, _, _, cx| {
2259                                    action_log.update(cx, |action_log, cx| {
2260                                        action_log.reject_all_edits(cx).detach();
2261                                    })
2262                                })
2263                            }),
2264                    )
2265                    .child(
2266                        Button::new("keep-all-changes", "Keep All")
2267                            .label_size(LabelSize::Small)
2268                            .disabled(pending_edits)
2269                            .when(pending_edits, |this| {
2270                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2271                            })
2272                            .key_binding(
2273                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
2274                                    .map(|kb| kb.size(rems_from_px(10.))),
2275                            )
2276                            .on_click({
2277                                let action_log = action_log.clone();
2278                                cx.listener(move |_, _, _, cx| {
2279                                    action_log.update(cx, |action_log, cx| {
2280                                        action_log.keep_all_edits(cx);
2281                                    })
2282                                })
2283                            }),
2284                    ),
2285            )
2286    }
2287
2288    fn render_edited_files(
2289        &self,
2290        action_log: &Entity<ActionLog>,
2291        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2292        pending_edits: bool,
2293        cx: &Context<Self>,
2294    ) -> Div {
2295        let editor_bg_color = cx.theme().colors().editor_background;
2296
2297        v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
2298            |(index, (buffer, _diff))| {
2299                let file = buffer.read(cx).file()?;
2300                let path = file.path();
2301
2302                let file_path = path.parent().and_then(|parent| {
2303                    let parent_str = parent.to_string_lossy();
2304
2305                    if parent_str.is_empty() {
2306                        None
2307                    } else {
2308                        Some(
2309                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
2310                                .color(Color::Muted)
2311                                .size(LabelSize::XSmall)
2312                                .buffer_font(cx),
2313                        )
2314                    }
2315                });
2316
2317                let file_name = path.file_name().map(|name| {
2318                    Label::new(name.to_string_lossy().to_string())
2319                        .size(LabelSize::XSmall)
2320                        .buffer_font(cx)
2321                });
2322
2323                let file_icon = FileIcons::get_icon(&path, cx)
2324                    .map(Icon::from_path)
2325                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2326                    .unwrap_or_else(|| {
2327                        Icon::new(IconName::File)
2328                            .color(Color::Muted)
2329                            .size(IconSize::Small)
2330                    });
2331
2332                let overlay_gradient = linear_gradient(
2333                    90.,
2334                    linear_color_stop(editor_bg_color, 1.),
2335                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
2336                );
2337
2338                let element = h_flex()
2339                    .group("edited-code")
2340                    .id(("file-container", index))
2341                    .relative()
2342                    .py_1()
2343                    .pl_2()
2344                    .pr_1()
2345                    .gap_2()
2346                    .justify_between()
2347                    .bg(editor_bg_color)
2348                    .when(index < changed_buffers.len() - 1, |parent| {
2349                        parent.border_color(cx.theme().colors().border).border_b_1()
2350                    })
2351                    .child(
2352                        h_flex()
2353                            .id(("file-name", index))
2354                            .pr_8()
2355                            .gap_1p5()
2356                            .max_w_full()
2357                            .overflow_x_scroll()
2358                            .child(file_icon)
2359                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
2360                            .on_click({
2361                                let buffer = buffer.clone();
2362                                cx.listener(move |this, _, window, cx| {
2363                                    this.open_edited_buffer(&buffer, window, cx);
2364                                })
2365                            }),
2366                    )
2367                    .child(
2368                        h_flex()
2369                            .gap_1()
2370                            .visible_on_hover("edited-code")
2371                            .child(
2372                                Button::new("review", "Review")
2373                                    .label_size(LabelSize::Small)
2374                                    .on_click({
2375                                        let buffer = buffer.clone();
2376                                        cx.listener(move |this, _, window, cx| {
2377                                            this.open_edited_buffer(&buffer, window, cx);
2378                                        })
2379                                    }),
2380                            )
2381                            .child(Divider::vertical().color(DividerColor::BorderVariant))
2382                            .child(
2383                                Button::new("reject-file", "Reject")
2384                                    .label_size(LabelSize::Small)
2385                                    .disabled(pending_edits)
2386                                    .on_click({
2387                                        let buffer = buffer.clone();
2388                                        let action_log = action_log.clone();
2389                                        move |_, _, cx| {
2390                                            action_log.update(cx, |action_log, cx| {
2391                                                action_log
2392                                                    .reject_edits_in_ranges(
2393                                                        buffer.clone(),
2394                                                        vec![Anchor::MIN..Anchor::MAX],
2395                                                        cx,
2396                                                    )
2397                                                    .detach_and_log_err(cx);
2398                                            })
2399                                        }
2400                                    }),
2401                            )
2402                            .child(
2403                                Button::new("keep-file", "Keep")
2404                                    .label_size(LabelSize::Small)
2405                                    .disabled(pending_edits)
2406                                    .on_click({
2407                                        let buffer = buffer.clone();
2408                                        let action_log = action_log.clone();
2409                                        move |_, _, cx| {
2410                                            action_log.update(cx, |action_log, cx| {
2411                                                action_log.keep_edits_in_range(
2412                                                    buffer.clone(),
2413                                                    Anchor::MIN..Anchor::MAX,
2414                                                    cx,
2415                                                );
2416                                            })
2417                                        }
2418                                    }),
2419                            ),
2420                    )
2421                    .child(
2422                        div()
2423                            .id("gradient-overlay")
2424                            .absolute()
2425                            .h_full()
2426                            .w_12()
2427                            .top_0()
2428                            .bottom_0()
2429                            .right(px(152.))
2430                            .bg(overlay_gradient),
2431                    );
2432
2433                Some(element)
2434            },
2435        ))
2436    }
2437
2438    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2439        let focus_handle = self.message_editor.focus_handle(cx);
2440        let editor_bg_color = cx.theme().colors().editor_background;
2441        let (expand_icon, expand_tooltip) = if self.editor_expanded {
2442            (IconName::Minimize, "Minimize Message Editor")
2443        } else {
2444            (IconName::Maximize, "Expand Message Editor")
2445        };
2446
2447        v_flex()
2448            .on_action(cx.listener(Self::expand_message_editor))
2449            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
2450                if let Some(profile_selector) = this.profile_selector.as_ref() {
2451                    profile_selector.read(cx).menu_handle().toggle(window, cx);
2452                }
2453            }))
2454            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
2455                if let Some(model_selector) = this.model_selector.as_ref() {
2456                    model_selector
2457                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
2458                }
2459            }))
2460            .p_2()
2461            .gap_2()
2462            .border_t_1()
2463            .border_color(cx.theme().colors().border)
2464            .bg(editor_bg_color)
2465            .when(self.editor_expanded, |this| {
2466                this.h(vh(0.8, window)).size_full().justify_between()
2467            })
2468            .child(
2469                v_flex()
2470                    .relative()
2471                    .size_full()
2472                    .pt_1()
2473                    .pr_2p5()
2474                    .child(self.message_editor.clone())
2475                    .child(
2476                        h_flex()
2477                            .absolute()
2478                            .top_0()
2479                            .right_0()
2480                            .opacity(0.5)
2481                            .hover(|this| this.opacity(1.0))
2482                            .child(
2483                                IconButton::new("toggle-height", expand_icon)
2484                                    .icon_size(IconSize::Small)
2485                                    .icon_color(Color::Muted)
2486                                    .tooltip({
2487                                        let focus_handle = focus_handle.clone();
2488                                        move |window, cx| {
2489                                            Tooltip::for_action_in(
2490                                                expand_tooltip,
2491                                                &ExpandMessageEditor,
2492                                                &focus_handle,
2493                                                window,
2494                                                cx,
2495                                            )
2496                                        }
2497                                    })
2498                                    .on_click(cx.listener(|_, _, window, cx| {
2499                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2500                                    })),
2501                            ),
2502                    ),
2503            )
2504            .child(
2505                h_flex()
2506                    .flex_none()
2507                    .justify_between()
2508                    .child(
2509                        h_flex()
2510                            .gap_1()
2511                            .child(self.render_follow_toggle(cx))
2512                            .children(self.render_burn_mode_toggle(cx)),
2513                    )
2514                    .child(
2515                        h_flex()
2516                            .gap_1()
2517                            .children(self.profile_selector.clone())
2518                            .children(self.model_selector.clone())
2519                            .child(self.render_send_button(cx)),
2520                    ),
2521            )
2522            .into_any()
2523    }
2524
2525    pub(crate) fn as_native_connection(
2526        &self,
2527        cx: &App,
2528    ) -> Option<Rc<agent2::NativeAgentConnection>> {
2529        let acp_thread = self.thread()?.read(cx);
2530        acp_thread.connection().clone().downcast()
2531    }
2532
2533    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
2534        let acp_thread = self.thread()?.read(cx);
2535        self.as_native_connection(cx)?
2536            .thread(acp_thread.session_id(), cx)
2537    }
2538
2539    fn toggle_burn_mode(
2540        &mut self,
2541        _: &ToggleBurnMode,
2542        _window: &mut Window,
2543        cx: &mut Context<Self>,
2544    ) {
2545        let Some(thread) = self.as_native_thread(cx) else {
2546            return;
2547        };
2548
2549        thread.update(cx, |thread, _cx| {
2550            let current_mode = thread.completion_mode();
2551            thread.set_completion_mode(match current_mode {
2552                CompletionMode::Burn => CompletionMode::Normal,
2553                CompletionMode::Normal => CompletionMode::Burn,
2554            });
2555        });
2556    }
2557
2558    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2559        let thread = self.as_native_thread(cx)?.read(cx);
2560
2561        if thread
2562            .model()
2563            .map_or(true, |model| !model.supports_burn_mode())
2564        {
2565            return None;
2566        }
2567
2568        let active_completion_mode = thread.completion_mode();
2569        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2570        let icon = if burn_mode_enabled {
2571            IconName::ZedBurnModeOn
2572        } else {
2573            IconName::ZedBurnMode
2574        };
2575
2576        Some(
2577            IconButton::new("burn-mode", icon)
2578                .icon_size(IconSize::Small)
2579                .icon_color(Color::Muted)
2580                .toggle_state(burn_mode_enabled)
2581                .selected_icon_color(Color::Error)
2582                .on_click(cx.listener(|this, _event, window, cx| {
2583                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
2584                }))
2585                .tooltip(move |_window, cx| {
2586                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2587                        .into()
2588                })
2589                .into_any_element(),
2590        )
2591    }
2592
2593    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2594        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2595        let is_generating = self.thread().map_or(false, |thread| {
2596            thread.read(cx).status() != ThreadStatus::Idle
2597        });
2598
2599        if is_generating && is_editor_empty {
2600            IconButton::new("stop-generation", IconName::Stop)
2601                .icon_color(Color::Error)
2602                .style(ButtonStyle::Tinted(ui::TintColor::Error))
2603                .tooltip(move |window, cx| {
2604                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2605                })
2606                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
2607                .into_any_element()
2608        } else {
2609            let send_btn_tooltip = if is_editor_empty && !is_generating {
2610                "Type to Send"
2611            } else if is_generating {
2612                "Stop and Send Message"
2613            } else {
2614                "Send"
2615            };
2616
2617            IconButton::new("send-message", IconName::Send)
2618                .style(ButtonStyle::Filled)
2619                .map(|this| {
2620                    if is_editor_empty && !is_generating {
2621                        this.disabled(true).icon_color(Color::Muted)
2622                    } else {
2623                        this.icon_color(Color::Accent)
2624                    }
2625                })
2626                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
2627                .on_click(cx.listener(|this, _, window, cx| {
2628                    this.send(window, cx);
2629                }))
2630                .into_any_element()
2631        }
2632    }
2633
2634    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2635        let following = self
2636            .workspace
2637            .read_with(cx, |workspace, _| {
2638                workspace.is_being_followed(CollaboratorId::Agent)
2639            })
2640            .unwrap_or(false);
2641
2642        IconButton::new("follow-agent", IconName::Crosshair)
2643            .icon_size(IconSize::Small)
2644            .icon_color(Color::Muted)
2645            .toggle_state(following)
2646            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2647            .tooltip(move |window, cx| {
2648                if following {
2649                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2650                } else {
2651                    Tooltip::with_meta(
2652                        "Follow Agent",
2653                        Some(&Follow),
2654                        "Track the agent's location as it reads and edits files.",
2655                        window,
2656                        cx,
2657                    )
2658                }
2659            })
2660            .on_click(cx.listener(move |this, _, window, cx| {
2661                this.workspace
2662                    .update(cx, |workspace, cx| {
2663                        if following {
2664                            workspace.unfollow(CollaboratorId::Agent, window, cx);
2665                        } else {
2666                            workspace.follow(CollaboratorId::Agent, window, cx);
2667                        }
2668                    })
2669                    .ok();
2670            }))
2671    }
2672
2673    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2674        let workspace = self.workspace.clone();
2675        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2676            Self::open_link(text, &workspace, window, cx);
2677        })
2678    }
2679
2680    fn open_link(
2681        url: SharedString,
2682        workspace: &WeakEntity<Workspace>,
2683        window: &mut Window,
2684        cx: &mut App,
2685    ) {
2686        let Some(workspace) = workspace.upgrade() else {
2687            cx.open_url(&url);
2688            return;
2689        };
2690
2691        if let Some(mention) = MentionUri::parse(&url).log_err() {
2692            workspace.update(cx, |workspace, cx| match mention {
2693                MentionUri::File { abs_path, .. } => {
2694                    let project = workspace.project();
2695                    let Some((path, entry)) = project.update(cx, |project, cx| {
2696                        let path = project.find_project_path(abs_path, cx)?;
2697                        let entry = project.entry_for_path(&path, cx)?;
2698                        Some((path, entry))
2699                    }) else {
2700                        return;
2701                    };
2702
2703                    if entry.is_dir() {
2704                        project.update(cx, |_, cx| {
2705                            cx.emit(project::Event::RevealInProjectPanel(entry.id));
2706                        });
2707                    } else {
2708                        workspace
2709                            .open_path(path, None, true, window, cx)
2710                            .detach_and_log_err(cx);
2711                    }
2712                }
2713                MentionUri::Symbol {
2714                    path, line_range, ..
2715                }
2716                | MentionUri::Selection { path, line_range } => {
2717                    let project = workspace.project();
2718                    let Some((path, _)) = project.update(cx, |project, cx| {
2719                        let path = project.find_project_path(path, cx)?;
2720                        let entry = project.entry_for_path(&path, cx)?;
2721                        Some((path, entry))
2722                    }) else {
2723                        return;
2724                    };
2725
2726                    let item = workspace.open_path(path, None, true, window, cx);
2727                    window
2728                        .spawn(cx, async move |cx| {
2729                            let Some(editor) = item.await?.downcast::<Editor>() else {
2730                                return Ok(());
2731                            };
2732                            let range =
2733                                Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
2734                            editor
2735                                .update_in(cx, |editor, window, cx| {
2736                                    editor.change_selections(
2737                                        SelectionEffects::scroll(Autoscroll::center()),
2738                                        window,
2739                                        cx,
2740                                        |s| s.select_ranges(vec![range]),
2741                                    );
2742                                })
2743                                .ok();
2744                            anyhow::Ok(())
2745                        })
2746                        .detach_and_log_err(cx);
2747                }
2748                MentionUri::Thread { id, .. } => {
2749                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2750                        panel.update(cx, |panel, cx| {
2751                            panel
2752                                .open_thread_by_id(&id, window, cx)
2753                                .detach_and_log_err(cx)
2754                        });
2755                    }
2756                }
2757                MentionUri::TextThread { path, .. } => {
2758                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2759                        panel.update(cx, |panel, cx| {
2760                            panel
2761                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
2762                                .detach_and_log_err(cx);
2763                        });
2764                    }
2765                }
2766                MentionUri::Rule { id, .. } => {
2767                    let PromptId::User { uuid } = id else {
2768                        return;
2769                    };
2770                    window.dispatch_action(
2771                        Box::new(OpenRulesLibrary {
2772                            prompt_to_select: Some(uuid.0),
2773                        }),
2774                        cx,
2775                    )
2776                }
2777                MentionUri::Fetch { url } => {
2778                    cx.open_url(url.as_str());
2779                }
2780            })
2781        } else {
2782            cx.open_url(&url);
2783        }
2784    }
2785
2786    fn open_tool_call_location(
2787        &self,
2788        entry_ix: usize,
2789        location_ix: usize,
2790        window: &mut Window,
2791        cx: &mut Context<Self>,
2792    ) -> Option<()> {
2793        let (tool_call_location, agent_location) = self
2794            .thread()?
2795            .read(cx)
2796            .entries()
2797            .get(entry_ix)?
2798            .location(location_ix)?;
2799
2800        let project_path = self
2801            .project
2802            .read(cx)
2803            .find_project_path(&tool_call_location.path, cx)?;
2804
2805        let open_task = self
2806            .workspace
2807            .update(cx, |workspace, cx| {
2808                workspace.open_path(project_path, None, true, window, cx)
2809            })
2810            .log_err()?;
2811        window
2812            .spawn(cx, async move |cx| {
2813                let item = open_task.await?;
2814
2815                let Some(active_editor) = item.downcast::<Editor>() else {
2816                    return anyhow::Ok(());
2817                };
2818
2819                active_editor.update_in(cx, |editor, window, cx| {
2820                    let multibuffer = editor.buffer().read(cx);
2821                    let buffer = multibuffer.as_singleton();
2822                    if agent_location.buffer.upgrade() == buffer {
2823                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
2824                        let anchor = editor::Anchor::in_buffer(
2825                            excerpt_id.unwrap(),
2826                            buffer.unwrap().read(cx).remote_id(),
2827                            agent_location.position,
2828                        );
2829                        editor.change_selections(Default::default(), window, cx, |selections| {
2830                            selections.select_anchor_ranges([anchor..anchor]);
2831                        })
2832                    } else {
2833                        let row = tool_call_location.line.unwrap_or_default();
2834                        editor.change_selections(Default::default(), window, cx, |selections| {
2835                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
2836                        })
2837                    }
2838                })?;
2839
2840                anyhow::Ok(())
2841            })
2842            .detach_and_log_err(cx);
2843
2844        None
2845    }
2846
2847    pub fn open_thread_as_markdown(
2848        &self,
2849        workspace: Entity<Workspace>,
2850        window: &mut Window,
2851        cx: &mut App,
2852    ) -> Task<anyhow::Result<()>> {
2853        let markdown_language_task = workspace
2854            .read(cx)
2855            .app_state()
2856            .languages
2857            .language_for_name("Markdown");
2858
2859        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2860            let thread = thread.read(cx);
2861            (thread.title().to_string(), thread.to_markdown(cx))
2862        } else {
2863            return Task::ready(Ok(()));
2864        };
2865
2866        window.spawn(cx, async move |cx| {
2867            let markdown_language = markdown_language_task.await?;
2868
2869            workspace.update_in(cx, |workspace, window, cx| {
2870                let project = workspace.project().clone();
2871
2872                if !project.read(cx).is_local() {
2873                    bail!("failed to open active thread as markdown in remote project");
2874                }
2875
2876                let buffer = project.update(cx, |project, cx| {
2877                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
2878                });
2879                let buffer = cx.new(|cx| {
2880                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2881                });
2882
2883                workspace.add_item_to_active_pane(
2884                    Box::new(cx.new(|cx| {
2885                        let mut editor =
2886                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2887                        editor.set_breadcrumb_header(thread_summary);
2888                        editor
2889                    })),
2890                    None,
2891                    true,
2892                    window,
2893                    cx,
2894                );
2895
2896                anyhow::Ok(())
2897            })??;
2898            anyhow::Ok(())
2899        })
2900    }
2901
2902    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2903        self.list_state.scroll_to(ListOffset::default());
2904        cx.notify();
2905    }
2906
2907    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
2908        if let Some(thread) = self.thread() {
2909            let entry_count = thread.read(cx).entries().len();
2910            self.list_state.reset(entry_count);
2911            cx.notify();
2912        }
2913    }
2914
2915    fn notify_with_sound(
2916        &mut self,
2917        caption: impl Into<SharedString>,
2918        icon: IconName,
2919        window: &mut Window,
2920        cx: &mut Context<Self>,
2921    ) {
2922        self.play_notification_sound(window, cx);
2923        self.show_notification(caption, icon, window, cx);
2924    }
2925
2926    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2927        let settings = AgentSettings::get_global(cx);
2928        if settings.play_sound_when_agent_done && !window.is_window_active() {
2929            Audio::play_sound(Sound::AgentDone, cx);
2930        }
2931    }
2932
2933    fn show_notification(
2934        &mut self,
2935        caption: impl Into<SharedString>,
2936        icon: IconName,
2937        window: &mut Window,
2938        cx: &mut Context<Self>,
2939    ) {
2940        if window.is_window_active() || !self.notifications.is_empty() {
2941            return;
2942        }
2943
2944        let title = self.title(cx);
2945
2946        match AgentSettings::get_global(cx).notify_when_agent_waiting {
2947            NotifyWhenAgentWaiting::PrimaryScreen => {
2948                if let Some(primary) = cx.primary_display() {
2949                    self.pop_up(icon, caption.into(), title, window, primary, cx);
2950                }
2951            }
2952            NotifyWhenAgentWaiting::AllScreens => {
2953                let caption = caption.into();
2954                for screen in cx.displays() {
2955                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2956                }
2957            }
2958            NotifyWhenAgentWaiting::Never => {
2959                // Don't show anything
2960            }
2961        }
2962    }
2963
2964    fn pop_up(
2965        &mut self,
2966        icon: IconName,
2967        caption: SharedString,
2968        title: SharedString,
2969        window: &mut Window,
2970        screen: Rc<dyn PlatformDisplay>,
2971        cx: &mut Context<Self>,
2972    ) {
2973        let options = AgentNotification::window_options(screen, cx);
2974
2975        let project_name = self.workspace.upgrade().and_then(|workspace| {
2976            workspace
2977                .read(cx)
2978                .project()
2979                .read(cx)
2980                .visible_worktrees(cx)
2981                .next()
2982                .map(|worktree| worktree.read(cx).root_name().to_string())
2983        });
2984
2985        if let Some(screen_window) = cx
2986            .open_window(options, |_, cx| {
2987                cx.new(|_| {
2988                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2989                })
2990            })
2991            .log_err()
2992        {
2993            if let Some(pop_up) = screen_window.entity(cx).log_err() {
2994                self.notification_subscriptions
2995                    .entry(screen_window)
2996                    .or_insert_with(Vec::new)
2997                    .push(cx.subscribe_in(&pop_up, window, {
2998                        |this, _, event, window, cx| match event {
2999                            AgentNotificationEvent::Accepted => {
3000                                let handle = window.window_handle();
3001                                cx.activate(true);
3002
3003                                let workspace_handle = this.workspace.clone();
3004
3005                                // If there are multiple Zed windows, activate the correct one.
3006                                cx.defer(move |cx| {
3007                                    handle
3008                                        .update(cx, |_view, window, _cx| {
3009                                            window.activate_window();
3010
3011                                            if let Some(workspace) = workspace_handle.upgrade() {
3012                                                workspace.update(_cx, |workspace, cx| {
3013                                                    workspace.focus_panel::<AgentPanel>(window, cx);
3014                                                });
3015                                            }
3016                                        })
3017                                        .log_err();
3018                                });
3019
3020                                this.dismiss_notifications(cx);
3021                            }
3022                            AgentNotificationEvent::Dismissed => {
3023                                this.dismiss_notifications(cx);
3024                            }
3025                        }
3026                    }));
3027
3028                self.notifications.push(screen_window);
3029
3030                // If the user manually refocuses the original window, dismiss the popup.
3031                self.notification_subscriptions
3032                    .entry(screen_window)
3033                    .or_insert_with(Vec::new)
3034                    .push({
3035                        let pop_up_weak = pop_up.downgrade();
3036
3037                        cx.observe_window_activation(window, move |_, window, cx| {
3038                            if window.is_window_active() {
3039                                if let Some(pop_up) = pop_up_weak.upgrade() {
3040                                    pop_up.update(cx, |_, cx| {
3041                                        cx.emit(AgentNotificationEvent::Dismissed);
3042                                    });
3043                                }
3044                            }
3045                        })
3046                    });
3047            }
3048        }
3049    }
3050
3051    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3052        for window in self.notifications.drain(..) {
3053            window
3054                .update(cx, |_, window, _| {
3055                    window.remove_window();
3056                })
3057                .ok();
3058
3059            self.notification_subscriptions.remove(&window);
3060        }
3061    }
3062
3063    fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3064        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3065            .shape(ui::IconButtonShape::Square)
3066            .icon_size(IconSize::Small)
3067            .icon_color(Color::Ignored)
3068            .tooltip(Tooltip::text("Open Thread as Markdown"))
3069            .on_click(cx.listener(move |this, _, window, cx| {
3070                if let Some(workspace) = this.workspace.upgrade() {
3071                    this.open_thread_as_markdown(workspace, window, cx)
3072                        .detach_and_log_err(cx);
3073                }
3074            }));
3075
3076        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3077            .shape(ui::IconButtonShape::Square)
3078            .icon_size(IconSize::Small)
3079            .icon_color(Color::Ignored)
3080            .tooltip(Tooltip::text("Scroll To Top"))
3081            .on_click(cx.listener(move |this, _, _, cx| {
3082                this.scroll_to_top(cx);
3083            }));
3084
3085        h_flex()
3086            .w_full()
3087            .mr_1()
3088            .pb_2()
3089            .px(RESPONSE_PADDING_X)
3090            .opacity(0.4)
3091            .hover(|style| style.opacity(1.))
3092            .flex_wrap()
3093            .justify_end()
3094            .child(open_as_markdown)
3095            .child(scroll_to_top)
3096    }
3097
3098    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
3099        div()
3100            .id("acp-thread-scrollbar")
3101            .occlude()
3102            .on_mouse_move(cx.listener(|_, _, _, cx| {
3103                cx.notify();
3104                cx.stop_propagation()
3105            }))
3106            .on_hover(|_, _, cx| {
3107                cx.stop_propagation();
3108            })
3109            .on_any_mouse_down(|_, _, cx| {
3110                cx.stop_propagation();
3111            })
3112            .on_mouse_up(
3113                MouseButton::Left,
3114                cx.listener(|_, _, _, cx| {
3115                    cx.stop_propagation();
3116                }),
3117            )
3118            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3119                cx.notify();
3120            }))
3121            .h_full()
3122            .absolute()
3123            .right_1()
3124            .top_1()
3125            .bottom_0()
3126            .w(px(12.))
3127            .cursor_default()
3128            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
3129    }
3130
3131    fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
3132        self.entry_view_state.update(cx, |entry_view_state, cx| {
3133            entry_view_state.settings_changed(cx);
3134        });
3135    }
3136
3137    pub(crate) fn insert_dragged_files(
3138        &self,
3139        paths: Vec<project::ProjectPath>,
3140        added_worktrees: Vec<Entity<project::Worktree>>,
3141        window: &mut Window,
3142        cx: &mut Context<Self>,
3143    ) {
3144        self.message_editor.update(cx, |message_editor, cx| {
3145            message_editor.insert_dragged_files(paths, window, cx);
3146            drop(added_worktrees);
3147        })
3148    }
3149
3150    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<'_, Self>) -> Option<Div> {
3151        let content = match self.thread_error.as_ref()? {
3152            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
3153            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
3154            ThreadError::ModelRequestLimitReached(plan) => {
3155                self.render_model_request_limit_reached_error(*plan, cx)
3156            }
3157            ThreadError::ToolUseLimitReached => {
3158                self.render_tool_use_limit_reached_error(window, cx)?
3159            }
3160        };
3161
3162        Some(
3163            div()
3164                .border_t_1()
3165                .border_color(cx.theme().colors().border)
3166                .child(content),
3167        )
3168    }
3169
3170    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
3171        let icon = Icon::new(IconName::XCircle)
3172            .size(IconSize::Small)
3173            .color(Color::Error);
3174
3175        Callout::new()
3176            .icon(icon)
3177            .title("Error")
3178            .description(error.clone())
3179            .secondary_action(self.create_copy_button(error.to_string()))
3180            .primary_action(self.dismiss_error_button(cx))
3181            .bg_color(self.error_callout_bg(cx))
3182    }
3183
3184    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
3185        const ERROR_MESSAGE: &str =
3186            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3187
3188        let icon = Icon::new(IconName::XCircle)
3189            .size(IconSize::Small)
3190            .color(Color::Error);
3191
3192        Callout::new()
3193            .icon(icon)
3194            .title("Free Usage Exceeded")
3195            .description(ERROR_MESSAGE)
3196            .tertiary_action(self.upgrade_button(cx))
3197            .secondary_action(self.create_copy_button(ERROR_MESSAGE))
3198            .primary_action(self.dismiss_error_button(cx))
3199            .bg_color(self.error_callout_bg(cx))
3200    }
3201
3202    fn render_model_request_limit_reached_error(
3203        &self,
3204        plan: cloud_llm_client::Plan,
3205        cx: &mut Context<Self>,
3206    ) -> Callout {
3207        let error_message = match plan {
3208            cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3209            cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
3210                "Upgrade to Zed Pro for more prompts."
3211            }
3212        };
3213
3214        let icon = Icon::new(IconName::XCircle)
3215            .size(IconSize::Small)
3216            .color(Color::Error);
3217
3218        Callout::new()
3219            .icon(icon)
3220            .title("Model Prompt Limit Reached")
3221            .description(error_message)
3222            .tertiary_action(self.upgrade_button(cx))
3223            .secondary_action(self.create_copy_button(error_message))
3224            .primary_action(self.dismiss_error_button(cx))
3225            .bg_color(self.error_callout_bg(cx))
3226    }
3227
3228    fn render_tool_use_limit_reached_error(
3229        &self,
3230        window: &mut Window,
3231        cx: &mut Context<Self>,
3232    ) -> Option<Callout> {
3233        let thread = self.as_native_thread(cx)?;
3234        let supports_burn_mode = thread
3235            .read(cx)
3236            .model()
3237            .map_or(false, |model| model.supports_burn_mode());
3238
3239        let focus_handle = self.focus_handle(cx);
3240
3241        let icon = Icon::new(IconName::Info)
3242            .size(IconSize::Small)
3243            .color(Color::Info);
3244
3245        Some(
3246            Callout::new()
3247                .icon(icon)
3248                .title("Consecutive tool use limit reached.")
3249                .when(supports_burn_mode, |this| {
3250                    this.secondary_action(
3251                        Button::new("continue-burn-mode", "Continue with Burn Mode")
3252                            .style(ButtonStyle::Filled)
3253                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3254                            .layer(ElevationIndex::ModalSurface)
3255                            .label_size(LabelSize::Small)
3256                            .key_binding(
3257                                KeyBinding::for_action_in(
3258                                    &ContinueWithBurnMode,
3259                                    &focus_handle,
3260                                    window,
3261                                    cx,
3262                                )
3263                                .map(|kb| kb.size(rems_from_px(10.))),
3264                            )
3265                            .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
3266                            .on_click({
3267                                cx.listener(move |this, _, _window, cx| {
3268                                    thread.update(cx, |thread, _cx| {
3269                                        thread.set_completion_mode(CompletionMode::Burn);
3270                                    });
3271                                    this.resume_chat(cx);
3272                                })
3273                            }),
3274                    )
3275                })
3276                .primary_action(
3277                    Button::new("continue-conversation", "Continue")
3278                        .layer(ElevationIndex::ModalSurface)
3279                        .label_size(LabelSize::Small)
3280                        .key_binding(
3281                            KeyBinding::for_action_in(&ContinueThread, &focus_handle, window, cx)
3282                                .map(|kb| kb.size(rems_from_px(10.))),
3283                        )
3284                        .on_click(cx.listener(|this, _, _window, cx| {
3285                            this.resume_chat(cx);
3286                        })),
3287                ),
3288        )
3289    }
3290
3291    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3292        let message = message.into();
3293
3294        IconButton::new("copy", IconName::Copy)
3295            .icon_size(IconSize::Small)
3296            .icon_color(Color::Muted)
3297            .tooltip(Tooltip::text("Copy Error Message"))
3298            .on_click(move |_, _, cx| {
3299                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3300            })
3301    }
3302
3303    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3304        IconButton::new("dismiss", IconName::Close)
3305            .icon_size(IconSize::Small)
3306            .icon_color(Color::Muted)
3307            .tooltip(Tooltip::text("Dismiss Error"))
3308            .on_click(cx.listener({
3309                move |this, _, _, cx| {
3310                    this.clear_thread_error(cx);
3311                    cx.notify();
3312                }
3313            }))
3314    }
3315
3316    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3317        Button::new("upgrade", "Upgrade")
3318            .label_size(LabelSize::Small)
3319            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3320            .on_click(cx.listener({
3321                move |this, _, _, cx| {
3322                    this.clear_thread_error(cx);
3323                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3324                }
3325            }))
3326    }
3327
3328    fn error_callout_bg(&self, cx: &Context<Self>) -> Hsla {
3329        cx.theme().status().error.opacity(0.08)
3330    }
3331}
3332
3333impl Focusable for AcpThreadView {
3334    fn focus_handle(&self, cx: &App) -> FocusHandle {
3335        self.message_editor.focus_handle(cx)
3336    }
3337}
3338
3339impl Render for AcpThreadView {
3340    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3341        let has_messages = self.list_state.item_count() > 0;
3342
3343        v_flex()
3344            .size_full()
3345            .key_context("AcpThread")
3346            .on_action(cx.listener(Self::open_agent_diff))
3347            .on_action(cx.listener(Self::toggle_burn_mode))
3348            .bg(cx.theme().colors().panel_background)
3349            .child(match &self.thread_state {
3350                ThreadState::Unauthenticated { connection } => v_flex()
3351                    .p_2()
3352                    .flex_1()
3353                    .items_center()
3354                    .justify_center()
3355                    .child(self.render_pending_auth_state())
3356                    .child(h_flex().mt_1p5().justify_center().children(
3357                        connection.auth_methods().into_iter().map(|method| {
3358                            Button::new(
3359                                SharedString::from(method.id.0.clone()),
3360                                method.name.clone(),
3361                            )
3362                            .on_click({
3363                                let method_id = method.id.clone();
3364                                cx.listener(move |this, _, window, cx| {
3365                                    this.authenticate(method_id.clone(), window, cx)
3366                                })
3367                            })
3368                        }),
3369                    )),
3370                ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3371                ThreadState::LoadError(e) => v_flex()
3372                    .p_2()
3373                    .flex_1()
3374                    .items_center()
3375                    .justify_center()
3376                    .child(self.render_load_error(e, cx)),
3377                ThreadState::ServerExited { status } => v_flex()
3378                    .p_2()
3379                    .flex_1()
3380                    .items_center()
3381                    .justify_center()
3382                    .child(self.render_server_exited(*status, cx)),
3383                ThreadState::Ready { thread, .. } => {
3384                    let thread_clone = thread.clone();
3385
3386                    v_flex().flex_1().map(|this| {
3387                        if has_messages {
3388                            this.child(
3389                                list(
3390                                    self.list_state.clone(),
3391                                    cx.processor(|this, index: usize, window, cx| {
3392                                        let Some((entry, len)) = this.thread().and_then(|thread| {
3393                                            let entries = &thread.read(cx).entries();
3394                                            Some((entries.get(index)?, entries.len()))
3395                                        }) else {
3396                                            return Empty.into_any();
3397                                        };
3398                                        this.render_entry(index, len, entry, window, cx)
3399                                    }),
3400                                )
3401                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3402                                .flex_grow()
3403                                .into_any(),
3404                            )
3405                            .child(self.render_vertical_scrollbar(cx))
3406                            .children(
3407                                match thread_clone.read(cx).status() {
3408                                    ThreadStatus::Idle
3409                                    | ThreadStatus::WaitingForToolConfirmation => None,
3410                                    ThreadStatus::Generating => div()
3411                                        .px_5()
3412                                        .py_2()
3413                                        .child(LoadingLabel::new("").size(LabelSize::Small))
3414                                        .into(),
3415                                },
3416                            )
3417                        } else {
3418                            this.child(self.render_empty_state(cx))
3419                        }
3420                    })
3421                }
3422            })
3423            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
3424            // above so that the scrollbar doesn't render behind it. The current setup allows
3425            // the scrollbar to stop exactly at the activity bar start.
3426            .when(has_messages, |this| match &self.thread_state {
3427                ThreadState::Ready { thread, .. } => {
3428                    this.children(self.render_activity_bar(thread, window, cx))
3429                }
3430                _ => this,
3431            })
3432            .children(self.render_thread_error(window, cx))
3433            .child(self.render_message_editor(window, cx))
3434    }
3435}
3436
3437fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
3438    let theme_settings = ThemeSettings::get_global(cx);
3439    let colors = cx.theme().colors();
3440
3441    let buffer_font_size = TextSize::Small.rems(cx);
3442
3443    let mut text_style = window.text_style();
3444    let line_height = buffer_font_size * 1.75;
3445
3446    let font_family = if buffer_font {
3447        theme_settings.buffer_font.family.clone()
3448    } else {
3449        theme_settings.ui_font.family.clone()
3450    };
3451
3452    let font_size = if buffer_font {
3453        TextSize::Small.rems(cx)
3454    } else {
3455        TextSize::Default.rems(cx)
3456    };
3457
3458    text_style.refine(&TextStyleRefinement {
3459        font_family: Some(font_family),
3460        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
3461        font_features: Some(theme_settings.ui_font.features.clone()),
3462        font_size: Some(font_size.into()),
3463        line_height: Some(line_height.into()),
3464        color: Some(cx.theme().colors().text),
3465        ..Default::default()
3466    });
3467
3468    MarkdownStyle {
3469        base_text_style: text_style.clone(),
3470        syntax: cx.theme().syntax().clone(),
3471        selection_background_color: cx.theme().colors().element_selection_background,
3472        code_block_overflow_x_scroll: true,
3473        table_overflow_x_scroll: true,
3474        heading_level_styles: Some(HeadingLevelStyles {
3475            h1: Some(TextStyleRefinement {
3476                font_size: Some(rems(1.15).into()),
3477                ..Default::default()
3478            }),
3479            h2: Some(TextStyleRefinement {
3480                font_size: Some(rems(1.1).into()),
3481                ..Default::default()
3482            }),
3483            h3: Some(TextStyleRefinement {
3484                font_size: Some(rems(1.05).into()),
3485                ..Default::default()
3486            }),
3487            h4: Some(TextStyleRefinement {
3488                font_size: Some(rems(1.).into()),
3489                ..Default::default()
3490            }),
3491            h5: Some(TextStyleRefinement {
3492                font_size: Some(rems(0.95).into()),
3493                ..Default::default()
3494            }),
3495            h6: Some(TextStyleRefinement {
3496                font_size: Some(rems(0.875).into()),
3497                ..Default::default()
3498            }),
3499        }),
3500        code_block: StyleRefinement {
3501            padding: EdgesRefinement {
3502                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3503                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3504                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3505                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3506            },
3507            margin: EdgesRefinement {
3508                top: Some(Length::Definite(Pixels(8.).into())),
3509                left: Some(Length::Definite(Pixels(0.).into())),
3510                right: Some(Length::Definite(Pixels(0.).into())),
3511                bottom: Some(Length::Definite(Pixels(12.).into())),
3512            },
3513            border_style: Some(BorderStyle::Solid),
3514            border_widths: EdgesRefinement {
3515                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
3516                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
3517                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
3518                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
3519            },
3520            border_color: Some(colors.border_variant),
3521            background: Some(colors.editor_background.into()),
3522            text: Some(TextStyleRefinement {
3523                font_family: Some(theme_settings.buffer_font.family.clone()),
3524                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3525                font_features: Some(theme_settings.buffer_font.features.clone()),
3526                font_size: Some(buffer_font_size.into()),
3527                ..Default::default()
3528            }),
3529            ..Default::default()
3530        },
3531        inline_code: TextStyleRefinement {
3532            font_family: Some(theme_settings.buffer_font.family.clone()),
3533            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3534            font_features: Some(theme_settings.buffer_font.features.clone()),
3535            font_size: Some(buffer_font_size.into()),
3536            background_color: Some(colors.editor_foreground.opacity(0.08)),
3537            ..Default::default()
3538        },
3539        link: TextStyleRefinement {
3540            background_color: Some(colors.editor_foreground.opacity(0.025)),
3541            underline: Some(UnderlineStyle {
3542                color: Some(colors.text_accent.opacity(0.5)),
3543                thickness: px(1.),
3544                ..Default::default()
3545            }),
3546            ..Default::default()
3547        },
3548        ..Default::default()
3549    }
3550}
3551
3552fn plan_label_markdown_style(
3553    status: &acp::PlanEntryStatus,
3554    window: &Window,
3555    cx: &App,
3556) -> MarkdownStyle {
3557    let default_md_style = default_markdown_style(false, window, cx);
3558
3559    MarkdownStyle {
3560        base_text_style: TextStyle {
3561            color: cx.theme().colors().text_muted,
3562            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
3563                Some(gpui::StrikethroughStyle {
3564                    thickness: px(1.),
3565                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
3566                })
3567            } else {
3568                None
3569            },
3570            ..default_md_style.base_text_style
3571        },
3572        ..default_md_style
3573    }
3574}
3575
3576fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3577    let default_md_style = default_markdown_style(true, window, cx);
3578
3579    MarkdownStyle {
3580        base_text_style: TextStyle {
3581            ..default_md_style.base_text_style
3582        },
3583        selection_background_color: cx.theme().colors().element_selection_background,
3584        ..Default::default()
3585    }
3586}
3587
3588#[cfg(test)]
3589pub(crate) mod tests {
3590    use acp_thread::StubAgentConnection;
3591    use agent::{TextThreadStore, ThreadStore};
3592    use agent_client_protocol::SessionId;
3593    use editor::EditorSettings;
3594    use fs::FakeFs;
3595    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
3596    use project::Project;
3597    use serde_json::json;
3598    use settings::SettingsStore;
3599    use std::any::Any;
3600    use std::path::Path;
3601    use workspace::Item;
3602
3603    use super::*;
3604
3605    #[gpui::test]
3606    async fn test_drop(cx: &mut TestAppContext) {
3607        init_test(cx);
3608
3609        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3610        let weak_view = thread_view.downgrade();
3611        drop(thread_view);
3612        assert!(!weak_view.is_upgradable());
3613    }
3614
3615    #[gpui::test]
3616    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
3617        init_test(cx);
3618
3619        let (thread_view, cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3620
3621        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3622        message_editor.update_in(cx, |editor, window, cx| {
3623            editor.set_text("Hello", window, cx);
3624        });
3625
3626        cx.deactivate_window();
3627
3628        thread_view.update_in(cx, |thread_view, window, cx| {
3629            thread_view.send(window, cx);
3630        });
3631
3632        cx.run_until_parked();
3633
3634        assert!(
3635            cx.windows()
3636                .iter()
3637                .any(|window| window.downcast::<AgentNotification>().is_some())
3638        );
3639    }
3640
3641    #[gpui::test]
3642    async fn test_notification_for_error(cx: &mut TestAppContext) {
3643        init_test(cx);
3644
3645        let (thread_view, cx) =
3646            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
3647
3648        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3649        message_editor.update_in(cx, |editor, window, cx| {
3650            editor.set_text("Hello", window, cx);
3651        });
3652
3653        cx.deactivate_window();
3654
3655        thread_view.update_in(cx, |thread_view, window, cx| {
3656            thread_view.send(window, cx);
3657        });
3658
3659        cx.run_until_parked();
3660
3661        assert!(
3662            cx.windows()
3663                .iter()
3664                .any(|window| window.downcast::<AgentNotification>().is_some())
3665        );
3666    }
3667
3668    #[gpui::test]
3669    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3670        init_test(cx);
3671
3672        let tool_call_id = acp::ToolCallId("1".into());
3673        let tool_call = acp::ToolCall {
3674            id: tool_call_id.clone(),
3675            title: "Label".into(),
3676            kind: acp::ToolKind::Edit,
3677            status: acp::ToolCallStatus::Pending,
3678            content: vec!["hi".into()],
3679            locations: vec![],
3680            raw_input: None,
3681            raw_output: None,
3682        };
3683        let connection =
3684            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3685                tool_call_id,
3686                vec![acp::PermissionOption {
3687                    id: acp::PermissionOptionId("1".into()),
3688                    name: "Allow".into(),
3689                    kind: acp::PermissionOptionKind::AllowOnce,
3690                }],
3691            )]));
3692
3693        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
3694
3695        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3696
3697        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3698        message_editor.update_in(cx, |editor, window, cx| {
3699            editor.set_text("Hello", window, cx);
3700        });
3701
3702        cx.deactivate_window();
3703
3704        thread_view.update_in(cx, |thread_view, window, cx| {
3705            thread_view.send(window, cx);
3706        });
3707
3708        cx.run_until_parked();
3709
3710        assert!(
3711            cx.windows()
3712                .iter()
3713                .any(|window| window.downcast::<AgentNotification>().is_some())
3714        );
3715    }
3716
3717    async fn setup_thread_view(
3718        agent: impl AgentServer + 'static,
3719        cx: &mut TestAppContext,
3720    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
3721        let fs = FakeFs::new(cx.executor());
3722        let project = Project::test(fs, [], cx).await;
3723        let (workspace, cx) =
3724            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3725
3726        let thread_store =
3727            cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
3728        let text_thread_store =
3729            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
3730
3731        let thread_view = cx.update(|window, cx| {
3732            cx.new(|cx| {
3733                AcpThreadView::new(
3734                    Rc::new(agent),
3735                    workspace.downgrade(),
3736                    project,
3737                    thread_store.clone(),
3738                    text_thread_store.clone(),
3739                    window,
3740                    cx,
3741                )
3742            })
3743        });
3744        cx.run_until_parked();
3745        (thread_view, cx)
3746    }
3747
3748    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
3749        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3750
3751        workspace
3752            .update_in(cx, |workspace, window, cx| {
3753                workspace.add_item_to_active_pane(
3754                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
3755                    None,
3756                    true,
3757                    window,
3758                    cx,
3759                );
3760            })
3761            .unwrap();
3762    }
3763
3764    struct ThreadViewItem(Entity<AcpThreadView>);
3765
3766    impl Item for ThreadViewItem {
3767        type Event = ();
3768
3769        fn include_in_nav_history() -> bool {
3770            false
3771        }
3772
3773        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3774            "Test".into()
3775        }
3776    }
3777
3778    impl EventEmitter<()> for ThreadViewItem {}
3779
3780    impl Focusable for ThreadViewItem {
3781        fn focus_handle(&self, cx: &App) -> FocusHandle {
3782            self.0.read(cx).focus_handle(cx).clone()
3783        }
3784    }
3785
3786    impl Render for ThreadViewItem {
3787        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3788            self.0.clone().into_any_element()
3789        }
3790    }
3791
3792    struct StubAgentServer<C> {
3793        connection: C,
3794    }
3795
3796    impl<C> StubAgentServer<C> {
3797        fn new(connection: C) -> Self {
3798            Self { connection }
3799        }
3800    }
3801
3802    impl StubAgentServer<StubAgentConnection> {
3803        fn default() -> Self {
3804            Self::new(StubAgentConnection::default())
3805        }
3806    }
3807
3808    impl<C> AgentServer for StubAgentServer<C>
3809    where
3810        C: 'static + AgentConnection + Send + Clone,
3811    {
3812        fn logo(&self) -> ui::IconName {
3813            ui::IconName::Ai
3814        }
3815
3816        fn name(&self) -> &'static str {
3817            "Test"
3818        }
3819
3820        fn empty_state_headline(&self) -> &'static str {
3821            "Test"
3822        }
3823
3824        fn empty_state_message(&self) -> &'static str {
3825            "Test"
3826        }
3827
3828        fn connect(
3829            &self,
3830            _root_dir: &Path,
3831            _project: &Entity<Project>,
3832            _cx: &mut App,
3833        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3834            Task::ready(Ok(Rc::new(self.connection.clone())))
3835        }
3836    }
3837
3838    #[derive(Clone)]
3839    struct SaboteurAgentConnection;
3840
3841    impl AgentConnection for SaboteurAgentConnection {
3842        fn new_thread(
3843            self: Rc<Self>,
3844            project: Entity<Project>,
3845            _cwd: &Path,
3846            cx: &mut gpui::App,
3847        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3848            Task::ready(Ok(cx.new(|cx| {
3849                AcpThread::new(
3850                    "SaboteurAgentConnection",
3851                    self,
3852                    project,
3853                    SessionId("test".into()),
3854                    cx,
3855                )
3856            })))
3857        }
3858
3859        fn auth_methods(&self) -> &[acp::AuthMethod] {
3860            &[]
3861        }
3862
3863        fn authenticate(
3864            &self,
3865            _method_id: acp::AuthMethodId,
3866            _cx: &mut App,
3867        ) -> Task<gpui::Result<()>> {
3868            unimplemented!()
3869        }
3870
3871        fn prompt(
3872            &self,
3873            _id: Option<acp_thread::UserMessageId>,
3874            _params: acp::PromptRequest,
3875            _cx: &mut App,
3876        ) -> Task<gpui::Result<acp::PromptResponse>> {
3877            Task::ready(Err(anyhow::anyhow!("Error prompting")))
3878        }
3879
3880        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3881            unimplemented!()
3882        }
3883
3884        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3885            self
3886        }
3887    }
3888
3889    pub(crate) fn init_test(cx: &mut TestAppContext) {
3890        cx.update(|cx| {
3891            let settings_store = SettingsStore::test(cx);
3892            cx.set_global(settings_store);
3893            language::init(cx);
3894            Project::init_settings(cx);
3895            AgentSettings::register(cx);
3896            workspace::init_settings(cx);
3897            ThemeSettings::register(cx);
3898            release_channel::init(SemanticVersion::default(), cx);
3899            EditorSettings::register(cx);
3900        });
3901    }
3902
3903    #[gpui::test]
3904    async fn test_rewind_views(cx: &mut TestAppContext) {
3905        init_test(cx);
3906
3907        let fs = FakeFs::new(cx.executor());
3908        fs.insert_tree(
3909            "/project",
3910            json!({
3911                "test1.txt": "old content 1",
3912                "test2.txt": "old content 2"
3913            }),
3914        )
3915        .await;
3916        let project = Project::test(fs, [Path::new("/project")], cx).await;
3917        let (workspace, cx) =
3918            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3919
3920        let thread_store =
3921            cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
3922        let text_thread_store =
3923            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
3924
3925        let connection = Rc::new(StubAgentConnection::new());
3926        let thread_view = cx.update(|window, cx| {
3927            cx.new(|cx| {
3928                AcpThreadView::new(
3929                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
3930                    workspace.downgrade(),
3931                    project.clone(),
3932                    thread_store.clone(),
3933                    text_thread_store.clone(),
3934                    window,
3935                    cx,
3936                )
3937            })
3938        });
3939
3940        cx.run_until_parked();
3941
3942        let thread = thread_view
3943            .read_with(cx, |view, _| view.thread().cloned())
3944            .unwrap();
3945
3946        // First user message
3947        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
3948            id: acp::ToolCallId("tool1".into()),
3949            title: "Edit file 1".into(),
3950            kind: acp::ToolKind::Edit,
3951            status: acp::ToolCallStatus::Completed,
3952            content: vec![acp::ToolCallContent::Diff {
3953                diff: acp::Diff {
3954                    path: "/project/test1.txt".into(),
3955                    old_text: Some("old content 1".into()),
3956                    new_text: "new content 1".into(),
3957                },
3958            }],
3959            locations: vec![],
3960            raw_input: None,
3961            raw_output: None,
3962        })]);
3963
3964        thread
3965            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
3966            .await
3967            .unwrap();
3968        cx.run_until_parked();
3969
3970        thread.read_with(cx, |thread, _| {
3971            assert_eq!(thread.entries().len(), 2);
3972        });
3973
3974        thread_view.read_with(cx, |view, cx| {
3975            view.entry_view_state.read_with(cx, |entry_view_state, _| {
3976                assert!(
3977                    entry_view_state
3978                        .entry(0)
3979                        .unwrap()
3980                        .message_editor()
3981                        .is_some()
3982                );
3983                assert!(entry_view_state.entry(1).unwrap().has_content());
3984            });
3985        });
3986
3987        // Second user message
3988        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
3989            id: acp::ToolCallId("tool2".into()),
3990            title: "Edit file 2".into(),
3991            kind: acp::ToolKind::Edit,
3992            status: acp::ToolCallStatus::Completed,
3993            content: vec![acp::ToolCallContent::Diff {
3994                diff: acp::Diff {
3995                    path: "/project/test2.txt".into(),
3996                    old_text: Some("old content 2".into()),
3997                    new_text: "new content 2".into(),
3998                },
3999            }],
4000            locations: vec![],
4001            raw_input: None,
4002            raw_output: None,
4003        })]);
4004
4005        thread
4006            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4007            .await
4008            .unwrap();
4009        cx.run_until_parked();
4010
4011        let second_user_message_id = thread.read_with(cx, |thread, _| {
4012            assert_eq!(thread.entries().len(), 4);
4013            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4014                panic!();
4015            };
4016            user_message.id.clone().unwrap()
4017        });
4018
4019        thread_view.read_with(cx, |view, cx| {
4020            view.entry_view_state.read_with(cx, |entry_view_state, _| {
4021                assert!(
4022                    entry_view_state
4023                        .entry(0)
4024                        .unwrap()
4025                        .message_editor()
4026                        .is_some()
4027                );
4028                assert!(entry_view_state.entry(1).unwrap().has_content());
4029                assert!(
4030                    entry_view_state
4031                        .entry(2)
4032                        .unwrap()
4033                        .message_editor()
4034                        .is_some()
4035                );
4036                assert!(entry_view_state.entry(3).unwrap().has_content());
4037            });
4038        });
4039
4040        // Rewind to first message
4041        thread
4042            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4043            .await
4044            .unwrap();
4045
4046        cx.run_until_parked();
4047
4048        thread.read_with(cx, |thread, _| {
4049            assert_eq!(thread.entries().len(), 2);
4050        });
4051
4052        thread_view.read_with(cx, |view, cx| {
4053            view.entry_view_state.read_with(cx, |entry_view_state, _| {
4054                assert!(
4055                    entry_view_state
4056                        .entry(0)
4057                        .unwrap()
4058                        .message_editor()
4059                        .is_some()
4060                );
4061                assert!(entry_view_state.entry(1).unwrap().has_content());
4062
4063                // Old views should be dropped
4064                assert!(entry_view_state.entry(2).is_none());
4065                assert!(entry_view_state.entry(3).is_none());
4066            });
4067        });
4068    }
4069
4070    #[gpui::test]
4071    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4072        init_test(cx);
4073
4074        let connection = StubAgentConnection::new();
4075
4076        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4077            content: acp::ContentBlock::Text(acp::TextContent {
4078                text: "Response".into(),
4079                annotations: None,
4080            }),
4081        }]);
4082
4083        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4084        add_to_workspace(thread_view.clone(), cx);
4085
4086        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4087        message_editor.update_in(cx, |editor, window, cx| {
4088            editor.set_text("Original message to edit", window, cx);
4089        });
4090        thread_view.update_in(cx, |thread_view, window, cx| {
4091            thread_view.send(window, cx);
4092        });
4093
4094        cx.run_until_parked();
4095
4096        let user_message_editor = thread_view.read_with(cx, |view, cx| {
4097            assert_eq!(view.editing_message, None);
4098
4099            view.entry_view_state
4100                .read(cx)
4101                .entry(0)
4102                .unwrap()
4103                .message_editor()
4104                .unwrap()
4105                .clone()
4106        });
4107
4108        // Focus
4109        cx.focus(&user_message_editor);
4110        thread_view.read_with(cx, |view, _cx| {
4111            assert_eq!(view.editing_message, Some(0));
4112        });
4113
4114        // Edit
4115        user_message_editor.update_in(cx, |editor, window, cx| {
4116            editor.set_text("Edited message content", window, cx);
4117        });
4118
4119        // Cancel
4120        user_message_editor.update_in(cx, |_editor, window, cx| {
4121            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4122        });
4123
4124        thread_view.read_with(cx, |view, _cx| {
4125            assert_eq!(view.editing_message, None);
4126        });
4127
4128        user_message_editor.read_with(cx, |editor, cx| {
4129            assert_eq!(editor.text(cx), "Original message to edit");
4130        });
4131    }
4132
4133    #[gpui::test]
4134    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4135        init_test(cx);
4136
4137        let connection = StubAgentConnection::new();
4138
4139        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4140            content: acp::ContentBlock::Text(acp::TextContent {
4141                text: "Response".into(),
4142                annotations: None,
4143            }),
4144        }]);
4145
4146        let (thread_view, cx) =
4147            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4148        add_to_workspace(thread_view.clone(), cx);
4149
4150        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4151        message_editor.update_in(cx, |editor, window, cx| {
4152            editor.set_text("Original message to edit", window, cx);
4153        });
4154        thread_view.update_in(cx, |thread_view, window, cx| {
4155            thread_view.send(window, cx);
4156        });
4157
4158        cx.run_until_parked();
4159
4160        let user_message_editor = thread_view.read_with(cx, |view, cx| {
4161            assert_eq!(view.editing_message, None);
4162            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
4163
4164            view.entry_view_state
4165                .read(cx)
4166                .entry(0)
4167                .unwrap()
4168                .message_editor()
4169                .unwrap()
4170                .clone()
4171        });
4172
4173        // Focus
4174        cx.focus(&user_message_editor);
4175
4176        // Edit
4177        user_message_editor.update_in(cx, |editor, window, cx| {
4178            editor.set_text("Edited message content", window, cx);
4179        });
4180
4181        // Send
4182        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4183            content: acp::ContentBlock::Text(acp::TextContent {
4184                text: "New Response".into(),
4185                annotations: None,
4186            }),
4187        }]);
4188
4189        user_message_editor.update_in(cx, |_editor, window, cx| {
4190            window.dispatch_action(Box::new(Chat), cx);
4191        });
4192
4193        cx.run_until_parked();
4194
4195        thread_view.read_with(cx, |view, cx| {
4196            assert_eq!(view.editing_message, None);
4197
4198            let entries = view.thread().unwrap().read(cx).entries();
4199            assert_eq!(entries.len(), 2);
4200            assert_eq!(
4201                entries[0].to_markdown(cx),
4202                "## User\n\nEdited message content\n\n"
4203            );
4204            assert_eq!(
4205                entries[1].to_markdown(cx),
4206                "## Assistant\n\nNew Response\n\n"
4207            );
4208
4209            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
4210                assert!(!state.entry(1).unwrap().has_content());
4211                state.entry(0).unwrap().message_editor().unwrap().clone()
4212            });
4213
4214            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4215        })
4216    }
4217}