thread_view.rs

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