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