thread_view.rs

   1use acp_thread::{AgentConnection, Plan};
   2use agent_servers::AgentServer;
   3use std::cell::RefCell;
   4use std::collections::BTreeMap;
   5use std::path::Path;
   6use std::rc::Rc;
   7use std::sync::Arc;
   8use std::time::Duration;
   9
  10use agent_client_protocol as acp;
  11use assistant_tool::ActionLog;
  12use buffer_diff::BufferDiff;
  13use collections::{HashMap, HashSet};
  14use editor::{
  15    AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorMode,
  16    EditorStyle, MinimapVisibility, MultiBuffer, PathKey,
  17};
  18use file_icons::FileIcons;
  19use gpui::{
  20    Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
  21    FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, SharedString, StyleRefinement,
  22    Subscription, Task, TextStyle, TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity,
  23    Window, div, linear_color_stop, linear_gradient, list, percentage, point, prelude::*,
  24    pulsating_between,
  25};
  26use language::language_settings::SoftWrap;
  27use language::{Buffer, Language};
  28use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  29use parking_lot::Mutex;
  30use project::Project;
  31use settings::Settings as _;
  32use text::Anchor;
  33use theme::ThemeSettings;
  34use ui::{Disclosure, Divider, DividerColor, KeyBinding, Tooltip, prelude::*};
  35use util::ResultExt;
  36use workspace::{CollaboratorId, Workspace};
  37use zed_actions::agent::{Chat, NextHistoryMessage, PreviousHistoryMessage};
  38
  39use ::acp_thread::{
  40    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, Diff,
  41    LoadError, MentionPath, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
  42};
  43
  44use crate::acp::completion_provider::{ContextPickerCompletionProvider, MentionSet};
  45use crate::acp::message_history::MessageHistory;
  46use crate::agent_diff::AgentDiff;
  47use crate::message_editor::{MAX_EDITOR_LINES, MIN_EDITOR_LINES};
  48use crate::{AgentDiffPane, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll};
  49
  50const RESPONSE_PADDING_X: Pixels = px(19.);
  51
  52pub struct AcpThreadView {
  53    agent: Rc<dyn AgentServer>,
  54    workspace: WeakEntity<Workspace>,
  55    project: Entity<Project>,
  56    thread_state: ThreadState,
  57    diff_editors: HashMap<EntityId, Entity<Editor>>,
  58    message_editor: Entity<Editor>,
  59    message_set_from_history: bool,
  60    _message_editor_subscription: Subscription,
  61    mention_set: Arc<Mutex<MentionSet>>,
  62    last_error: Option<Entity<Markdown>>,
  63    list_state: ListState,
  64    auth_task: Option<Task<()>>,
  65    expanded_tool_calls: HashSet<acp::ToolCallId>,
  66    expanded_thinking_blocks: HashSet<(usize, usize)>,
  67    edits_expanded: bool,
  68    plan_expanded: bool,
  69    editor_expanded: bool,
  70    message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
  71    _cancel_task: Option<Task<()>>,
  72}
  73
  74enum ThreadState {
  75    Loading {
  76        _task: Task<()>,
  77    },
  78    Ready {
  79        thread: Entity<AcpThread>,
  80        _subscription: [Subscription; 2],
  81    },
  82    LoadError(LoadError),
  83    Unauthenticated {
  84        connection: Rc<dyn AgentConnection>,
  85    },
  86}
  87
  88impl AcpThreadView {
  89    pub fn new(
  90        agent: Rc<dyn AgentServer>,
  91        workspace: WeakEntity<Workspace>,
  92        project: Entity<Project>,
  93        message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
  94        min_lines: usize,
  95        max_lines: Option<usize>,
  96        window: &mut Window,
  97        cx: &mut Context<Self>,
  98    ) -> Self {
  99        let language = Language::new(
 100            language::LanguageConfig {
 101                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
 102                ..Default::default()
 103            },
 104            None,
 105        );
 106
 107        let mention_set = Arc::new(Mutex::new(MentionSet::default()));
 108
 109        let message_editor = cx.new(|cx| {
 110            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
 111            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 112
 113            let mut editor = Editor::new(
 114                editor::EditorMode::AutoHeight {
 115                    min_lines,
 116                    max_lines: max_lines,
 117                },
 118                buffer,
 119                None,
 120                window,
 121                cx,
 122            );
 123            editor.set_placeholder_text("Message the agent - @ to include files", cx);
 124            editor.set_show_indent_guides(false, cx);
 125            editor.set_soft_wrap();
 126            editor.set_use_modal_editing(true);
 127            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
 128                mention_set.clone(),
 129                workspace.clone(),
 130                cx.weak_entity(),
 131            ))));
 132            editor.set_context_menu_options(ContextMenuOptions {
 133                min_entries_visible: 12,
 134                max_entries_visible: 12,
 135                placement: Some(ContextMenuPlacement::Above),
 136            });
 137            editor
 138        });
 139
 140        let message_editor_subscription = cx.subscribe(&message_editor, |this, _, event, _| {
 141            if let editor::EditorEvent::BufferEdited = &event {
 142                if !this.message_set_from_history {
 143                    this.message_history.borrow_mut().reset_position();
 144                }
 145                this.message_set_from_history = false;
 146            }
 147        });
 148
 149        let mention_set = mention_set.clone();
 150
 151        let list_state = ListState::new(
 152            0,
 153            gpui::ListAlignment::Bottom,
 154            px(2048.0),
 155            cx.processor({
 156                move |this: &mut Self, index: usize, window, cx| {
 157                    let Some((entry, len)) = this.thread().and_then(|thread| {
 158                        let entries = &thread.read(cx).entries();
 159                        Some((entries.get(index)?, entries.len()))
 160                    }) else {
 161                        return Empty.into_any();
 162                    };
 163                    this.render_entry(index, len, entry, window, cx)
 164                }
 165            }),
 166        );
 167
 168        Self {
 169            agent: agent.clone(),
 170            workspace: workspace.clone(),
 171            project: project.clone(),
 172            thread_state: Self::initial_state(agent, workspace, project, window, cx),
 173            message_editor,
 174            message_set_from_history: false,
 175            _message_editor_subscription: message_editor_subscription,
 176            mention_set,
 177            diff_editors: Default::default(),
 178            list_state: list_state,
 179            last_error: None,
 180            auth_task: None,
 181            expanded_tool_calls: HashSet::default(),
 182            expanded_thinking_blocks: HashSet::default(),
 183            edits_expanded: false,
 184            plan_expanded: false,
 185            editor_expanded: false,
 186            message_history,
 187            _cancel_task: None,
 188        }
 189    }
 190
 191    fn initial_state(
 192        agent: Rc<dyn AgentServer>,
 193        workspace: WeakEntity<Workspace>,
 194        project: Entity<Project>,
 195        window: &mut Window,
 196        cx: &mut Context<Self>,
 197    ) -> ThreadState {
 198        let root_dir = project
 199            .read(cx)
 200            .visible_worktrees(cx)
 201            .next()
 202            .map(|worktree| worktree.read(cx).abs_path())
 203            .unwrap_or_else(|| paths::home_dir().as_path().into());
 204
 205        let connect_task = agent.connect(&root_dir, &project, cx);
 206        let load_task = cx.spawn_in(window, async move |this, cx| {
 207            let connection = match connect_task.await {
 208                Ok(thread) => thread,
 209                Err(err) => {
 210                    this.update(cx, |this, cx| {
 211                        this.handle_load_error(err, cx);
 212                        cx.notify();
 213                    })
 214                    .log_err();
 215                    return;
 216                }
 217            };
 218
 219            let result = match connection
 220                .clone()
 221                .new_thread(project.clone(), &root_dir, cx)
 222                .await
 223            {
 224                Err(e) => {
 225                    let mut cx = cx.clone();
 226                    if e.downcast_ref::<acp_thread::Unauthenticated>().is_some() {
 227                        this.update(&mut cx, |this, cx| {
 228                            this.thread_state = ThreadState::Unauthenticated { connection };
 229                            cx.notify();
 230                        })
 231                        .ok();
 232                        return;
 233                    } else {
 234                        Err(e)
 235                    }
 236                }
 237                Ok(session_id) => Ok(session_id),
 238            };
 239
 240            this.update_in(cx, |this, window, cx| {
 241                match result {
 242                    Ok(thread) => {
 243                        let thread_subscription =
 244                            cx.subscribe_in(&thread, window, Self::handle_thread_event);
 245
 246                        let action_log = thread.read(cx).action_log().clone();
 247                        let action_log_subscription =
 248                            cx.observe(&action_log, |_, _, cx| cx.notify());
 249
 250                        this.list_state
 251                            .splice(0..0, thread.read(cx).entries().len());
 252
 253                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 254
 255                        this.thread_state = ThreadState::Ready {
 256                            thread,
 257                            _subscription: [thread_subscription, action_log_subscription],
 258                        };
 259
 260                        cx.notify();
 261                    }
 262                    Err(err) => {
 263                        this.handle_load_error(err, cx);
 264                    }
 265                };
 266            })
 267            .log_err();
 268        });
 269
 270        ThreadState::Loading { _task: load_task }
 271    }
 272
 273    fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
 274        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 275            self.thread_state = ThreadState::LoadError(load_err.clone());
 276        } else {
 277            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 278        }
 279        cx.notify();
 280    }
 281
 282    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 283        match &self.thread_state {
 284            ThreadState::Ready { thread, .. } => Some(thread),
 285            ThreadState::Unauthenticated { .. }
 286            | ThreadState::Loading { .. }
 287            | ThreadState::LoadError(..) => None,
 288        }
 289    }
 290
 291    pub fn title(&self, cx: &App) -> SharedString {
 292        match &self.thread_state {
 293            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
 294            ThreadState::Loading { .. } => "Loading…".into(),
 295            ThreadState::LoadError(_) => "Failed to load".into(),
 296            ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
 297        }
 298    }
 299
 300    pub fn cancel(&mut self, cx: &mut Context<Self>) {
 301        self.last_error.take();
 302
 303        if let Some(thread) = self.thread() {
 304            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 305        }
 306    }
 307
 308    pub fn expand_message_editor(
 309        &mut self,
 310        _: &ExpandMessageEditor,
 311        _window: &mut Window,
 312        cx: &mut Context<Self>,
 313    ) {
 314        self.set_editor_is_expanded(!self.editor_expanded, cx);
 315        cx.notify();
 316    }
 317
 318    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 319        self.editor_expanded = is_expanded;
 320        self.message_editor.update(cx, |editor, _| {
 321            if self.editor_expanded {
 322                editor.set_mode(EditorMode::Full {
 323                    scale_ui_elements_with_buffer_font_size: false,
 324                    show_active_line_background: false,
 325                    sized_by_content: false,
 326                })
 327            } else {
 328                editor.set_mode(EditorMode::AutoHeight {
 329                    min_lines: MIN_EDITOR_LINES,
 330                    max_lines: Some(MAX_EDITOR_LINES),
 331                })
 332            }
 333        });
 334        cx.notify();
 335    }
 336
 337    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 338        self.last_error.take();
 339
 340        let mut ix = 0;
 341        let mut chunks: Vec<acp::ContentBlock> = Vec::new();
 342        let project = self.project.clone();
 343        self.message_editor.update(cx, |editor, cx| {
 344            let text = editor.text(cx);
 345            editor.display_map.update(cx, |map, cx| {
 346                let snapshot = map.snapshot(cx);
 347                for (crease_id, crease) in snapshot.crease_snapshot.creases() {
 348                    if let Some(project_path) =
 349                        self.mention_set.lock().path_for_crease_id(crease_id)
 350                    {
 351                        let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
 352                        if crease_range.start > ix {
 353                            chunks.push(text[ix..crease_range.start].into());
 354                        }
 355                        if let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) {
 356                            let path_str = abs_path.display().to_string();
 357                            chunks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink {
 358                                uri: path_str.clone(),
 359                                name: path_str,
 360                                annotations: None,
 361                                description: None,
 362                                mime_type: None,
 363                                size: None,
 364                                title: None,
 365                            }));
 366                        }
 367                        ix = crease_range.end;
 368                    }
 369                }
 370
 371                if ix < text.len() {
 372                    let last_chunk = text[ix..].trim();
 373                    if !last_chunk.is_empty() {
 374                        chunks.push(last_chunk.into());
 375                    }
 376                }
 377            })
 378        });
 379
 380        if chunks.is_empty() {
 381            return;
 382        }
 383
 384        let Some(thread) = self.thread() else { return };
 385        let task = thread.update(cx, |thread, cx| thread.send(chunks.clone(), cx));
 386
 387        cx.spawn(async move |this, cx| {
 388            let result = task.await;
 389
 390            this.update(cx, |this, cx| {
 391                if let Err(err) = result {
 392                    this.last_error =
 393                        Some(cx.new(|cx| Markdown::new(err.to_string().into(), None, None, cx)))
 394                }
 395            })
 396        })
 397        .detach();
 398
 399        let mention_set = self.mention_set.clone();
 400
 401        self.set_editor_is_expanded(false, cx);
 402        self.message_editor.update(cx, |editor, cx| {
 403            editor.clear(window, cx);
 404            editor.remove_creases(mention_set.lock().drain(), cx)
 405        });
 406
 407        self.message_history.borrow_mut().push(chunks);
 408    }
 409
 410    fn previous_history_message(
 411        &mut self,
 412        _: &PreviousHistoryMessage,
 413        window: &mut Window,
 414        cx: &mut Context<Self>,
 415    ) {
 416        self.message_set_from_history = Self::set_draft_message(
 417            self.message_editor.clone(),
 418            self.mention_set.clone(),
 419            self.project.clone(),
 420            self.message_history.borrow_mut().prev(),
 421            window,
 422            cx,
 423        );
 424    }
 425
 426    fn next_history_message(
 427        &mut self,
 428        _: &NextHistoryMessage,
 429        window: &mut Window,
 430        cx: &mut Context<Self>,
 431    ) {
 432        self.message_set_from_history = Self::set_draft_message(
 433            self.message_editor.clone(),
 434            self.mention_set.clone(),
 435            self.project.clone(),
 436            self.message_history.borrow_mut().next(),
 437            window,
 438            cx,
 439        );
 440    }
 441
 442    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
 443        if let Some(thread) = self.thread() {
 444            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
 445        }
 446    }
 447
 448    fn open_edited_buffer(
 449        &mut self,
 450        buffer: &Entity<Buffer>,
 451        window: &mut Window,
 452        cx: &mut Context<Self>,
 453    ) {
 454        let Some(thread) = self.thread() else {
 455            return;
 456        };
 457
 458        let Some(diff) =
 459            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
 460        else {
 461            return;
 462        };
 463
 464        diff.update(cx, |diff, cx| {
 465            diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
 466        })
 467    }
 468
 469    fn set_draft_message(
 470        message_editor: Entity<Editor>,
 471        mention_set: Arc<Mutex<MentionSet>>,
 472        project: Entity<Project>,
 473        message: Option<&Vec<acp::ContentBlock>>,
 474        window: &mut Window,
 475        cx: &mut Context<Self>,
 476    ) -> bool {
 477        cx.notify();
 478
 479        let Some(message) = message else {
 480            return false;
 481        };
 482
 483        let mut text = String::new();
 484        let mut mentions = Vec::new();
 485
 486        for chunk in message {
 487            match chunk {
 488                acp::ContentBlock::Text(text_content) => {
 489                    text.push_str(&text_content.text);
 490                }
 491                acp::ContentBlock::ResourceLink(resource_link) => {
 492                    let path = Path::new(&resource_link.uri);
 493                    let start = text.len();
 494                    let content = MentionPath::new(&path).to_string();
 495                    text.push_str(&content);
 496                    let end = text.len();
 497                    if let Some(project_path) =
 498                        project.read(cx).project_path_for_absolute_path(&path, cx)
 499                    {
 500                        let filename: SharedString = path
 501                            .file_name()
 502                            .unwrap_or_default()
 503                            .to_string_lossy()
 504                            .to_string()
 505                            .into();
 506                        mentions.push((start..end, project_path, filename));
 507                    }
 508                }
 509                acp::ContentBlock::Image(_)
 510                | acp::ContentBlock::Audio(_)
 511                | acp::ContentBlock::Resource(_) => {}
 512            }
 513        }
 514
 515        let snapshot = message_editor.update(cx, |editor, cx| {
 516            editor.set_text(text, window, cx);
 517            editor.buffer().read(cx).snapshot(cx)
 518        });
 519
 520        for (range, project_path, filename) in mentions {
 521            let crease_icon_path = if project_path.path.is_dir() {
 522                FileIcons::get_folder_icon(false, cx)
 523                    .unwrap_or_else(|| IconName::Folder.path().into())
 524            } else {
 525                FileIcons::get_icon(Path::new(project_path.path.as_ref()), cx)
 526                    .unwrap_or_else(|| IconName::File.path().into())
 527            };
 528
 529            let anchor = snapshot.anchor_before(range.start);
 530            let crease_id = crate::context_picker::insert_crease_for_mention(
 531                anchor.excerpt_id,
 532                anchor.text_anchor,
 533                range.end - range.start,
 534                filename,
 535                crease_icon_path,
 536                message_editor.clone(),
 537                window,
 538                cx,
 539            );
 540            if let Some(crease_id) = crease_id {
 541                mention_set.lock().insert(crease_id, project_path);
 542            }
 543        }
 544
 545        true
 546    }
 547
 548    fn handle_thread_event(
 549        &mut self,
 550        thread: &Entity<AcpThread>,
 551        event: &AcpThreadEvent,
 552        window: &mut Window,
 553        cx: &mut Context<Self>,
 554    ) {
 555        let count = self.list_state.item_count();
 556        match event {
 557            AcpThreadEvent::NewEntry => {
 558                let index = thread.read(cx).entries().len() - 1;
 559                self.sync_thread_entry_view(index, window, cx);
 560                self.list_state.splice(count..count, 1);
 561            }
 562            AcpThreadEvent::EntryUpdated(index) => {
 563                let index = *index;
 564                self.sync_thread_entry_view(index, window, cx);
 565                self.list_state.splice(index..index + 1, 1);
 566            }
 567        }
 568        cx.notify();
 569    }
 570
 571    fn sync_thread_entry_view(
 572        &mut self,
 573        entry_ix: usize,
 574        window: &mut Window,
 575        cx: &mut Context<Self>,
 576    ) {
 577        let Some(multibuffer) = self.entry_diff_multibuffer(entry_ix, cx) else {
 578            return;
 579        };
 580
 581        if self.diff_editors.contains_key(&multibuffer.entity_id()) {
 582            return;
 583        }
 584
 585        let editor = cx.new(|cx| {
 586            let mut editor = Editor::new(
 587                EditorMode::Full {
 588                    scale_ui_elements_with_buffer_font_size: false,
 589                    show_active_line_background: false,
 590                    sized_by_content: true,
 591                },
 592                multibuffer.clone(),
 593                None,
 594                window,
 595                cx,
 596            );
 597            editor.set_show_gutter(false, cx);
 598            editor.disable_inline_diagnostics();
 599            editor.disable_expand_excerpt_buttons(cx);
 600            editor.set_show_vertical_scrollbar(false, cx);
 601            editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
 602            editor.set_soft_wrap_mode(SoftWrap::None, cx);
 603            editor.scroll_manager.set_forbid_vertical_scroll(true);
 604            editor.set_show_indent_guides(false, cx);
 605            editor.set_read_only(true);
 606            editor.set_show_breakpoints(false, cx);
 607            editor.set_show_code_actions(false, cx);
 608            editor.set_show_git_diff_gutter(false, cx);
 609            editor.set_expand_all_diff_hunks(cx);
 610            editor.set_text_style_refinement(TextStyleRefinement {
 611                font_size: Some(
 612                    TextSize::Small
 613                        .rems(cx)
 614                        .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
 615                        .into(),
 616                ),
 617                ..Default::default()
 618            });
 619            editor
 620        });
 621        let entity_id = multibuffer.entity_id();
 622        cx.observe_release(&multibuffer, move |this, _, _| {
 623            this.diff_editors.remove(&entity_id);
 624        })
 625        .detach();
 626
 627        self.diff_editors.insert(entity_id, editor);
 628    }
 629
 630    fn entry_diff_multibuffer(&self, entry_ix: usize, cx: &App) -> Option<Entity<MultiBuffer>> {
 631        let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
 632        entry.first_diff().map(|diff| diff.multibuffer.clone())
 633    }
 634
 635    fn authenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 636        let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
 637            return;
 638        };
 639
 640        self.last_error.take();
 641        let authenticate = connection.authenticate(cx);
 642        self.auth_task = Some(cx.spawn_in(window, {
 643            let project = self.project.clone();
 644            let agent = self.agent.clone();
 645            async move |this, cx| {
 646                let result = authenticate.await;
 647
 648                this.update_in(cx, |this, window, cx| {
 649                    if let Err(err) = result {
 650                        this.last_error = Some(cx.new(|cx| {
 651                            Markdown::new(format!("Error: {err}").into(), None, None, cx)
 652                        }))
 653                    } else {
 654                        this.thread_state = Self::initial_state(
 655                            agent,
 656                            this.workspace.clone(),
 657                            project.clone(),
 658                            window,
 659                            cx,
 660                        )
 661                    }
 662                    this.auth_task.take()
 663                })
 664                .ok();
 665            }
 666        }));
 667    }
 668
 669    fn authorize_tool_call(
 670        &mut self,
 671        tool_call_id: acp::ToolCallId,
 672        option_id: acp::PermissionOptionId,
 673        option_kind: acp::PermissionOptionKind,
 674        cx: &mut Context<Self>,
 675    ) {
 676        let Some(thread) = self.thread() else {
 677            return;
 678        };
 679        thread.update(cx, |thread, cx| {
 680            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
 681        });
 682        cx.notify();
 683    }
 684
 685    fn render_entry(
 686        &self,
 687        index: usize,
 688        total_entries: usize,
 689        entry: &AgentThreadEntry,
 690        window: &mut Window,
 691        cx: &Context<Self>,
 692    ) -> AnyElement {
 693        match &entry {
 694            AgentThreadEntry::UserMessage(message) => div()
 695                .py_4()
 696                .px_2()
 697                .child(
 698                    v_flex()
 699                        .p_3()
 700                        .gap_1p5()
 701                        .rounded_lg()
 702                        .shadow_md()
 703                        .bg(cx.theme().colors().editor_background)
 704                        .border_1()
 705                        .border_color(cx.theme().colors().border)
 706                        .text_xs()
 707                        .children(message.content.markdown().map(|md| {
 708                            self.render_markdown(
 709                                md.clone(),
 710                                user_message_markdown_style(window, cx),
 711                            )
 712                        })),
 713                )
 714                .into_any(),
 715            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
 716                let style = default_markdown_style(false, window, cx);
 717                let message_body = v_flex()
 718                    .w_full()
 719                    .gap_2p5()
 720                    .children(chunks.iter().enumerate().filter_map(
 721                        |(chunk_ix, chunk)| match chunk {
 722                            AssistantMessageChunk::Message { block } => {
 723                                block.markdown().map(|md| {
 724                                    self.render_markdown(md.clone(), style.clone())
 725                                        .into_any_element()
 726                                })
 727                            }
 728                            AssistantMessageChunk::Thought { block } => {
 729                                block.markdown().map(|md| {
 730                                    self.render_thinking_block(
 731                                        index,
 732                                        chunk_ix,
 733                                        md.clone(),
 734                                        window,
 735                                        cx,
 736                                    )
 737                                    .into_any_element()
 738                                })
 739                            }
 740                        },
 741                    ))
 742                    .into_any();
 743
 744                v_flex()
 745                    .px_5()
 746                    .py_1()
 747                    .when(index + 1 == total_entries, |this| this.pb_4())
 748                    .w_full()
 749                    .text_ui(cx)
 750                    .child(message_body)
 751                    .into_any()
 752            }
 753            AgentThreadEntry::ToolCall(tool_call) => div()
 754                .py_1p5()
 755                .px_5()
 756                .child(self.render_tool_call(index, tool_call, window, cx))
 757                .into_any(),
 758        }
 759    }
 760
 761    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
 762        cx.theme()
 763            .colors()
 764            .element_background
 765            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
 766    }
 767
 768    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
 769        cx.theme().colors().border.opacity(0.6)
 770    }
 771
 772    fn tool_name_font_size(&self) -> Rems {
 773        rems_from_px(13.)
 774    }
 775
 776    fn render_thinking_block(
 777        &self,
 778        entry_ix: usize,
 779        chunk_ix: usize,
 780        chunk: Entity<Markdown>,
 781        window: &Window,
 782        cx: &Context<Self>,
 783    ) -> AnyElement {
 784        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
 785        let key = (entry_ix, chunk_ix);
 786        let is_open = self.expanded_thinking_blocks.contains(&key);
 787
 788        v_flex()
 789            .child(
 790                h_flex()
 791                    .id(header_id)
 792                    .group("disclosure-header")
 793                    .w_full()
 794                    .justify_between()
 795                    .opacity(0.8)
 796                    .hover(|style| style.opacity(1.))
 797                    .child(
 798                        h_flex()
 799                            .gap_1p5()
 800                            .child(
 801                                Icon::new(IconName::ToolBulb)
 802                                    .size(IconSize::Small)
 803                                    .color(Color::Muted),
 804                            )
 805                            .child(
 806                                div()
 807                                    .text_size(self.tool_name_font_size())
 808                                    .child("Thinking"),
 809                            ),
 810                    )
 811                    .child(
 812                        div().visible_on_hover("disclosure-header").child(
 813                            Disclosure::new("thinking-disclosure", is_open)
 814                                .opened_icon(IconName::ChevronUp)
 815                                .closed_icon(IconName::ChevronDown)
 816                                .on_click(cx.listener({
 817                                    move |this, _event, _window, cx| {
 818                                        if is_open {
 819                                            this.expanded_thinking_blocks.remove(&key);
 820                                        } else {
 821                                            this.expanded_thinking_blocks.insert(key);
 822                                        }
 823                                        cx.notify();
 824                                    }
 825                                })),
 826                        ),
 827                    )
 828                    .on_click(cx.listener({
 829                        move |this, _event, _window, cx| {
 830                            if is_open {
 831                                this.expanded_thinking_blocks.remove(&key);
 832                            } else {
 833                                this.expanded_thinking_blocks.insert(key);
 834                            }
 835                            cx.notify();
 836                        }
 837                    })),
 838            )
 839            .when(is_open, |this| {
 840                this.child(
 841                    div()
 842                        .relative()
 843                        .mt_1p5()
 844                        .ml(px(7.))
 845                        .pl_4()
 846                        .border_l_1()
 847                        .border_color(self.tool_card_border_color(cx))
 848                        .text_ui_sm(cx)
 849                        .child(
 850                            self.render_markdown(chunk, default_markdown_style(false, window, cx)),
 851                        ),
 852                )
 853            })
 854            .into_any_element()
 855    }
 856
 857    fn render_tool_call(
 858        &self,
 859        entry_ix: usize,
 860        tool_call: &ToolCall,
 861        window: &Window,
 862        cx: &Context<Self>,
 863    ) -> Div {
 864        let header_id = SharedString::from(format!("tool-call-header-{}", entry_ix));
 865
 866        let status_icon = match &tool_call.status {
 867            ToolCallStatus::WaitingForConfirmation { .. } => None,
 868            ToolCallStatus::Allowed {
 869                status: acp::ToolCallStatus::InProgress,
 870                ..
 871            } => Some(
 872                Icon::new(IconName::ArrowCircle)
 873                    .color(Color::Accent)
 874                    .size(IconSize::Small)
 875                    .with_animation(
 876                        "running",
 877                        Animation::new(Duration::from_secs(2)).repeat(),
 878                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
 879                    )
 880                    .into_any(),
 881            ),
 882            ToolCallStatus::Allowed {
 883                status: acp::ToolCallStatus::Completed,
 884                ..
 885            } => None,
 886            ToolCallStatus::Rejected
 887            | ToolCallStatus::Canceled
 888            | ToolCallStatus::Allowed {
 889                status: acp::ToolCallStatus::Failed,
 890                ..
 891            } => Some(
 892                Icon::new(IconName::X)
 893                    .color(Color::Error)
 894                    .size(IconSize::Small)
 895                    .into_any_element(),
 896            ),
 897        };
 898
 899        let needs_confirmation = match &tool_call.status {
 900            ToolCallStatus::WaitingForConfirmation { .. } => true,
 901            _ => tool_call
 902                .content
 903                .iter()
 904                .any(|content| matches!(content, ToolCallContent::Diff { .. })),
 905        };
 906
 907        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
 908        let is_open = !is_collapsible || self.expanded_tool_calls.contains(&tool_call.id);
 909
 910        v_flex()
 911            .when(needs_confirmation, |this| {
 912                this.rounded_lg()
 913                    .border_1()
 914                    .border_color(self.tool_card_border_color(cx))
 915                    .bg(cx.theme().colors().editor_background)
 916                    .overflow_hidden()
 917            })
 918            .child(
 919                h_flex()
 920                    .id(header_id)
 921                    .w_full()
 922                    .gap_1()
 923                    .justify_between()
 924                    .map(|this| {
 925                        if needs_confirmation {
 926                            this.px_2()
 927                                .py_1()
 928                                .rounded_t_md()
 929                                .bg(self.tool_card_header_bg(cx))
 930                                .border_b_1()
 931                                .border_color(self.tool_card_border_color(cx))
 932                        } else {
 933                            this.opacity(0.8).hover(|style| style.opacity(1.))
 934                        }
 935                    })
 936                    .child(
 937                        h_flex()
 938                            .id("tool-call-header")
 939                            .overflow_x_scroll()
 940                            .map(|this| {
 941                                if needs_confirmation {
 942                                    this.text_xs()
 943                                } else {
 944                                    this.text_size(self.tool_name_font_size())
 945                                }
 946                            })
 947                            .gap_1p5()
 948                            .child(
 949                                Icon::new(match tool_call.kind {
 950                                    acp::ToolKind::Read => IconName::ToolRead,
 951                                    acp::ToolKind::Edit => IconName::ToolPencil,
 952                                    acp::ToolKind::Search => IconName::ToolSearch,
 953                                    acp::ToolKind::Execute => IconName::ToolTerminal,
 954                                    acp::ToolKind::Think => IconName::ToolBulb,
 955                                    acp::ToolKind::Fetch => IconName::ToolWeb,
 956                                    acp::ToolKind::Other => IconName::ToolHammer,
 957                                })
 958                                .size(IconSize::Small)
 959                                .color(Color::Muted),
 960                            )
 961                            .child(if tool_call.locations.len() == 1 {
 962                                let name = tool_call.locations[0]
 963                                    .path
 964                                    .file_name()
 965                                    .unwrap_or_default()
 966                                    .display()
 967                                    .to_string();
 968
 969                                h_flex()
 970                                    .id(("open-tool-call-location", entry_ix))
 971                                    .child(name)
 972                                    .w_full()
 973                                    .max_w_full()
 974                                    .pr_1()
 975                                    .gap_0p5()
 976                                    .cursor_pointer()
 977                                    .rounded_sm()
 978                                    .opacity(0.8)
 979                                    .hover(|label| {
 980                                        label.opacity(1.).bg(cx
 981                                            .theme()
 982                                            .colors()
 983                                            .element_hover
 984                                            .opacity(0.5))
 985                                    })
 986                                    .tooltip(Tooltip::text("Jump to File"))
 987                                    .on_click(cx.listener(move |this, _, window, cx| {
 988                                        this.open_tool_call_location(entry_ix, 0, window, cx);
 989                                    }))
 990                                    .into_any_element()
 991                            } else {
 992                                self.render_markdown(
 993                                    tool_call.label.clone(),
 994                                    default_markdown_style(needs_confirmation, window, cx),
 995                                )
 996                                .into_any()
 997                            }),
 998                    )
 999                    .child(
1000                        h_flex()
1001                            .gap_0p5()
1002                            .when(is_collapsible, |this| {
1003                                this.child(
1004                                    Disclosure::new(("expand", entry_ix), is_open)
1005                                        .opened_icon(IconName::ChevronUp)
1006                                        .closed_icon(IconName::ChevronDown)
1007                                        .on_click(cx.listener({
1008                                            let id = tool_call.id.clone();
1009                                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1010                                                if is_open {
1011                                                    this.expanded_tool_calls.remove(&id);
1012                                                } else {
1013                                                    this.expanded_tool_calls.insert(id.clone());
1014                                                }
1015                                                cx.notify();
1016                                            }
1017                                        })),
1018                                )
1019                            })
1020                            .children(status_icon),
1021                    )
1022                    .on_click(cx.listener({
1023                        let id = tool_call.id.clone();
1024                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1025                            if is_open {
1026                                this.expanded_tool_calls.remove(&id);
1027                            } else {
1028                                this.expanded_tool_calls.insert(id.clone());
1029                            }
1030                            cx.notify();
1031                        }
1032                    })),
1033            )
1034            .when(is_open, |this| {
1035                this.child(
1036                    v_flex()
1037                        .text_xs()
1038                        .when(is_collapsible, |this| {
1039                            this.mt_1()
1040                                .border_1()
1041                                .border_color(self.tool_card_border_color(cx))
1042                                .bg(cx.theme().colors().editor_background)
1043                                .rounded_lg()
1044                        })
1045                        .map(|this| {
1046                            if is_open {
1047                                match &tool_call.status {
1048                                    ToolCallStatus::WaitingForConfirmation { options, .. } => this
1049                                        .children(tool_call.content.iter().map(|content| {
1050                                            div()
1051                                                .py_1p5()
1052                                                .child(
1053                                                    self.render_tool_call_content(
1054                                                        content, window, cx,
1055                                                    ),
1056                                                )
1057                                                .into_any_element()
1058                                        }))
1059                                        // todo! confirm this looks ok
1060                                        .child(self.render_permission_buttons(
1061                                            options,
1062                                            entry_ix,
1063                                            tool_call.id.clone(),
1064                                            cx,
1065                                        )),
1066                                    ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1067                                        this.children(tool_call.content.iter().map(|content| {
1068                                            div()
1069                                                .py_1p5()
1070                                                .child(
1071                                                    self.render_tool_call_content(
1072                                                        content, window, cx,
1073                                                    ),
1074                                                )
1075                                                .into_any_element()
1076                                        }))
1077                                    }
1078                                    ToolCallStatus::Rejected => this,
1079                                }
1080                            } else {
1081                                this
1082                            }
1083                        }),
1084                )
1085            })
1086    }
1087
1088    fn render_tool_call_content(
1089        &self,
1090        content: &ToolCallContent,
1091        window: &Window,
1092        cx: &Context<Self>,
1093    ) -> AnyElement {
1094        match content {
1095            ToolCallContent::ContentBlock { content } => {
1096                if let Some(md) = content.markdown() {
1097                    div()
1098                        .p_2()
1099                        .child(
1100                            self.render_markdown(
1101                                md.clone(),
1102                                default_markdown_style(false, window, cx),
1103                            ),
1104                        )
1105                        .into_any_element()
1106                } else {
1107                    Empty.into_any_element()
1108                }
1109            }
1110            ToolCallContent::Diff {
1111                diff: Diff { multibuffer, .. },
1112                ..
1113            } => self.render_diff_editor(multibuffer),
1114        }
1115    }
1116
1117    fn render_permission_buttons(
1118        &self,
1119        options: &[acp::PermissionOption],
1120        entry_ix: usize,
1121        tool_call_id: acp::ToolCallId,
1122        cx: &Context<Self>,
1123    ) -> Div {
1124        h_flex()
1125            .pt_1p5()
1126            .px_1p5()
1127            .gap_1()
1128            .justify_end()
1129            .border_t_1()
1130            .border_color(self.tool_card_border_color(cx))
1131            .children(options.iter().map(|option| {
1132                let option_id = SharedString::from(option.id.0.clone());
1133                Button::new((option_id, entry_ix), option.label.clone())
1134                    .map(|this| match option.kind {
1135                        acp::PermissionOptionKind::AllowOnce => {
1136                            this.icon(IconName::Check).icon_color(Color::Success)
1137                        }
1138                        acp::PermissionOptionKind::AllowAlways => {
1139                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1140                        }
1141                        acp::PermissionOptionKind::RejectOnce => {
1142                            this.icon(IconName::X).icon_color(Color::Error)
1143                        }
1144                        acp::PermissionOptionKind::RejectAlways => {
1145                            this.icon(IconName::X).icon_color(Color::Error)
1146                        }
1147                    })
1148                    .icon_position(IconPosition::Start)
1149                    .icon_size(IconSize::XSmall)
1150                    .on_click(cx.listener({
1151                        let tool_call_id = tool_call_id.clone();
1152                        let option_id = option.id.clone();
1153                        let option_kind = option.kind;
1154                        move |this, _, _, cx| {
1155                            this.authorize_tool_call(
1156                                tool_call_id.clone(),
1157                                option_id.clone(),
1158                                option_kind,
1159                                cx,
1160                            );
1161                        }
1162                    }))
1163            }))
1164    }
1165
1166    fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1167        v_flex()
1168            .h_full()
1169            .child(
1170                if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1171                    editor.clone().into_any_element()
1172                } else {
1173                    Empty.into_any()
1174                },
1175            )
1176            .into_any()
1177    }
1178
1179    fn render_agent_logo(&self) -> AnyElement {
1180        Icon::new(self.agent.logo())
1181            .color(Color::Muted)
1182            .size(IconSize::XLarge)
1183            .into_any_element()
1184    }
1185
1186    fn render_error_agent_logo(&self) -> AnyElement {
1187        let logo = Icon::new(self.agent.logo())
1188            .color(Color::Muted)
1189            .size(IconSize::XLarge)
1190            .into_any_element();
1191
1192        h_flex()
1193            .relative()
1194            .justify_center()
1195            .child(div().opacity(0.3).child(logo))
1196            .child(
1197                h_flex().absolute().right_1().bottom_0().child(
1198                    Icon::new(IconName::XCircle)
1199                        .color(Color::Error)
1200                        .size(IconSize::Small),
1201                ),
1202            )
1203            .into_any_element()
1204    }
1205
1206    fn render_empty_state(&self, cx: &App) -> AnyElement {
1207        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1208
1209        v_flex()
1210            .size_full()
1211            .items_center()
1212            .justify_center()
1213            .child(if loading {
1214                h_flex()
1215                    .justify_center()
1216                    .child(self.render_agent_logo())
1217                    .with_animation(
1218                        "pulsating_icon",
1219                        Animation::new(Duration::from_secs(2))
1220                            .repeat()
1221                            .with_easing(pulsating_between(0.4, 1.0)),
1222                        |icon, delta| icon.opacity(delta),
1223                    )
1224                    .into_any()
1225            } else {
1226                self.render_agent_logo().into_any_element()
1227            })
1228            .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1229                div()
1230                    .child(LoadingLabel::new("").size(LabelSize::Large))
1231                    .into_any_element()
1232            } else {
1233                Headline::new(self.agent.empty_state_headline())
1234                    .size(HeadlineSize::Medium)
1235                    .into_any_element()
1236            }))
1237            .child(
1238                div()
1239                    .max_w_1_2()
1240                    .text_sm()
1241                    .text_center()
1242                    .map(|this| {
1243                        if loading {
1244                            this.invisible()
1245                        } else {
1246                            this.text_color(cx.theme().colors().text_muted)
1247                        }
1248                    })
1249                    .child(self.agent.empty_state_message()),
1250            )
1251            .into_any()
1252    }
1253
1254    fn render_pending_auth_state(&self) -> AnyElement {
1255        v_flex()
1256            .items_center()
1257            .justify_center()
1258            .child(self.render_error_agent_logo())
1259            .child(
1260                h_flex()
1261                    .mt_4()
1262                    .mb_1()
1263                    .justify_center()
1264                    .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1265            )
1266            .into_any()
1267    }
1268
1269    fn render_error_state(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1270        let mut container = v_flex()
1271            .items_center()
1272            .justify_center()
1273            .child(self.render_error_agent_logo())
1274            .child(
1275                v_flex()
1276                    .mt_4()
1277                    .mb_2()
1278                    .gap_0p5()
1279                    .text_center()
1280                    .items_center()
1281                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1282                    .child(
1283                        Label::new(e.to_string())
1284                            .size(LabelSize::Small)
1285                            .color(Color::Muted),
1286                    ),
1287            );
1288
1289        if let LoadError::Unsupported {
1290            upgrade_message,
1291            upgrade_command,
1292            ..
1293        } = &e
1294        {
1295            let upgrade_message = upgrade_message.clone();
1296            let upgrade_command = upgrade_command.clone();
1297            container = container.child(Button::new("upgrade", upgrade_message).on_click(
1298                cx.listener(move |this, _, window, cx| {
1299                    this.workspace
1300                        .update(cx, |workspace, cx| {
1301                            let project = workspace.project().read(cx);
1302                            let cwd = project.first_project_directory(cx);
1303                            let shell = project.terminal_settings(&cwd, cx).shell.clone();
1304                            let spawn_in_terminal = task::SpawnInTerminal {
1305                                id: task::TaskId("install".to_string()),
1306                                full_label: upgrade_command.clone(),
1307                                label: upgrade_command.clone(),
1308                                command: Some(upgrade_command.clone()),
1309                                args: Vec::new(),
1310                                command_label: upgrade_command.clone(),
1311                                cwd,
1312                                env: Default::default(),
1313                                use_new_terminal: true,
1314                                allow_concurrent_runs: true,
1315                                reveal: Default::default(),
1316                                reveal_target: Default::default(),
1317                                hide: Default::default(),
1318                                shell,
1319                                show_summary: true,
1320                                show_command: true,
1321                                show_rerun: false,
1322                            };
1323                            workspace
1324                                .spawn_in_terminal(spawn_in_terminal, window, cx)
1325                                .detach();
1326                        })
1327                        .ok();
1328                }),
1329            ));
1330        }
1331
1332        container.into_any()
1333    }
1334
1335    fn render_activity_bar(
1336        &self,
1337        thread_entity: &Entity<AcpThread>,
1338        window: &mut Window,
1339        cx: &Context<Self>,
1340    ) -> Option<AnyElement> {
1341        let thread = thread_entity.read(cx);
1342        let action_log = thread.action_log();
1343        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1344        let plan = thread.plan();
1345
1346        if changed_buffers.is_empty() && plan.is_empty() {
1347            return None;
1348        }
1349
1350        let editor_bg_color = cx.theme().colors().editor_background;
1351        let active_color = cx.theme().colors().element_selected;
1352        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1353
1354        let pending_edits = thread.has_pending_edit_tool_calls();
1355
1356        v_flex()
1357            .mt_1()
1358            .mx_2()
1359            .bg(bg_edit_files_disclosure)
1360            .border_1()
1361            .border_b_0()
1362            .border_color(cx.theme().colors().border)
1363            .rounded_t_md()
1364            .shadow(vec![gpui::BoxShadow {
1365                color: gpui::black().opacity(0.15),
1366                offset: point(px(1.), px(-1.)),
1367                blur_radius: px(3.),
1368                spread_radius: px(0.),
1369            }])
1370            .when(!plan.is_empty(), |this| {
1371                this.child(self.render_plan_summary(plan, window, cx))
1372                    .when(self.plan_expanded, |parent| {
1373                        parent.child(self.render_plan_entries(plan, window, cx))
1374                    })
1375            })
1376            .when(!changed_buffers.is_empty(), |this| {
1377                this.child(Divider::horizontal())
1378                    .child(self.render_edits_summary(
1379                        action_log,
1380                        &changed_buffers,
1381                        self.edits_expanded,
1382                        pending_edits,
1383                        window,
1384                        cx,
1385                    ))
1386                    .when(self.edits_expanded, |parent| {
1387                        parent.child(self.render_edited_files(
1388                            action_log,
1389                            &changed_buffers,
1390                            pending_edits,
1391                            cx,
1392                        ))
1393                    })
1394            })
1395            .into_any()
1396            .into()
1397    }
1398
1399    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1400        let stats = plan.stats();
1401
1402        let title = if let Some(entry) = stats.in_progress_entry
1403            && !self.plan_expanded
1404        {
1405            h_flex()
1406                .w_full()
1407                .gap_1()
1408                .text_xs()
1409                .text_color(cx.theme().colors().text_muted)
1410                .justify_between()
1411                .child(
1412                    h_flex()
1413                        .gap_1()
1414                        .child(
1415                            Label::new("Current:")
1416                                .size(LabelSize::Small)
1417                                .color(Color::Muted),
1418                        )
1419                        .child(MarkdownElement::new(
1420                            entry.content.clone(),
1421                            plan_label_markdown_style(&entry.status, window, cx),
1422                        )),
1423                )
1424                .when(stats.pending > 0, |this| {
1425                    this.child(
1426                        Label::new(format!("{} left", stats.pending))
1427                            .size(LabelSize::Small)
1428                            .color(Color::Muted)
1429                            .mr_1(),
1430                    )
1431                })
1432        } else {
1433            let status_label = if stats.pending == 0 {
1434                "All Done".to_string()
1435            } else if stats.completed == 0 {
1436                format!("{}", plan.entries.len())
1437            } else {
1438                format!("{}/{}", stats.completed, plan.entries.len())
1439            };
1440
1441            h_flex()
1442                .w_full()
1443                .gap_1()
1444                .justify_between()
1445                .child(
1446                    Label::new("Plan")
1447                        .size(LabelSize::Small)
1448                        .color(Color::Muted),
1449                )
1450                .child(
1451                    Label::new(status_label)
1452                        .size(LabelSize::Small)
1453                        .color(Color::Muted)
1454                        .mr_1(),
1455                )
1456        };
1457
1458        h_flex()
1459            .p_1()
1460            .justify_between()
1461            .when(self.plan_expanded, |this| {
1462                this.border_b_1().border_color(cx.theme().colors().border)
1463            })
1464            .child(
1465                h_flex()
1466                    .id("plan_summary")
1467                    .w_full()
1468                    .gap_1()
1469                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1470                    .child(title)
1471                    .on_click(cx.listener(|this, _, _, cx| {
1472                        this.plan_expanded = !this.plan_expanded;
1473                        cx.notify();
1474                    })),
1475            )
1476    }
1477
1478    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1479        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1480            let element = h_flex()
1481                .py_1()
1482                .px_2()
1483                .gap_2()
1484                .justify_between()
1485                .bg(cx.theme().colors().editor_background)
1486                .when(index < plan.entries.len() - 1, |parent| {
1487                    parent.border_color(cx.theme().colors().border).border_b_1()
1488                })
1489                .child(
1490                    h_flex()
1491                        .id(("plan_entry", index))
1492                        .gap_1p5()
1493                        .max_w_full()
1494                        .overflow_x_scroll()
1495                        .text_xs()
1496                        .text_color(cx.theme().colors().text_muted)
1497                        .child(match entry.status {
1498                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1499                                .size(IconSize::Small)
1500                                .color(Color::Muted)
1501                                .into_any_element(),
1502                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1503                                .size(IconSize::Small)
1504                                .color(Color::Accent)
1505                                .with_animation(
1506                                    "running",
1507                                    Animation::new(Duration::from_secs(2)).repeat(),
1508                                    |icon, delta| {
1509                                        icon.transform(Transformation::rotate(percentage(delta)))
1510                                    },
1511                                )
1512                                .into_any_element(),
1513                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1514                                .size(IconSize::Small)
1515                                .color(Color::Success)
1516                                .into_any_element(),
1517                        })
1518                        .child(MarkdownElement::new(
1519                            entry.content.clone(),
1520                            plan_label_markdown_style(&entry.status, window, cx),
1521                        )),
1522                );
1523
1524            Some(element)
1525        }))
1526    }
1527
1528    fn render_edits_summary(
1529        &self,
1530        action_log: &Entity<ActionLog>,
1531        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1532        expanded: bool,
1533        pending_edits: bool,
1534        window: &mut Window,
1535        cx: &Context<Self>,
1536    ) -> Div {
1537        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1538
1539        let focus_handle = self.focus_handle(cx);
1540
1541        h_flex()
1542            .p_1()
1543            .justify_between()
1544            .when(expanded, |this| {
1545                this.border_b_1().border_color(cx.theme().colors().border)
1546            })
1547            .child(
1548                h_flex()
1549                    .id("edits-container")
1550                    .cursor_pointer()
1551                    .w_full()
1552                    .gap_1()
1553                    .child(Disclosure::new("edits-disclosure", expanded))
1554                    .map(|this| {
1555                        if pending_edits {
1556                            this.child(
1557                                Label::new(format!(
1558                                    "Editing {} {}",
1559                                    changed_buffers.len(),
1560                                    if changed_buffers.len() == 1 {
1561                                        "file"
1562                                    } else {
1563                                        "files"
1564                                    }
1565                                ))
1566                                .color(Color::Muted)
1567                                .size(LabelSize::Small)
1568                                .with_animation(
1569                                    "edit-label",
1570                                    Animation::new(Duration::from_secs(2))
1571                                        .repeat()
1572                                        .with_easing(pulsating_between(0.3, 0.7)),
1573                                    |label, delta| label.alpha(delta),
1574                                ),
1575                            )
1576                        } else {
1577                            this.child(
1578                                Label::new("Edits")
1579                                    .size(LabelSize::Small)
1580                                    .color(Color::Muted),
1581                            )
1582                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
1583                            .child(
1584                                Label::new(format!(
1585                                    "{} {}",
1586                                    changed_buffers.len(),
1587                                    if changed_buffers.len() == 1 {
1588                                        "file"
1589                                    } else {
1590                                        "files"
1591                                    }
1592                                ))
1593                                .size(LabelSize::Small)
1594                                .color(Color::Muted),
1595                            )
1596                        }
1597                    })
1598                    .on_click(cx.listener(|this, _, _, cx| {
1599                        this.edits_expanded = !this.edits_expanded;
1600                        cx.notify();
1601                    })),
1602            )
1603            .child(
1604                h_flex()
1605                    .gap_1()
1606                    .child(
1607                        IconButton::new("review-changes", IconName::ListTodo)
1608                            .icon_size(IconSize::Small)
1609                            .tooltip({
1610                                let focus_handle = focus_handle.clone();
1611                                move |window, cx| {
1612                                    Tooltip::for_action_in(
1613                                        "Review Changes",
1614                                        &OpenAgentDiff,
1615                                        &focus_handle,
1616                                        window,
1617                                        cx,
1618                                    )
1619                                }
1620                            })
1621                            .on_click(cx.listener(|_, _, window, cx| {
1622                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
1623                            })),
1624                    )
1625                    .child(Divider::vertical().color(DividerColor::Border))
1626                    .child(
1627                        Button::new("reject-all-changes", "Reject All")
1628                            .label_size(LabelSize::Small)
1629                            .disabled(pending_edits)
1630                            .when(pending_edits, |this| {
1631                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1632                            })
1633                            .key_binding(
1634                                KeyBinding::for_action_in(
1635                                    &RejectAll,
1636                                    &focus_handle.clone(),
1637                                    window,
1638                                    cx,
1639                                )
1640                                .map(|kb| kb.size(rems_from_px(10.))),
1641                            )
1642                            .on_click({
1643                                let action_log = action_log.clone();
1644                                cx.listener(move |_, _, _, cx| {
1645                                    action_log.update(cx, |action_log, cx| {
1646                                        action_log.reject_all_edits(cx).detach();
1647                                    })
1648                                })
1649                            }),
1650                    )
1651                    .child(
1652                        Button::new("keep-all-changes", "Keep All")
1653                            .label_size(LabelSize::Small)
1654                            .disabled(pending_edits)
1655                            .when(pending_edits, |this| {
1656                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1657                            })
1658                            .key_binding(
1659                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
1660                                    .map(|kb| kb.size(rems_from_px(10.))),
1661                            )
1662                            .on_click({
1663                                let action_log = action_log.clone();
1664                                cx.listener(move |_, _, _, cx| {
1665                                    action_log.update(cx, |action_log, cx| {
1666                                        action_log.keep_all_edits(cx);
1667                                    })
1668                                })
1669                            }),
1670                    ),
1671            )
1672    }
1673
1674    fn render_edited_files(
1675        &self,
1676        action_log: &Entity<ActionLog>,
1677        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1678        pending_edits: bool,
1679        cx: &Context<Self>,
1680    ) -> Div {
1681        let editor_bg_color = cx.theme().colors().editor_background;
1682
1683        v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1684            |(index, (buffer, _diff))| {
1685                let file = buffer.read(cx).file()?;
1686                let path = file.path();
1687
1688                let file_path = path.parent().and_then(|parent| {
1689                    let parent_str = parent.to_string_lossy();
1690
1691                    if parent_str.is_empty() {
1692                        None
1693                    } else {
1694                        Some(
1695                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
1696                                .color(Color::Muted)
1697                                .size(LabelSize::XSmall)
1698                                .buffer_font(cx),
1699                        )
1700                    }
1701                });
1702
1703                let file_name = path.file_name().map(|name| {
1704                    Label::new(name.to_string_lossy().to_string())
1705                        .size(LabelSize::XSmall)
1706                        .buffer_font(cx)
1707                });
1708
1709                let file_icon = FileIcons::get_icon(&path, cx)
1710                    .map(Icon::from_path)
1711                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1712                    .unwrap_or_else(|| {
1713                        Icon::new(IconName::File)
1714                            .color(Color::Muted)
1715                            .size(IconSize::Small)
1716                    });
1717
1718                let overlay_gradient = linear_gradient(
1719                    90.,
1720                    linear_color_stop(editor_bg_color, 1.),
1721                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1722                );
1723
1724                let element = h_flex()
1725                    .group("edited-code")
1726                    .id(("file-container", index))
1727                    .relative()
1728                    .py_1()
1729                    .pl_2()
1730                    .pr_1()
1731                    .gap_2()
1732                    .justify_between()
1733                    .bg(editor_bg_color)
1734                    .when(index < changed_buffers.len() - 1, |parent| {
1735                        parent.border_color(cx.theme().colors().border).border_b_1()
1736                    })
1737                    .child(
1738                        h_flex()
1739                            .id(("file-name", index))
1740                            .pr_8()
1741                            .gap_1p5()
1742                            .max_w_full()
1743                            .overflow_x_scroll()
1744                            .child(file_icon)
1745                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
1746                            .on_click({
1747                                let buffer = buffer.clone();
1748                                cx.listener(move |this, _, window, cx| {
1749                                    this.open_edited_buffer(&buffer, window, cx);
1750                                })
1751                            }),
1752                    )
1753                    .child(
1754                        h_flex()
1755                            .gap_1()
1756                            .visible_on_hover("edited-code")
1757                            .child(
1758                                Button::new("review", "Review")
1759                                    .label_size(LabelSize::Small)
1760                                    .on_click({
1761                                        let buffer = buffer.clone();
1762                                        cx.listener(move |this, _, window, cx| {
1763                                            this.open_edited_buffer(&buffer, window, cx);
1764                                        })
1765                                    }),
1766                            )
1767                            .child(Divider::vertical().color(DividerColor::BorderVariant))
1768                            .child(
1769                                Button::new("reject-file", "Reject")
1770                                    .label_size(LabelSize::Small)
1771                                    .disabled(pending_edits)
1772                                    .on_click({
1773                                        let buffer = buffer.clone();
1774                                        let action_log = action_log.clone();
1775                                        move |_, _, cx| {
1776                                            action_log.update(cx, |action_log, cx| {
1777                                                action_log
1778                                                    .reject_edits_in_ranges(
1779                                                        buffer.clone(),
1780                                                        vec![Anchor::MIN..Anchor::MAX],
1781                                                        cx,
1782                                                    )
1783                                                    .detach_and_log_err(cx);
1784                                            })
1785                                        }
1786                                    }),
1787                            )
1788                            .child(
1789                                Button::new("keep-file", "Keep")
1790                                    .label_size(LabelSize::Small)
1791                                    .disabled(pending_edits)
1792                                    .on_click({
1793                                        let buffer = buffer.clone();
1794                                        let action_log = action_log.clone();
1795                                        move |_, _, cx| {
1796                                            action_log.update(cx, |action_log, cx| {
1797                                                action_log.keep_edits_in_range(
1798                                                    buffer.clone(),
1799                                                    Anchor::MIN..Anchor::MAX,
1800                                                    cx,
1801                                                );
1802                                            })
1803                                        }
1804                                    }),
1805                            ),
1806                    )
1807                    .child(
1808                        div()
1809                            .id("gradient-overlay")
1810                            .absolute()
1811                            .h_full()
1812                            .w_12()
1813                            .top_0()
1814                            .bottom_0()
1815                            .right(px(152.))
1816                            .bg(overlay_gradient),
1817                    );
1818
1819                Some(element)
1820            },
1821        ))
1822    }
1823
1824    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1825        let focus_handle = self.message_editor.focus_handle(cx);
1826        let editor_bg_color = cx.theme().colors().editor_background;
1827        let (expand_icon, expand_tooltip) = if self.editor_expanded {
1828            (IconName::Minimize, "Minimize Message Editor")
1829        } else {
1830            (IconName::Maximize, "Expand Message Editor")
1831        };
1832
1833        v_flex()
1834            .on_action(cx.listener(Self::expand_message_editor))
1835            .p_2()
1836            .gap_2()
1837            .border_t_1()
1838            .border_color(cx.theme().colors().border)
1839            .bg(editor_bg_color)
1840            .when(self.editor_expanded, |this| {
1841                this.h(vh(0.8, window)).size_full().justify_between()
1842            })
1843            .child(
1844                v_flex()
1845                    .relative()
1846                    .size_full()
1847                    .pt_1()
1848                    .pr_2p5()
1849                    .child(div().flex_1().child({
1850                        let settings = ThemeSettings::get_global(cx);
1851                        let font_size = TextSize::Small
1852                            .rems(cx)
1853                            .to_pixels(settings.agent_font_size(cx));
1854                        let line_height = settings.buffer_line_height.value() * font_size;
1855
1856                        let text_style = TextStyle {
1857                            color: cx.theme().colors().text,
1858                            font_family: settings.buffer_font.family.clone(),
1859                            font_fallbacks: settings.buffer_font.fallbacks.clone(),
1860                            font_features: settings.buffer_font.features.clone(),
1861                            font_size: font_size.into(),
1862                            line_height: line_height.into(),
1863                            ..Default::default()
1864                        };
1865
1866                        EditorElement::new(
1867                            &self.message_editor,
1868                            EditorStyle {
1869                                background: editor_bg_color,
1870                                local_player: cx.theme().players().local(),
1871                                text: text_style,
1872                                syntax: cx.theme().syntax().clone(),
1873                                ..Default::default()
1874                            },
1875                        )
1876                    }))
1877                    .child(
1878                        h_flex()
1879                            .absolute()
1880                            .top_0()
1881                            .right_0()
1882                            .opacity(0.5)
1883                            .hover(|this| this.opacity(1.0))
1884                            .child(
1885                                IconButton::new("toggle-height", expand_icon)
1886                                    .icon_size(IconSize::XSmall)
1887                                    .icon_color(Color::Muted)
1888                                    .tooltip({
1889                                        let focus_handle = focus_handle.clone();
1890                                        move |window, cx| {
1891                                            Tooltip::for_action_in(
1892                                                expand_tooltip,
1893                                                &ExpandMessageEditor,
1894                                                &focus_handle,
1895                                                window,
1896                                                cx,
1897                                            )
1898                                        }
1899                                    })
1900                                    .on_click(cx.listener(|_, _, window, cx| {
1901                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
1902                                    })),
1903                            ),
1904                    ),
1905            )
1906            .child(
1907                h_flex()
1908                    .flex_none()
1909                    .justify_between()
1910                    .child(self.render_follow_toggle(cx))
1911                    .child(self.render_send_button(cx)),
1912            )
1913            .into_any()
1914    }
1915
1916    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
1917        if self.thread().map_or(true, |thread| {
1918            thread.read(cx).status() == ThreadStatus::Idle
1919        }) {
1920            let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
1921            IconButton::new("send-message", IconName::Send)
1922                .icon_color(Color::Accent)
1923                .style(ButtonStyle::Filled)
1924                .disabled(self.thread().is_none() || is_editor_empty)
1925                .on_click(cx.listener(|this, _, window, cx| {
1926                    this.chat(&Chat, window, cx);
1927                }))
1928                .when(!is_editor_empty, |button| {
1929                    button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
1930                })
1931                .when(is_editor_empty, |button| {
1932                    button.tooltip(Tooltip::text("Type a message to submit"))
1933                })
1934                .into_any_element()
1935        } else {
1936            IconButton::new("stop-generation", IconName::StopFilled)
1937                .icon_color(Color::Error)
1938                .style(ButtonStyle::Tinted(ui::TintColor::Error))
1939                .tooltip(move |window, cx| {
1940                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
1941                })
1942                .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
1943                .into_any_element()
1944        }
1945    }
1946
1947    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
1948        let following = self
1949            .workspace
1950            .read_with(cx, |workspace, _| {
1951                workspace.is_being_followed(CollaboratorId::Agent)
1952            })
1953            .unwrap_or(false);
1954
1955        IconButton::new("follow-agent", IconName::Crosshair)
1956            .icon_size(IconSize::Small)
1957            .icon_color(Color::Muted)
1958            .toggle_state(following)
1959            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
1960            .tooltip(move |window, cx| {
1961                if following {
1962                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
1963                } else {
1964                    Tooltip::with_meta(
1965                        "Follow Agent",
1966                        Some(&Follow),
1967                        "Track the agent's location as it reads and edits files.",
1968                        window,
1969                        cx,
1970                    )
1971                }
1972            })
1973            .on_click(cx.listener(move |this, _, window, cx| {
1974                this.workspace
1975                    .update(cx, |workspace, cx| {
1976                        if following {
1977                            workspace.unfollow(CollaboratorId::Agent, window, cx);
1978                        } else {
1979                            workspace.follow(CollaboratorId::Agent, window, cx);
1980                        }
1981                    })
1982                    .ok();
1983            }))
1984    }
1985
1986    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
1987        let workspace = self.workspace.clone();
1988        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
1989            Self::open_link(text, &workspace, window, cx);
1990        })
1991    }
1992
1993    fn open_link(
1994        url: SharedString,
1995        workspace: &WeakEntity<Workspace>,
1996        window: &mut Window,
1997        cx: &mut App,
1998    ) {
1999        let Some(workspace) = workspace.upgrade() else {
2000            cx.open_url(&url);
2001            return;
2002        };
2003
2004        if let Some(mention_path) = MentionPath::try_parse(&url) {
2005            workspace.update(cx, |workspace, cx| {
2006                let project = workspace.project();
2007                let Some((path, entry)) = project.update(cx, |project, cx| {
2008                    let path = project.find_project_path(mention_path.path(), cx)?;
2009                    let entry = project.entry_for_path(&path, cx)?;
2010                    Some((path, entry))
2011                }) else {
2012                    return;
2013                };
2014
2015                if entry.is_dir() {
2016                    project.update(cx, |_, cx| {
2017                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
2018                    });
2019                } else {
2020                    workspace
2021                        .open_path(path, None, true, window, cx)
2022                        .detach_and_log_err(cx);
2023                }
2024            })
2025        } else {
2026            cx.open_url(&url);
2027        }
2028    }
2029
2030    fn open_tool_call_location(
2031        &self,
2032        entry_ix: usize,
2033        location_ix: usize,
2034        window: &mut Window,
2035        cx: &mut Context<Self>,
2036    ) -> Option<()> {
2037        let location = self
2038            .thread()?
2039            .read(cx)
2040            .entries()
2041            .get(entry_ix)?
2042            .locations()?
2043            .get(location_ix)?;
2044
2045        let project_path = self
2046            .project
2047            .read(cx)
2048            .find_project_path(&location.path, cx)?;
2049
2050        let open_task = self
2051            .workspace
2052            .update(cx, |worskpace, cx| {
2053                worskpace.open_path(project_path, None, true, window, cx)
2054            })
2055            .log_err()?;
2056
2057        window
2058            .spawn(cx, async move |cx| {
2059                let item = open_task.await?;
2060
2061                let Some(active_editor) = item.downcast::<Editor>() else {
2062                    return anyhow::Ok(());
2063                };
2064
2065                active_editor.update_in(cx, |editor, window, cx| {
2066                    let snapshot = editor.buffer().read(cx).snapshot(cx);
2067                    let first_hunk = editor
2068                        .diff_hunks_in_ranges(
2069                            &[editor::Anchor::min()..editor::Anchor::max()],
2070                            &snapshot,
2071                        )
2072                        .next();
2073                    if let Some(first_hunk) = first_hunk {
2074                        let first_hunk_start = first_hunk.multi_buffer_range().start;
2075                        editor.change_selections(Default::default(), window, cx, |selections| {
2076                            selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2077                        })
2078                    }
2079                })?;
2080
2081                anyhow::Ok(())
2082            })
2083            .detach_and_log_err(cx);
2084
2085        None
2086    }
2087
2088    pub fn open_thread_as_markdown(
2089        &self,
2090        workspace: Entity<Workspace>,
2091        window: &mut Window,
2092        cx: &mut App,
2093    ) -> Task<anyhow::Result<()>> {
2094        let markdown_language_task = workspace
2095            .read(cx)
2096            .app_state()
2097            .languages
2098            .language_for_name("Markdown");
2099
2100        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2101            let thread = thread.read(cx);
2102            (thread.title().to_string(), thread.to_markdown(cx))
2103        } else {
2104            return Task::ready(Ok(()));
2105        };
2106
2107        window.spawn(cx, async move |cx| {
2108            let markdown_language = markdown_language_task.await?;
2109
2110            workspace.update_in(cx, |workspace, window, cx| {
2111                let project = workspace.project().clone();
2112
2113                if !project.read(cx).is_local() {
2114                    anyhow::bail!("failed to open active thread as markdown in remote project");
2115                }
2116
2117                let buffer = project.update(cx, |project, cx| {
2118                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
2119                });
2120                let buffer = cx.new(|cx| {
2121                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2122                });
2123
2124                workspace.add_item_to_active_pane(
2125                    Box::new(cx.new(|cx| {
2126                        let mut editor =
2127                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2128                        editor.set_breadcrumb_header(thread_summary);
2129                        editor
2130                    })),
2131                    None,
2132                    true,
2133                    window,
2134                    cx,
2135                );
2136
2137                anyhow::Ok(())
2138            })??;
2139            anyhow::Ok(())
2140        })
2141    }
2142
2143    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2144        self.list_state.scroll_to(ListOffset::default());
2145        cx.notify();
2146    }
2147}
2148
2149impl Focusable for AcpThreadView {
2150    fn focus_handle(&self, cx: &App) -> FocusHandle {
2151        self.message_editor.focus_handle(cx)
2152    }
2153}
2154
2155impl Render for AcpThreadView {
2156    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2157        let open_as_markdown = IconButton::new("open-as-markdown", IconName::DocumentText)
2158            .icon_size(IconSize::XSmall)
2159            .icon_color(Color::Ignored)
2160            .tooltip(Tooltip::text("Open Thread as Markdown"))
2161            .on_click(cx.listener(move |this, _, window, cx| {
2162                if let Some(workspace) = this.workspace.upgrade() {
2163                    this.open_thread_as_markdown(workspace, window, cx)
2164                        .detach_and_log_err(cx);
2165                }
2166            }));
2167
2168        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUpAlt)
2169            .icon_size(IconSize::XSmall)
2170            .icon_color(Color::Ignored)
2171            .tooltip(Tooltip::text("Scroll To Top"))
2172            .on_click(cx.listener(move |this, _, _, cx| {
2173                this.scroll_to_top(cx);
2174            }));
2175
2176        v_flex()
2177            .size_full()
2178            .key_context("AcpThread")
2179            .on_action(cx.listener(Self::chat))
2180            .on_action(cx.listener(Self::previous_history_message))
2181            .on_action(cx.listener(Self::next_history_message))
2182            .on_action(cx.listener(Self::open_agent_diff))
2183            .child(match &self.thread_state {
2184                ThreadState::Unauthenticated { .. } => {
2185                    v_flex()
2186                        .p_2()
2187                        .flex_1()
2188                        .items_center()
2189                        .justify_center()
2190                        .child(self.render_pending_auth_state())
2191                        .child(
2192                            h_flex().mt_1p5().justify_center().child(
2193                                Button::new("sign-in", format!("Sign in to {}", self.agent.name()))
2194                                    .on_click(cx.listener(|this, _, window, cx| {
2195                                        this.authenticate(window, cx)
2196                                    })),
2197                            ),
2198                        )
2199                }
2200                ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2201                ThreadState::LoadError(e) => v_flex()
2202                    .p_2()
2203                    .flex_1()
2204                    .items_center()
2205                    .justify_center()
2206                    .child(self.render_error_state(e, cx)),
2207                ThreadState::Ready { thread, .. } => v_flex().flex_1().map(|this| {
2208                    if self.list_state.item_count() > 0 {
2209                        this.child(
2210                            list(self.list_state.clone())
2211                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2212                                .flex_grow()
2213                                .into_any(),
2214                        )
2215                        .child(
2216                            h_flex()
2217                                .group("controls")
2218                                .mt_1()
2219                                .mr_1()
2220                                .py_2()
2221                                .px(RESPONSE_PADDING_X)
2222                                .opacity(0.4)
2223                                .hover(|style| style.opacity(1.))
2224                                .flex_wrap()
2225                                .justify_end()
2226                                .child(open_as_markdown)
2227                                .child(scroll_to_top)
2228                                .into_any_element(),
2229                        )
2230                        .children(match thread.read(cx).status() {
2231                            ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => None,
2232                            ThreadStatus::Generating => div()
2233                                .px_5()
2234                                .py_2()
2235                                .child(LoadingLabel::new("").size(LabelSize::Small))
2236                                .into(),
2237                        })
2238                        .children(self.render_activity_bar(&thread, window, cx))
2239                    } else {
2240                        this.child(self.render_empty_state(cx))
2241                    }
2242                }),
2243            })
2244            .when_some(self.last_error.clone(), |el, error| {
2245                el.child(
2246                    div()
2247                        .p_2()
2248                        .text_xs()
2249                        .border_t_1()
2250                        .border_color(cx.theme().colors().border)
2251                        .bg(cx.theme().status().error_background)
2252                        .child(
2253                            self.render_markdown(error, default_markdown_style(false, window, cx)),
2254                        ),
2255                )
2256            })
2257            .child(self.render_message_editor(window, cx))
2258    }
2259}
2260
2261fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2262    let mut style = default_markdown_style(false, window, cx);
2263    let mut text_style = window.text_style();
2264    let theme_settings = ThemeSettings::get_global(cx);
2265
2266    let buffer_font = theme_settings.buffer_font.family.clone();
2267    let buffer_font_size = TextSize::Small.rems(cx);
2268
2269    text_style.refine(&TextStyleRefinement {
2270        font_family: Some(buffer_font),
2271        font_size: Some(buffer_font_size.into()),
2272        ..Default::default()
2273    });
2274
2275    style.base_text_style = text_style;
2276    style.link_callback = Some(Rc::new(move |url, cx| {
2277        if MentionPath::try_parse(url).is_some() {
2278            let colors = cx.theme().colors();
2279            Some(TextStyleRefinement {
2280                background_color: Some(colors.element_background),
2281                ..Default::default()
2282            })
2283        } else {
2284            None
2285        }
2286    }));
2287    style
2288}
2289
2290fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2291    let theme_settings = ThemeSettings::get_global(cx);
2292    let colors = cx.theme().colors();
2293
2294    let buffer_font_size = TextSize::Small.rems(cx);
2295
2296    let mut text_style = window.text_style();
2297    let line_height = buffer_font_size * 1.75;
2298
2299    let font_family = if buffer_font {
2300        theme_settings.buffer_font.family.clone()
2301    } else {
2302        theme_settings.ui_font.family.clone()
2303    };
2304
2305    let font_size = if buffer_font {
2306        TextSize::Small.rems(cx)
2307    } else {
2308        TextSize::Default.rems(cx)
2309    };
2310
2311    text_style.refine(&TextStyleRefinement {
2312        font_family: Some(font_family),
2313        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2314        font_features: Some(theme_settings.ui_font.features.clone()),
2315        font_size: Some(font_size.into()),
2316        line_height: Some(line_height.into()),
2317        color: Some(cx.theme().colors().text),
2318        ..Default::default()
2319    });
2320
2321    MarkdownStyle {
2322        base_text_style: text_style.clone(),
2323        syntax: cx.theme().syntax().clone(),
2324        selection_background_color: cx.theme().colors().element_selection_background,
2325        code_block_overflow_x_scroll: true,
2326        table_overflow_x_scroll: true,
2327        heading_level_styles: Some(HeadingLevelStyles {
2328            h1: Some(TextStyleRefinement {
2329                font_size: Some(rems(1.15).into()),
2330                ..Default::default()
2331            }),
2332            h2: Some(TextStyleRefinement {
2333                font_size: Some(rems(1.1).into()),
2334                ..Default::default()
2335            }),
2336            h3: Some(TextStyleRefinement {
2337                font_size: Some(rems(1.05).into()),
2338                ..Default::default()
2339            }),
2340            h4: Some(TextStyleRefinement {
2341                font_size: Some(rems(1.).into()),
2342                ..Default::default()
2343            }),
2344            h5: Some(TextStyleRefinement {
2345                font_size: Some(rems(0.95).into()),
2346                ..Default::default()
2347            }),
2348            h6: Some(TextStyleRefinement {
2349                font_size: Some(rems(0.875).into()),
2350                ..Default::default()
2351            }),
2352        }),
2353        code_block: StyleRefinement {
2354            padding: EdgesRefinement {
2355                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2356                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2357                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2358                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2359            },
2360            margin: EdgesRefinement {
2361                top: Some(Length::Definite(Pixels(8.).into())),
2362                left: Some(Length::Definite(Pixels(0.).into())),
2363                right: Some(Length::Definite(Pixels(0.).into())),
2364                bottom: Some(Length::Definite(Pixels(12.).into())),
2365            },
2366            border_style: Some(BorderStyle::Solid),
2367            border_widths: EdgesRefinement {
2368                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2369                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2370                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2371                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2372            },
2373            border_color: Some(colors.border_variant),
2374            background: Some(colors.editor_background.into()),
2375            text: Some(TextStyleRefinement {
2376                font_family: Some(theme_settings.buffer_font.family.clone()),
2377                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2378                font_features: Some(theme_settings.buffer_font.features.clone()),
2379                font_size: Some(buffer_font_size.into()),
2380                ..Default::default()
2381            }),
2382            ..Default::default()
2383        },
2384        inline_code: TextStyleRefinement {
2385            font_family: Some(theme_settings.buffer_font.family.clone()),
2386            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2387            font_features: Some(theme_settings.buffer_font.features.clone()),
2388            font_size: Some(buffer_font_size.into()),
2389            background_color: Some(colors.editor_foreground.opacity(0.08)),
2390            ..Default::default()
2391        },
2392        link: TextStyleRefinement {
2393            background_color: Some(colors.editor_foreground.opacity(0.025)),
2394            underline: Some(UnderlineStyle {
2395                color: Some(colors.text_accent.opacity(0.5)),
2396                thickness: px(1.),
2397                ..Default::default()
2398            }),
2399            ..Default::default()
2400        },
2401        ..Default::default()
2402    }
2403}
2404
2405fn plan_label_markdown_style(
2406    status: &acp::PlanEntryStatus,
2407    window: &Window,
2408    cx: &App,
2409) -> MarkdownStyle {
2410    let default_md_style = default_markdown_style(false, window, cx);
2411
2412    MarkdownStyle {
2413        base_text_style: TextStyle {
2414            color: cx.theme().colors().text_muted,
2415            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2416                Some(gpui::StrikethroughStyle {
2417                    thickness: px(1.),
2418                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2419                })
2420            } else {
2421                None
2422            },
2423            ..default_md_style.base_text_style
2424        },
2425        ..default_md_style
2426    }
2427}