active_thread.rs

   1use crate::context_picker::{ContextPicker, MentionLink};
   2use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
   3use crate::message_editor::{extract_message_creases, insert_message_creases};
   4use crate::ui::{AddedContext, AgentNotification, AgentNotificationEvent, ContextPill};
   5use crate::{AgentPanel, ModelUsageContext};
   6use agent::{
   7    ContextStore, LastRestoreCheckpoint, MessageCrease, MessageId, MessageSegment, TextThreadStore,
   8    Thread, ThreadError, ThreadEvent, ThreadFeedback, ThreadStore, ThreadSummary,
   9    context::{self, AgentContextHandle, RULES_ICON},
  10    thread_store::RulesLoadingError,
  11    tool_use::{PendingToolUseStatus, ToolUse},
  12};
  13use agent_settings::{AgentSettings, NotifyWhenAgentWaiting};
  14use anyhow::Context as _;
  15use assistant_tool::ToolUseStatus;
  16use audio::{Audio, Sound};
  17use collections::{HashMap, HashSet};
  18use editor::actions::{MoveUp, Paste};
  19use editor::scroll::Autoscroll;
  20use editor::{Editor, EditorElement, EditorEvent, EditorStyle, MultiBuffer, SelectionEffects};
  21use gpui::{
  22    AbsoluteLength, Animation, AnimationExt, AnyElement, App, ClickEvent, ClipboardEntry,
  23    ClipboardItem, DefiniteLength, EdgesRefinement, Empty, Entity, EventEmitter, Focusable, Hsla,
  24    ListAlignment, ListOffset, ListState, MouseButton, PlatformDisplay, ScrollHandle, Stateful,
  25    StyleRefinement, Subscription, Task, TextStyle, TextStyleRefinement, Transformation,
  26    UnderlineStyle, WeakEntity, WindowHandle, linear_color_stop, linear_gradient, list, percentage,
  27    pulsating_between,
  28};
  29use language::{Buffer, Language, LanguageRegistry};
  30use language_model::{
  31    LanguageModelRequestMessage, LanguageModelToolUseId, MessageContent, Role, StopReason,
  32};
  33use markdown::parser::{CodeBlockKind, CodeBlockMetadata};
  34use markdown::{
  35    HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle, ParsedMarkdown, PathWithRange,
  36};
  37use project::{ProjectEntryId, ProjectItem as _};
  38use rope::Point;
  39use settings::{Settings as _, SettingsStore, update_settings_file};
  40use std::ffi::OsStr;
  41use std::path::Path;
  42use std::rc::Rc;
  43use std::sync::Arc;
  44use std::time::Duration;
  45use text::ToPoint;
  46use theme::ThemeSettings;
  47use ui::{
  48    Banner, Disclosure, KeyBinding, PopoverMenuHandle, Scrollbar, ScrollbarState, TextSize,
  49    Tooltip, prelude::*,
  50};
  51use util::ResultExt as _;
  52use util::markdown::MarkdownCodeBlock;
  53use workspace::{CollaboratorId, Workspace};
  54use zed_actions::assistant::OpenRulesLibrary;
  55use zed_llm_client::CompletionIntent;
  56
  57const CODEBLOCK_CONTAINER_GROUP: &str = "codeblock_container";
  58const EDIT_PREVIOUS_MESSAGE_MIN_LINES: usize = 1;
  59const RESPONSE_PADDING_X: Pixels = px(19.);
  60
  61pub struct ActiveThread {
  62    context_store: Entity<ContextStore>,
  63    language_registry: Arc<LanguageRegistry>,
  64    thread_store: Entity<ThreadStore>,
  65    text_thread_store: Entity<TextThreadStore>,
  66    thread: Entity<Thread>,
  67    workspace: WeakEntity<Workspace>,
  68    save_thread_task: Option<Task<()>>,
  69    messages: Vec<MessageId>,
  70    list_state: ListState,
  71    scrollbar_state: ScrollbarState,
  72    show_scrollbar: bool,
  73    hide_scrollbar_task: Option<Task<()>>,
  74    rendered_messages_by_id: HashMap<MessageId, RenderedMessage>,
  75    rendered_tool_uses: HashMap<LanguageModelToolUseId, RenderedToolUse>,
  76    editing_message: Option<(MessageId, EditingMessageState)>,
  77    expanded_tool_uses: HashMap<LanguageModelToolUseId, bool>,
  78    expanded_thinking_segments: HashMap<(MessageId, usize), bool>,
  79    expanded_code_blocks: HashMap<(MessageId, usize), bool>,
  80    last_error: Option<ThreadError>,
  81    notifications: Vec<WindowHandle<AgentNotification>>,
  82    copied_code_block_ids: HashSet<(MessageId, usize)>,
  83    _subscriptions: Vec<Subscription>,
  84    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
  85    open_feedback_editors: HashMap<MessageId, Entity<Editor>>,
  86    _load_edited_message_context_task: Option<Task<()>>,
  87}
  88
  89struct RenderedMessage {
  90    language_registry: Arc<LanguageRegistry>,
  91    segments: Vec<RenderedMessageSegment>,
  92}
  93
  94#[derive(Clone)]
  95struct RenderedToolUse {
  96    label: Entity<Markdown>,
  97    input: Entity<Markdown>,
  98    output: Entity<Markdown>,
  99}
 100
 101impl RenderedMessage {
 102    fn from_segments(
 103        segments: &[MessageSegment],
 104        language_registry: Arc<LanguageRegistry>,
 105        cx: &mut App,
 106    ) -> Self {
 107        let mut this = Self {
 108            language_registry,
 109            segments: Vec::with_capacity(segments.len()),
 110        };
 111        for segment in segments {
 112            this.push_segment(segment, cx);
 113        }
 114        this
 115    }
 116
 117    fn append_thinking(&mut self, text: &String, cx: &mut App) {
 118        if let Some(RenderedMessageSegment::Thinking {
 119            content,
 120            scroll_handle,
 121        }) = self.segments.last_mut()
 122        {
 123            content.update(cx, |markdown, cx| {
 124                markdown.append(text, cx);
 125            });
 126            scroll_handle.scroll_to_bottom();
 127        } else {
 128            self.segments.push(RenderedMessageSegment::Thinking {
 129                content: parse_markdown(text.into(), self.language_registry.clone(), cx),
 130                scroll_handle: ScrollHandle::default(),
 131            });
 132        }
 133    }
 134
 135    fn append_text(&mut self, text: &String, cx: &mut App) {
 136        if let Some(RenderedMessageSegment::Text(markdown)) = self.segments.last_mut() {
 137            markdown.update(cx, |markdown, cx| markdown.append(text, cx));
 138        } else {
 139            self.segments
 140                .push(RenderedMessageSegment::Text(parse_markdown(
 141                    SharedString::from(text),
 142                    self.language_registry.clone(),
 143                    cx,
 144                )));
 145        }
 146    }
 147
 148    fn push_segment(&mut self, segment: &MessageSegment, cx: &mut App) {
 149        match segment {
 150            MessageSegment::Thinking { text, .. } => {
 151                self.segments.push(RenderedMessageSegment::Thinking {
 152                    content: parse_markdown(text.into(), self.language_registry.clone(), cx),
 153                    scroll_handle: ScrollHandle::default(),
 154                })
 155            }
 156            MessageSegment::Text(text) => {
 157                self.segments
 158                    .push(RenderedMessageSegment::Text(parse_markdown(
 159                        text.into(),
 160                        self.language_registry.clone(),
 161                        cx,
 162                    )))
 163            }
 164            MessageSegment::RedactedThinking(_) => {}
 165        };
 166    }
 167}
 168
 169enum RenderedMessageSegment {
 170    Thinking {
 171        content: Entity<Markdown>,
 172        scroll_handle: ScrollHandle,
 173    },
 174    Text(Entity<Markdown>),
 175}
 176
 177fn parse_markdown(
 178    text: SharedString,
 179    language_registry: Arc<LanguageRegistry>,
 180    cx: &mut App,
 181) -> Entity<Markdown> {
 182    cx.new(|cx| Markdown::new(text, Some(language_registry), None, cx))
 183}
 184
 185pub(crate) fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
 186    let theme_settings = ThemeSettings::get_global(cx);
 187    let colors = cx.theme().colors();
 188    let ui_font_size = TextSize::Default.rems(cx);
 189    let buffer_font_size = TextSize::Small.rems(cx);
 190    let mut text_style = window.text_style();
 191    let line_height = buffer_font_size * 1.75;
 192
 193    text_style.refine(&TextStyleRefinement {
 194        font_family: Some(theme_settings.ui_font.family.clone()),
 195        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
 196        font_features: Some(theme_settings.ui_font.features.clone()),
 197        font_size: Some(ui_font_size.into()),
 198        line_height: Some(line_height.into()),
 199        color: Some(cx.theme().colors().text),
 200        ..Default::default()
 201    });
 202
 203    MarkdownStyle {
 204        base_text_style: text_style.clone(),
 205        syntax: cx.theme().syntax().clone(),
 206        selection_background_color: cx.theme().colors().element_selection_background,
 207        code_block_overflow_x_scroll: true,
 208        table_overflow_x_scroll: true,
 209        heading_level_styles: Some(HeadingLevelStyles {
 210            h1: Some(TextStyleRefinement {
 211                font_size: Some(rems(1.15).into()),
 212                ..Default::default()
 213            }),
 214            h2: Some(TextStyleRefinement {
 215                font_size: Some(rems(1.1).into()),
 216                ..Default::default()
 217            }),
 218            h3: Some(TextStyleRefinement {
 219                font_size: Some(rems(1.05).into()),
 220                ..Default::default()
 221            }),
 222            h4: Some(TextStyleRefinement {
 223                font_size: Some(rems(1.).into()),
 224                ..Default::default()
 225            }),
 226            h5: Some(TextStyleRefinement {
 227                font_size: Some(rems(0.95).into()),
 228                ..Default::default()
 229            }),
 230            h6: Some(TextStyleRefinement {
 231                font_size: Some(rems(0.875).into()),
 232                ..Default::default()
 233            }),
 234        }),
 235        code_block: StyleRefinement {
 236            padding: EdgesRefinement {
 237                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 238                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 239                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 240                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 241            },
 242            background: Some(colors.editor_background.into()),
 243            text: Some(TextStyleRefinement {
 244                font_family: Some(theme_settings.buffer_font.family.clone()),
 245                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 246                font_features: Some(theme_settings.buffer_font.features.clone()),
 247                font_size: Some(buffer_font_size.into()),
 248                ..Default::default()
 249            }),
 250            ..Default::default()
 251        },
 252        inline_code: TextStyleRefinement {
 253            font_family: Some(theme_settings.buffer_font.family.clone()),
 254            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 255            font_features: Some(theme_settings.buffer_font.features.clone()),
 256            font_size: Some(buffer_font_size.into()),
 257            background_color: Some(colors.editor_foreground.opacity(0.08)),
 258            ..Default::default()
 259        },
 260        link: TextStyleRefinement {
 261            background_color: Some(colors.editor_foreground.opacity(0.025)),
 262            underline: Some(UnderlineStyle {
 263                color: Some(colors.text_accent.opacity(0.5)),
 264                thickness: px(1.),
 265                ..Default::default()
 266            }),
 267            ..Default::default()
 268        },
 269        link_callback: Some(Rc::new(move |url, cx| {
 270            if MentionLink::is_valid(url) {
 271                let colors = cx.theme().colors();
 272                Some(TextStyleRefinement {
 273                    background_color: Some(colors.element_background),
 274                    ..Default::default()
 275                })
 276            } else {
 277                None
 278            }
 279        })),
 280        ..Default::default()
 281    }
 282}
 283
 284fn tool_use_markdown_style(window: &Window, cx: &mut App) -> MarkdownStyle {
 285    let theme_settings = ThemeSettings::get_global(cx);
 286    let colors = cx.theme().colors();
 287    let ui_font_size = TextSize::Default.rems(cx);
 288    let buffer_font_size = TextSize::Small.rems(cx);
 289    let mut text_style = window.text_style();
 290
 291    text_style.refine(&TextStyleRefinement {
 292        font_family: Some(theme_settings.ui_font.family.clone()),
 293        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
 294        font_features: Some(theme_settings.ui_font.features.clone()),
 295        font_size: Some(ui_font_size.into()),
 296        color: Some(cx.theme().colors().text),
 297        ..Default::default()
 298    });
 299
 300    MarkdownStyle {
 301        base_text_style: text_style,
 302        syntax: cx.theme().syntax().clone(),
 303        selection_background_color: cx.theme().colors().element_selection_background,
 304        code_block_overflow_x_scroll: false,
 305        code_block: StyleRefinement {
 306            margin: EdgesRefinement::default(),
 307            padding: EdgesRefinement::default(),
 308            background: Some(colors.editor_background.into()),
 309            border_color: None,
 310            border_widths: EdgesRefinement::default(),
 311            text: Some(TextStyleRefinement {
 312                font_family: Some(theme_settings.buffer_font.family.clone()),
 313                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 314                font_features: Some(theme_settings.buffer_font.features.clone()),
 315                font_size: Some(buffer_font_size.into()),
 316                ..Default::default()
 317            }),
 318            ..Default::default()
 319        },
 320        inline_code: TextStyleRefinement {
 321            font_family: Some(theme_settings.buffer_font.family.clone()),
 322            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 323            font_features: Some(theme_settings.buffer_font.features.clone()),
 324            font_size: Some(TextSize::XSmall.rems(cx).into()),
 325            ..Default::default()
 326        },
 327        heading: StyleRefinement {
 328            text: Some(TextStyleRefinement {
 329                font_size: Some(ui_font_size.into()),
 330                ..Default::default()
 331            }),
 332            ..Default::default()
 333        },
 334        ..Default::default()
 335    }
 336}
 337
 338fn render_markdown_code_block(
 339    message_id: MessageId,
 340    ix: usize,
 341    kind: &CodeBlockKind,
 342    parsed_markdown: &ParsedMarkdown,
 343    metadata: CodeBlockMetadata,
 344    active_thread: Entity<ActiveThread>,
 345    workspace: WeakEntity<Workspace>,
 346    _window: &Window,
 347    cx: &App,
 348) -> Div {
 349    let label_size = rems(0.8125);
 350
 351    let label = match kind {
 352        CodeBlockKind::Indented => None,
 353        CodeBlockKind::Fenced => Some(
 354            h_flex()
 355                .px_1()
 356                .gap_1()
 357                .child(
 358                    Icon::new(IconName::Code)
 359                        .color(Color::Muted)
 360                        .size(IconSize::XSmall),
 361                )
 362                .child(div().text_size(label_size).child("Plain Text"))
 363                .into_any_element(),
 364        ),
 365        CodeBlockKind::FencedLang(raw_language_name) => Some(render_code_language(
 366            parsed_markdown.languages_by_name.get(raw_language_name),
 367            raw_language_name.clone(),
 368            cx,
 369        )),
 370        CodeBlockKind::FencedSrc(path_range) => path_range.path.file_name().map(|file_name| {
 371            // We tell the model to use /dev/null for the path instead of using ```language
 372            // because otherwise it consistently fails to use code citations.
 373            if path_range.path.starts_with("/dev/null") {
 374                let ext = path_range
 375                    .path
 376                    .extension()
 377                    .and_then(OsStr::to_str)
 378                    .map(|str| SharedString::new(str.to_string()))
 379                    .unwrap_or_default();
 380
 381                render_code_language(
 382                    parsed_markdown
 383                        .languages_by_path
 384                        .get(&path_range.path)
 385                        .or_else(|| parsed_markdown.languages_by_name.get(&ext)),
 386                    ext,
 387                    cx,
 388                )
 389            } else {
 390                let content = if let Some(parent) = path_range.path.parent() {
 391                    let file_name = file_name.to_string_lossy().to_string();
 392                    let path = parent.to_string_lossy().to_string();
 393                    let path_and_file = format!("{}/{}", path, file_name);
 394
 395                    h_flex()
 396                        .id(("code-block-header-label", ix))
 397                        .ml_1()
 398                        .gap_1()
 399                        .child(div().text_size(label_size).child(file_name))
 400                        .child(Label::new(path).color(Color::Muted).size(LabelSize::Small))
 401                        .tooltip(move |window, cx| {
 402                            Tooltip::with_meta(
 403                                "Jump to File",
 404                                None,
 405                                path_and_file.clone(),
 406                                window,
 407                                cx,
 408                            )
 409                        })
 410                        .into_any_element()
 411                } else {
 412                    div()
 413                        .ml_1()
 414                        .text_size(label_size)
 415                        .child(path_range.path.to_string_lossy().to_string())
 416                        .into_any_element()
 417                };
 418
 419                h_flex()
 420                    .id(("code-block-header-button", ix))
 421                    .w_full()
 422                    .max_w_full()
 423                    .px_1()
 424                    .gap_0p5()
 425                    .cursor_pointer()
 426                    .rounded_sm()
 427                    .hover(|item| item.bg(cx.theme().colors().element_hover.opacity(0.5)))
 428                    .child(
 429                        h_flex()
 430                            .gap_0p5()
 431                            .children(
 432                                file_icons::FileIcons::get_icon(&path_range.path, cx)
 433                                    .map(Icon::from_path)
 434                                    .map(|icon| icon.color(Color::Muted).size(IconSize::XSmall)),
 435                            )
 436                            .child(content)
 437                            .child(
 438                                Icon::new(IconName::ArrowUpRight)
 439                                    .size(IconSize::XSmall)
 440                                    .color(Color::Ignored),
 441                            ),
 442                    )
 443                    .on_click({
 444                        let path_range = path_range.clone();
 445                        move |_, window, cx| {
 446                            workspace
 447                                .update(cx, |workspace, cx| {
 448                                    open_path(&path_range, window, workspace, cx)
 449                                })
 450                                .ok();
 451                        }
 452                    })
 453                    .into_any_element()
 454            }
 455        }),
 456    };
 457
 458    let codeblock_was_copied = active_thread
 459        .read(cx)
 460        .copied_code_block_ids
 461        .contains(&(message_id, ix));
 462
 463    let is_expanded = active_thread.read(cx).is_codeblock_expanded(message_id, ix);
 464
 465    let codeblock_header_bg = cx
 466        .theme()
 467        .colors()
 468        .element_background
 469        .blend(cx.theme().colors().editor_foreground.opacity(0.025));
 470
 471    let control_buttons = h_flex()
 472        .visible_on_hover(CODEBLOCK_CONTAINER_GROUP)
 473        .absolute()
 474        .top_0()
 475        .right_0()
 476        .h_full()
 477        .bg(codeblock_header_bg)
 478        .rounded_tr_md()
 479        .px_1()
 480        .gap_1()
 481        .child(
 482            IconButton::new(
 483                ("copy-markdown-code", ix),
 484                if codeblock_was_copied {
 485                    IconName::Check
 486                } else {
 487                    IconName::Copy
 488                },
 489            )
 490            .icon_color(Color::Muted)
 491            .shape(ui::IconButtonShape::Square)
 492            .tooltip(Tooltip::text("Copy Code"))
 493            .on_click({
 494                let active_thread = active_thread.clone();
 495                let parsed_markdown = parsed_markdown.clone();
 496                let code_block_range = metadata.content_range.clone();
 497                move |_event, _window, cx| {
 498                    active_thread.update(cx, |this, cx| {
 499                        this.copied_code_block_ids.insert((message_id, ix));
 500
 501                        let code = parsed_markdown.source()[code_block_range.clone()].to_string();
 502                        cx.write_to_clipboard(ClipboardItem::new_string(code));
 503
 504                        cx.spawn(async move |this, cx| {
 505                            cx.background_executor().timer(Duration::from_secs(2)).await;
 506
 507                            cx.update(|cx| {
 508                                this.update(cx, |this, cx| {
 509                                    this.copied_code_block_ids.remove(&(message_id, ix));
 510                                    cx.notify();
 511                                })
 512                            })
 513                            .ok();
 514                        })
 515                        .detach();
 516                    });
 517                }
 518            }),
 519        )
 520        .child(
 521            IconButton::new(
 522                ("expand-collapse-code", ix),
 523                if is_expanded {
 524                    IconName::ChevronUp
 525                } else {
 526                    IconName::ChevronDown
 527                },
 528            )
 529            .icon_color(Color::Muted)
 530            .shape(ui::IconButtonShape::Square)
 531            .tooltip(Tooltip::text(if is_expanded {
 532                "Collapse Code"
 533            } else {
 534                "Expand Code"
 535            }))
 536            .on_click({
 537                let active_thread = active_thread.clone();
 538                move |_event, _window, cx| {
 539                    active_thread.update(cx, |this, cx| {
 540                        this.toggle_codeblock_expanded(message_id, ix);
 541                        cx.notify();
 542                    });
 543                }
 544            }),
 545        );
 546
 547    let codeblock_header = h_flex()
 548        .relative()
 549        .p_1()
 550        .gap_1()
 551        .justify_between()
 552        .bg(codeblock_header_bg)
 553        .map(|this| {
 554            if !is_expanded {
 555                this.rounded_md()
 556            } else {
 557                this.rounded_t_md()
 558                    .border_b_1()
 559                    .border_color(cx.theme().colors().border.opacity(0.6))
 560            }
 561        })
 562        .children(label)
 563        .child(control_buttons);
 564
 565    v_flex()
 566        .group(CODEBLOCK_CONTAINER_GROUP)
 567        .my_2()
 568        .overflow_hidden()
 569        .rounded_md()
 570        .border_1()
 571        .border_color(cx.theme().colors().border.opacity(0.6))
 572        .bg(cx.theme().colors().editor_background)
 573        .child(codeblock_header)
 574        .when(!is_expanded, |this| this.h(rems_from_px(31.)))
 575}
 576
 577fn open_path(
 578    path_range: &PathWithRange,
 579    window: &mut Window,
 580    workspace: &mut Workspace,
 581    cx: &mut Context<'_, Workspace>,
 582) {
 583    let Some(project_path) = workspace
 584        .project()
 585        .read(cx)
 586        .find_project_path(&path_range.path, cx)
 587    else {
 588        return; // TODO instead of just bailing out, open that path in a buffer.
 589    };
 590
 591    let Some(target) = path_range.range.as_ref().map(|range| {
 592        Point::new(
 593            // Line number is 1-based
 594            range.start.line.saturating_sub(1),
 595            range.start.col.unwrap_or(0),
 596        )
 597    }) else {
 598        return;
 599    };
 600    let open_task = workspace.open_path(project_path, None, true, window, cx);
 601    window
 602        .spawn(cx, async move |cx| {
 603            let item = open_task.await?;
 604            if let Some(active_editor) = item.downcast::<Editor>() {
 605                active_editor
 606                    .update_in(cx, |editor, window, cx| {
 607                        editor.go_to_singleton_buffer_point(target, window, cx);
 608                    })
 609                    .ok();
 610            }
 611            anyhow::Ok(())
 612        })
 613        .detach_and_log_err(cx);
 614}
 615
 616fn render_code_language(
 617    language: Option<&Arc<Language>>,
 618    name_fallback: SharedString,
 619    cx: &App,
 620) -> AnyElement {
 621    let icon_path = language.and_then(|language| {
 622        language
 623            .config()
 624            .matcher
 625            .path_suffixes
 626            .iter()
 627            .find_map(|extension| file_icons::FileIcons::get_icon(Path::new(extension), cx))
 628            .map(Icon::from_path)
 629    });
 630
 631    let language_label = language
 632        .map(|language| language.name().into())
 633        .unwrap_or(name_fallback);
 634
 635    let label_size = rems(0.8125);
 636
 637    h_flex()
 638        .px_1()
 639        .gap_1p5()
 640        .children(icon_path.map(|icon| icon.color(Color::Muted).size(IconSize::XSmall)))
 641        .child(div().text_size(label_size).child(language_label))
 642        .into_any_element()
 643}
 644
 645fn open_markdown_link(
 646    text: SharedString,
 647    workspace: WeakEntity<Workspace>,
 648    window: &mut Window,
 649    cx: &mut App,
 650) {
 651    let Some(workspace) = workspace.upgrade() else {
 652        cx.open_url(&text);
 653        return;
 654    };
 655
 656    match MentionLink::try_parse(&text, &workspace, cx) {
 657        Some(MentionLink::File(path, entry)) => workspace.update(cx, |workspace, cx| {
 658            if entry.is_dir() {
 659                workspace.project().update(cx, |_, cx| {
 660                    cx.emit(project::Event::RevealInProjectPanel(entry.id));
 661                })
 662            } else {
 663                workspace
 664                    .open_path(path, None, true, window, cx)
 665                    .detach_and_log_err(cx);
 666            }
 667        }),
 668        Some(MentionLink::Symbol(path, symbol_name)) => {
 669            let open_task = workspace.update(cx, |workspace, cx| {
 670                workspace.open_path(path, None, true, window, cx)
 671            });
 672            window
 673                .spawn(cx, async move |cx| {
 674                    let active_editor = open_task
 675                        .await?
 676                        .downcast::<Editor>()
 677                        .context("Item is not an editor")?;
 678                    active_editor.update_in(cx, |editor, window, cx| {
 679                        let symbol_range = editor
 680                            .buffer()
 681                            .read(cx)
 682                            .snapshot(cx)
 683                            .outline(None)
 684                            .and_then(|outline| {
 685                                outline
 686                                    .find_most_similar(&symbol_name)
 687                                    .map(|(_, item)| item.range.clone())
 688                            })
 689                            .context("Could not find matching symbol")?;
 690
 691                        editor.change_selections(
 692                            SelectionEffects::scroll(Autoscroll::center()),
 693                            window,
 694                            cx,
 695                            |s| s.select_anchor_ranges([symbol_range.start..symbol_range.start]),
 696                        );
 697                        anyhow::Ok(())
 698                    })
 699                })
 700                .detach_and_log_err(cx);
 701        }
 702        Some(MentionLink::Selection(path, line_range)) => {
 703            let open_task = workspace.update(cx, |workspace, cx| {
 704                workspace.open_path(path, None, true, window, cx)
 705            });
 706            window
 707                .spawn(cx, async move |cx| {
 708                    let active_editor = open_task
 709                        .await?
 710                        .downcast::<Editor>()
 711                        .context("Item is not an editor")?;
 712                    active_editor.update_in(cx, |editor, window, cx| {
 713                        editor.change_selections(
 714                            SelectionEffects::scroll(Autoscroll::center()),
 715                            window,
 716                            cx,
 717                            |s| {
 718                                s.select_ranges([Point::new(line_range.start as u32, 0)
 719                                    ..Point::new(line_range.start as u32, 0)])
 720                            },
 721                        );
 722                        anyhow::Ok(())
 723                    })
 724                })
 725                .detach_and_log_err(cx);
 726        }
 727        Some(MentionLink::Thread(thread_id)) => workspace.update(cx, |workspace, cx| {
 728            if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 729                panel.update(cx, |panel, cx| {
 730                    panel
 731                        .open_thread_by_id(&thread_id, window, cx)
 732                        .detach_and_log_err(cx)
 733                });
 734            }
 735        }),
 736        Some(MentionLink::TextThread(path)) => workspace.update(cx, |workspace, cx| {
 737            if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 738                panel.update(cx, |panel, cx| {
 739                    panel
 740                        .open_saved_prompt_editor(path, window, cx)
 741                        .detach_and_log_err(cx);
 742                });
 743            }
 744        }),
 745        Some(MentionLink::Fetch(url)) => cx.open_url(&url),
 746        Some(MentionLink::Rule(prompt_id)) => window.dispatch_action(
 747            Box::new(OpenRulesLibrary {
 748                prompt_to_select: Some(prompt_id.0),
 749            }),
 750            cx,
 751        ),
 752        None => cx.open_url(&text),
 753    }
 754}
 755
 756struct EditingMessageState {
 757    editor: Entity<Editor>,
 758    context_strip: Entity<ContextStrip>,
 759    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 760    last_estimated_token_count: Option<u64>,
 761    _subscriptions: [Subscription; 2],
 762    _update_token_count_task: Option<Task<()>>,
 763}
 764
 765impl ActiveThread {
 766    pub fn new(
 767        thread: Entity<Thread>,
 768        thread_store: Entity<ThreadStore>,
 769        text_thread_store: Entity<TextThreadStore>,
 770        context_store: Entity<ContextStore>,
 771        language_registry: Arc<LanguageRegistry>,
 772        workspace: WeakEntity<Workspace>,
 773        window: &mut Window,
 774        cx: &mut Context<Self>,
 775    ) -> Self {
 776        let subscriptions = vec![
 777            cx.observe(&thread, |_, _, cx| cx.notify()),
 778            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 779            cx.subscribe(&thread_store, Self::handle_rules_loading_error),
 780            cx.observe_global::<SettingsStore>(|_, cx| cx.notify()),
 781        ];
 782
 783        let list_state = ListState::new(0, ListAlignment::Bottom, px(2048.), {
 784            let this = cx.entity().downgrade();
 785            move |ix, window: &mut Window, cx: &mut App| {
 786                this.update(cx, |this, cx| this.render_message(ix, window, cx))
 787                    .unwrap()
 788            }
 789        });
 790        let mut this = Self {
 791            language_registry,
 792            thread_store,
 793            text_thread_store,
 794            context_store,
 795            thread: thread.clone(),
 796            workspace,
 797            save_thread_task: None,
 798            messages: Vec::new(),
 799            rendered_messages_by_id: HashMap::default(),
 800            rendered_tool_uses: HashMap::default(),
 801            expanded_tool_uses: HashMap::default(),
 802            expanded_thinking_segments: HashMap::default(),
 803            expanded_code_blocks: HashMap::default(),
 804            list_state: list_state.clone(),
 805            scrollbar_state: ScrollbarState::new(list_state),
 806            show_scrollbar: false,
 807            hide_scrollbar_task: None,
 808            editing_message: None,
 809            last_error: None,
 810            copied_code_block_ids: HashSet::default(),
 811            notifications: Vec::new(),
 812            _subscriptions: subscriptions,
 813            notification_subscriptions: HashMap::default(),
 814            open_feedback_editors: HashMap::default(),
 815            _load_edited_message_context_task: None,
 816        };
 817
 818        for message in thread.read(cx).messages().cloned().collect::<Vec<_>>() {
 819            let rendered_message = RenderedMessage::from_segments(
 820                &message.segments,
 821                this.language_registry.clone(),
 822                cx,
 823            );
 824            this.push_rendered_message(message.id, rendered_message);
 825
 826            for tool_use in thread.read(cx).tool_uses_for_message(message.id, cx) {
 827                this.render_tool_use_markdown(
 828                    tool_use.id.clone(),
 829                    tool_use.ui_text.clone(),
 830                    &serde_json::to_string_pretty(&tool_use.input).unwrap_or_default(),
 831                    tool_use.status.text(),
 832                    cx,
 833                );
 834            }
 835        }
 836
 837        this
 838    }
 839
 840    pub fn thread(&self) -> &Entity<Thread> {
 841        &self.thread
 842    }
 843
 844    pub fn is_empty(&self) -> bool {
 845        self.messages.is_empty()
 846    }
 847
 848    pub fn summary<'a>(&'a self, cx: &'a App) -> &'a ThreadSummary {
 849        self.thread.read(cx).summary()
 850    }
 851
 852    pub fn regenerate_summary(&self, cx: &mut App) {
 853        self.thread.update(cx, |thread, cx| thread.summarize(cx))
 854    }
 855
 856    pub fn cancel_last_completion(&mut self, window: &mut Window, cx: &mut App) -> bool {
 857        self.last_error.take();
 858        self.thread.update(cx, |thread, cx| {
 859            thread.cancel_last_completion(Some(window.window_handle()), cx)
 860        })
 861    }
 862
 863    pub fn last_error(&self) -> Option<ThreadError> {
 864        self.last_error.clone()
 865    }
 866
 867    pub fn clear_last_error(&mut self) {
 868        self.last_error.take();
 869    }
 870
 871    /// Returns the editing message id and the estimated token count in the content
 872    pub fn editing_message_id(&self) -> Option<(MessageId, u64)> {
 873        self.editing_message
 874            .as_ref()
 875            .map(|(id, state)| (*id, state.last_estimated_token_count.unwrap_or(0)))
 876    }
 877
 878    pub fn context_store(&self) -> &Entity<ContextStore> {
 879        &self.context_store
 880    }
 881
 882    pub fn thread_store(&self) -> &Entity<ThreadStore> {
 883        &self.thread_store
 884    }
 885
 886    pub fn text_thread_store(&self) -> &Entity<TextThreadStore> {
 887        &self.text_thread_store
 888    }
 889
 890    fn push_rendered_message(&mut self, id: MessageId, rendered_message: RenderedMessage) {
 891        let old_len = self.messages.len();
 892        self.messages.push(id);
 893        self.list_state.splice(old_len..old_len, 1);
 894        self.rendered_messages_by_id.insert(id, rendered_message);
 895    }
 896
 897    fn deleted_message(&mut self, id: &MessageId) {
 898        let Some(index) = self.messages.iter().position(|message_id| message_id == id) else {
 899            return;
 900        };
 901        self.messages.remove(index);
 902        self.list_state.splice(index..index + 1, 0);
 903        self.rendered_messages_by_id.remove(id);
 904    }
 905
 906    fn render_tool_use_markdown(
 907        &mut self,
 908        tool_use_id: LanguageModelToolUseId,
 909        tool_label: impl Into<SharedString>,
 910        tool_input: &str,
 911        tool_output: SharedString,
 912        cx: &mut Context<Self>,
 913    ) {
 914        let rendered = self
 915            .rendered_tool_uses
 916            .entry(tool_use_id.clone())
 917            .or_insert_with(|| RenderedToolUse {
 918                label: cx.new(|cx| {
 919                    Markdown::new("".into(), Some(self.language_registry.clone()), None, cx)
 920                }),
 921                input: cx.new(|cx| {
 922                    Markdown::new("".into(), Some(self.language_registry.clone()), None, cx)
 923                }),
 924                output: cx.new(|cx| {
 925                    Markdown::new("".into(), Some(self.language_registry.clone()), None, cx)
 926                }),
 927            });
 928
 929        rendered.label.update(cx, |this, cx| {
 930            this.replace(tool_label, cx);
 931        });
 932        rendered.input.update(cx, |this, cx| {
 933            this.replace(
 934                MarkdownCodeBlock {
 935                    tag: "json",
 936                    text: tool_input,
 937                }
 938                .to_string(),
 939                cx,
 940            );
 941        });
 942        rendered.output.update(cx, |this, cx| {
 943            this.replace(tool_output, cx);
 944        });
 945    }
 946
 947    fn handle_thread_event(
 948        &mut self,
 949        _thread: &Entity<Thread>,
 950        event: &ThreadEvent,
 951        window: &mut Window,
 952        cx: &mut Context<Self>,
 953    ) {
 954        match event {
 955            ThreadEvent::CancelEditing => {
 956                if self.editing_message.is_some() {
 957                    self.cancel_editing_message(&menu::Cancel, window, cx);
 958                }
 959            }
 960            ThreadEvent::ShowError(error) => {
 961                self.last_error = Some(error.clone());
 962            }
 963            ThreadEvent::NewRequest => {
 964                cx.notify();
 965            }
 966            ThreadEvent::CompletionCanceled => {
 967                self.thread.update(cx, |thread, cx| {
 968                    thread.project().update(cx, |project, cx| {
 969                        project.set_agent_location(None, cx);
 970                    })
 971                });
 972                self.workspace
 973                    .update(cx, |workspace, cx| {
 974                        if workspace.is_being_followed(CollaboratorId::Agent) {
 975                            workspace.unfollow(CollaboratorId::Agent, window, cx);
 976                        }
 977                    })
 978                    .ok();
 979                cx.notify();
 980            }
 981            ThreadEvent::StreamedCompletion
 982            | ThreadEvent::SummaryGenerated
 983            | ThreadEvent::SummaryChanged => {
 984                self.save_thread(cx);
 985            }
 986            ThreadEvent::Stopped(reason) => {
 987                match reason {
 988                    Ok(StopReason::EndTurn | StopReason::MaxTokens) => {
 989                        let used_tools = self.thread.read(cx).used_tools_since_last_user_message();
 990                        self.notify_with_sound(
 991                            if used_tools {
 992                                "Finished running tools"
 993                            } else {
 994                                "New message"
 995                            },
 996                            IconName::ZedAssistant,
 997                            window,
 998                            cx,
 999                        );
1000                    }
1001                    Ok(StopReason::ToolUse) => {
1002                        // Don't notify for intermediate tool use
1003                    }
1004                    Ok(StopReason::Refusal) => {
1005                        self.notify_with_sound(
1006                            "Language model refused to respond",
1007                            IconName::Warning,
1008                            window,
1009                            cx,
1010                        );
1011                    }
1012                    Err(error) => {
1013                        self.notify_with_sound(
1014                            "Agent stopped due to an error",
1015                            IconName::Warning,
1016                            window,
1017                            cx,
1018                        );
1019
1020                        let error_message = error
1021                            .chain()
1022                            .map(|err| err.to_string())
1023                            .collect::<Vec<_>>()
1024                            .join("\n");
1025                        self.last_error = Some(ThreadError::Message {
1026                            header: "Error".into(),
1027                            message: error_message.into(),
1028                        });
1029                    }
1030                }
1031            }
1032            ThreadEvent::ToolConfirmationNeeded => {
1033                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1034            }
1035            ThreadEvent::ToolUseLimitReached => {
1036                self.notify_with_sound(
1037                    "Consecutive tool use limit reached.",
1038                    IconName::Warning,
1039                    window,
1040                    cx,
1041                );
1042            }
1043            ThreadEvent::StreamedAssistantText(message_id, text) => {
1044                if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
1045                    rendered_message.append_text(text, cx);
1046                }
1047            }
1048            ThreadEvent::StreamedAssistantThinking(message_id, text) => {
1049                if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
1050                    rendered_message.append_thinking(text, cx);
1051                }
1052            }
1053            ThreadEvent::MessageAdded(message_id) => {
1054                self.clear_last_error();
1055                if let Some(rendered_message) = self.thread.update(cx, |thread, cx| {
1056                    thread.message(*message_id).map(|message| {
1057                        RenderedMessage::from_segments(
1058                            &message.segments,
1059                            self.language_registry.clone(),
1060                            cx,
1061                        )
1062                    })
1063                }) {
1064                    self.push_rendered_message(*message_id, rendered_message);
1065                }
1066
1067                self.save_thread(cx);
1068                cx.notify();
1069            }
1070            ThreadEvent::MessageEdited(message_id) => {
1071                self.clear_last_error();
1072                if let Some(index) = self.messages.iter().position(|id| id == message_id) {
1073                    if let Some(rendered_message) = self.thread.update(cx, |thread, cx| {
1074                        thread.message(*message_id).map(|message| {
1075                            let mut rendered_message = RenderedMessage {
1076                                language_registry: self.language_registry.clone(),
1077                                segments: Vec::with_capacity(message.segments.len()),
1078                            };
1079                            for segment in &message.segments {
1080                                rendered_message.push_segment(segment, cx);
1081                            }
1082                            rendered_message
1083                        })
1084                    }) {
1085                        self.list_state.splice(index..index + 1, 1);
1086                        self.rendered_messages_by_id
1087                            .insert(*message_id, rendered_message);
1088                        self.scroll_to_bottom(cx);
1089                        self.save_thread(cx);
1090                        cx.notify();
1091                    }
1092                }
1093            }
1094            ThreadEvent::MessageDeleted(message_id) => {
1095                self.deleted_message(message_id);
1096                self.save_thread(cx);
1097                cx.notify();
1098            }
1099            ThreadEvent::UsePendingTools { tool_uses } => {
1100                for tool_use in tool_uses {
1101                    self.render_tool_use_markdown(
1102                        tool_use.id.clone(),
1103                        tool_use.ui_text.clone(),
1104                        &serde_json::to_string_pretty(&tool_use.input).unwrap_or_default(),
1105                        "".into(),
1106                        cx,
1107                    );
1108                }
1109            }
1110            ThreadEvent::StreamedToolUse {
1111                tool_use_id,
1112                ui_text,
1113                input,
1114            } => {
1115                self.render_tool_use_markdown(
1116                    tool_use_id.clone(),
1117                    ui_text.clone(),
1118                    &serde_json::to_string_pretty(&input).unwrap_or_default(),
1119                    "".into(),
1120                    cx,
1121                );
1122            }
1123            ThreadEvent::ToolFinished {
1124                pending_tool_use, ..
1125            } => {
1126                if let Some(tool_use) = pending_tool_use {
1127                    self.render_tool_use_markdown(
1128                        tool_use.id.clone(),
1129                        tool_use.ui_text.clone(),
1130                        &serde_json::to_string_pretty(&tool_use.input).unwrap_or_default(),
1131                        self.thread
1132                            .read(cx)
1133                            .output_for_tool(&tool_use.id)
1134                            .map(|output| output.clone().into())
1135                            .unwrap_or("".into()),
1136                        cx,
1137                    );
1138                }
1139            }
1140            ThreadEvent::CheckpointChanged => cx.notify(),
1141            ThreadEvent::ReceivedTextChunk => {}
1142            ThreadEvent::InvalidToolInput {
1143                tool_use_id,
1144                ui_text,
1145                invalid_input_json,
1146            } => {
1147                self.render_tool_use_markdown(
1148                    tool_use_id.clone(),
1149                    ui_text,
1150                    invalid_input_json,
1151                    self.thread
1152                        .read(cx)
1153                        .output_for_tool(tool_use_id)
1154                        .map(|output| output.clone().into())
1155                        .unwrap_or("".into()),
1156                    cx,
1157                );
1158            }
1159            ThreadEvent::MissingToolUse {
1160                tool_use_id,
1161                ui_text,
1162            } => {
1163                self.render_tool_use_markdown(
1164                    tool_use_id.clone(),
1165                    ui_text,
1166                    "",
1167                    self.thread
1168                        .read(cx)
1169                        .output_for_tool(tool_use_id)
1170                        .map(|output| output.clone().into())
1171                        .unwrap_or("".into()),
1172                    cx,
1173                );
1174            }
1175            ThreadEvent::ProfileChanged => {
1176                self.save_thread(cx);
1177                cx.notify();
1178            }
1179        }
1180    }
1181
1182    fn handle_rules_loading_error(
1183        &mut self,
1184        _thread_store: Entity<ThreadStore>,
1185        error: &RulesLoadingError,
1186        cx: &mut Context<Self>,
1187    ) {
1188        self.last_error = Some(ThreadError::Message {
1189            header: "Error loading rules file".into(),
1190            message: error.message.clone(),
1191        });
1192        cx.notify();
1193    }
1194
1195    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
1196        let settings = AgentSettings::get_global(cx);
1197        if settings.play_sound_when_agent_done && !window.is_window_active() {
1198            Audio::play_sound(Sound::AgentDone, cx);
1199        }
1200    }
1201
1202    fn show_notification(
1203        &mut self,
1204        caption: impl Into<SharedString>,
1205        icon: IconName,
1206        window: &mut Window,
1207        cx: &mut Context<ActiveThread>,
1208    ) {
1209        if window.is_window_active() || !self.notifications.is_empty() {
1210            return;
1211        }
1212
1213        let title = self.thread.read(cx).summary().unwrap_or("Agent Panel");
1214
1215        match AgentSettings::get_global(cx).notify_when_agent_waiting {
1216            NotifyWhenAgentWaiting::PrimaryScreen => {
1217                if let Some(primary) = cx.primary_display() {
1218                    self.pop_up(icon, caption.into(), title.clone(), window, primary, cx);
1219                }
1220            }
1221            NotifyWhenAgentWaiting::AllScreens => {
1222                let caption = caption.into();
1223                for screen in cx.displays() {
1224                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
1225                }
1226            }
1227            NotifyWhenAgentWaiting::Never => {
1228                // Don't show anything
1229            }
1230        }
1231    }
1232
1233    fn notify_with_sound(
1234        &mut self,
1235        caption: impl Into<SharedString>,
1236        icon: IconName,
1237        window: &mut Window,
1238        cx: &mut Context<ActiveThread>,
1239    ) {
1240        self.play_notification_sound(window, cx);
1241        self.show_notification(caption, icon, window, cx);
1242    }
1243
1244    fn pop_up(
1245        &mut self,
1246        icon: IconName,
1247        caption: SharedString,
1248        title: SharedString,
1249        window: &mut Window,
1250        screen: Rc<dyn PlatformDisplay>,
1251        cx: &mut Context<'_, ActiveThread>,
1252    ) {
1253        let options = AgentNotification::window_options(screen, cx);
1254
1255        let project_name = self.workspace.upgrade().and_then(|workspace| {
1256            workspace
1257                .read(cx)
1258                .project()
1259                .read(cx)
1260                .visible_worktrees(cx)
1261                .next()
1262                .map(|worktree| worktree.read(cx).root_name().to_string())
1263        });
1264
1265        if let Some(screen_window) = cx
1266            .open_window(options, |_, cx| {
1267                cx.new(|_| {
1268                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
1269                })
1270            })
1271            .log_err()
1272        {
1273            if let Some(pop_up) = screen_window.entity(cx).log_err() {
1274                self.notification_subscriptions
1275                    .entry(screen_window)
1276                    .or_insert_with(Vec::new)
1277                    .push(cx.subscribe_in(&pop_up, window, {
1278                        |this, _, event, window, cx| match event {
1279                            AgentNotificationEvent::Accepted => {
1280                                let handle = window.window_handle();
1281                                cx.activate(true);
1282
1283                                let workspace_handle = this.workspace.clone();
1284
1285                                // If there are multiple Zed windows, activate the correct one.
1286                                cx.defer(move |cx| {
1287                                    handle
1288                                        .update(cx, |_view, window, _cx| {
1289                                            window.activate_window();
1290
1291                                            if let Some(workspace) = workspace_handle.upgrade() {
1292                                                workspace.update(_cx, |workspace, cx| {
1293                                                    workspace.focus_panel::<AgentPanel>(window, cx);
1294                                                });
1295                                            }
1296                                        })
1297                                        .log_err();
1298                                });
1299
1300                                this.dismiss_notifications(cx);
1301                            }
1302                            AgentNotificationEvent::Dismissed => {
1303                                this.dismiss_notifications(cx);
1304                            }
1305                        }
1306                    }));
1307
1308                self.notifications.push(screen_window);
1309
1310                // If the user manually refocuses the original window, dismiss the popup.
1311                self.notification_subscriptions
1312                    .entry(screen_window)
1313                    .or_insert_with(Vec::new)
1314                    .push({
1315                        let pop_up_weak = pop_up.downgrade();
1316
1317                        cx.observe_window_activation(window, move |_, window, cx| {
1318                            if window.is_window_active() {
1319                                if let Some(pop_up) = pop_up_weak.upgrade() {
1320                                    pop_up.update(cx, |_, cx| {
1321                                        cx.emit(AgentNotificationEvent::Dismissed);
1322                                    });
1323                                }
1324                            }
1325                        })
1326                    });
1327            }
1328        }
1329    }
1330
1331    /// Spawns a task to save the active thread.
1332    ///
1333    /// Only one task to save the thread will be in flight at a time.
1334    fn save_thread(&mut self, cx: &mut Context<Self>) {
1335        let thread = self.thread.clone();
1336        self.save_thread_task = Some(cx.spawn(async move |this, cx| {
1337            let task = this
1338                .update(cx, |this, cx| {
1339                    this.thread_store
1340                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
1341                })
1342                .ok();
1343
1344            if let Some(task) = task {
1345                task.await.log_err();
1346            }
1347        }));
1348    }
1349
1350    fn start_editing_message(
1351        &mut self,
1352        message_id: MessageId,
1353        message_text: impl Into<Arc<str>>,
1354        message_creases: &[MessageCrease],
1355        window: &mut Window,
1356        cx: &mut Context<Self>,
1357    ) {
1358        let editor = crate::message_editor::create_editor(
1359            self.workspace.clone(),
1360            self.context_store.downgrade(),
1361            self.thread_store.downgrade(),
1362            self.text_thread_store.downgrade(),
1363            EDIT_PREVIOUS_MESSAGE_MIN_LINES,
1364            None,
1365            window,
1366            cx,
1367        );
1368        editor.update(cx, |editor, cx| {
1369            editor.set_text(message_text, window, cx);
1370            insert_message_creases(editor, message_creases, &self.context_store, window, cx);
1371            editor.focus_handle(cx).focus(window);
1372            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
1373        });
1374        let buffer_edited_subscription = cx.subscribe(&editor, |this, _, event, cx| match event {
1375            EditorEvent::BufferEdited => {
1376                this.update_editing_message_token_count(true, cx);
1377            }
1378            _ => {}
1379        });
1380
1381        let context_picker_menu_handle = PopoverMenuHandle::default();
1382        let context_strip = cx.new(|cx| {
1383            ContextStrip::new(
1384                self.context_store.clone(),
1385                self.workspace.clone(),
1386                Some(self.thread_store.downgrade()),
1387                Some(self.text_thread_store.downgrade()),
1388                context_picker_menu_handle.clone(),
1389                SuggestContextKind::File,
1390                ModelUsageContext::Thread(self.thread.clone()),
1391                window,
1392                cx,
1393            )
1394        });
1395
1396        let context_strip_subscription =
1397            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event);
1398
1399        self.editing_message = Some((
1400            message_id,
1401            EditingMessageState {
1402                editor: editor.clone(),
1403                context_strip,
1404                context_picker_menu_handle,
1405                last_estimated_token_count: None,
1406                _subscriptions: [buffer_edited_subscription, context_strip_subscription],
1407                _update_token_count_task: None,
1408            },
1409        ));
1410        self.update_editing_message_token_count(false, cx);
1411        cx.notify();
1412    }
1413
1414    fn handle_context_strip_event(
1415        &mut self,
1416        _context_strip: &Entity<ContextStrip>,
1417        event: &ContextStripEvent,
1418        window: &mut Window,
1419        cx: &mut Context<Self>,
1420    ) {
1421        if let Some((_, state)) = self.editing_message.as_ref() {
1422            match event {
1423                ContextStripEvent::PickerDismissed
1424                | ContextStripEvent::BlurredEmpty
1425                | ContextStripEvent::BlurredDown => {
1426                    let editor_focus_handle = state.editor.focus_handle(cx);
1427                    window.focus(&editor_focus_handle);
1428                }
1429                ContextStripEvent::BlurredUp => {}
1430            }
1431        }
1432    }
1433
1434    fn update_editing_message_token_count(&mut self, debounce: bool, cx: &mut Context<Self>) {
1435        let Some((message_id, state)) = self.editing_message.as_mut() else {
1436            return;
1437        };
1438
1439        cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1440        state._update_token_count_task.take();
1441
1442        let Some(configured_model) = self.thread.read(cx).configured_model() else {
1443            state.last_estimated_token_count.take();
1444            return;
1445        };
1446
1447        let editor = state.editor.clone();
1448        let thread = self.thread.clone();
1449        let message_id = *message_id;
1450
1451        state._update_token_count_task = Some(cx.spawn(async move |this, cx| {
1452            if debounce {
1453                cx.background_executor()
1454                    .timer(Duration::from_millis(200))
1455                    .await;
1456            }
1457
1458            let token_count = if let Some(task) = cx
1459                .update(|cx| {
1460                    let Some(message) = thread.read(cx).message(message_id) else {
1461                        log::error!("Message that was being edited no longer exists");
1462                        return None;
1463                    };
1464                    let message_text = editor.read(cx).text(cx);
1465
1466                    if message_text.is_empty() && message.loaded_context.is_empty() {
1467                        return None;
1468                    }
1469
1470                    let mut request_message = LanguageModelRequestMessage {
1471                        role: language_model::Role::User,
1472                        content: Vec::new(),
1473                        cache: false,
1474                    };
1475
1476                    message
1477                        .loaded_context
1478                        .add_to_request_message(&mut request_message);
1479
1480                    if !message_text.is_empty() {
1481                        request_message
1482                            .content
1483                            .push(MessageContent::Text(message_text));
1484                    }
1485
1486                    let request = language_model::LanguageModelRequest {
1487                        thread_id: None,
1488                        prompt_id: None,
1489                        intent: None,
1490                        mode: None,
1491                        messages: vec![request_message],
1492                        tools: vec![],
1493                        tool_choice: None,
1494                        stop: vec![],
1495                        temperature: AgentSettings::temperature_for_model(
1496                            &configured_model.model,
1497                            cx,
1498                        ),
1499                    };
1500
1501                    Some(configured_model.model.count_tokens(request, cx))
1502                })
1503                .ok()
1504                .flatten()
1505            {
1506                task.await.log_err()
1507            } else {
1508                Some(0)
1509            };
1510
1511            if let Some(token_count) = token_count {
1512                this.update(cx, |this, cx| {
1513                    let Some((_message_id, state)) = this.editing_message.as_mut() else {
1514                        return;
1515                    };
1516
1517                    state.last_estimated_token_count = Some(token_count);
1518                    cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1519                })
1520                .ok();
1521            };
1522        }));
1523    }
1524
1525    fn toggle_context_picker(
1526        &mut self,
1527        _: &crate::ToggleContextPicker,
1528        window: &mut Window,
1529        cx: &mut Context<Self>,
1530    ) {
1531        if let Some((_, state)) = self.editing_message.as_mut() {
1532            let handle = state.context_picker_menu_handle.clone();
1533            window.defer(cx, move |window, cx| {
1534                handle.toggle(window, cx);
1535            });
1536        }
1537    }
1538
1539    fn remove_all_context(
1540        &mut self,
1541        _: &crate::RemoveAllContext,
1542        _window: &mut Window,
1543        cx: &mut Context<Self>,
1544    ) {
1545        self.context_store.update(cx, |store, cx| store.clear(cx));
1546        cx.notify();
1547    }
1548
1549    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
1550        if let Some((_, state)) = self.editing_message.as_mut() {
1551            if state.context_picker_menu_handle.is_deployed() {
1552                cx.propagate();
1553            } else {
1554                state.context_strip.focus_handle(cx).focus(window);
1555            }
1556        }
1557    }
1558
1559    fn paste(&mut self, _: &Paste, _window: &mut Window, cx: &mut Context<Self>) {
1560        attach_pasted_images_as_context(&self.context_store, cx);
1561    }
1562
1563    fn cancel_editing_message(
1564        &mut self,
1565        _: &menu::Cancel,
1566        window: &mut Window,
1567        cx: &mut Context<Self>,
1568    ) {
1569        self.editing_message.take();
1570        cx.notify();
1571
1572        if let Some(workspace) = self.workspace.upgrade() {
1573            workspace.update(cx, |workspace, cx| {
1574                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
1575                    panel.focus_handle(cx).focus(window);
1576                }
1577            });
1578        }
1579    }
1580
1581    fn confirm_editing_message(
1582        &mut self,
1583        _: &menu::Confirm,
1584        window: &mut Window,
1585        cx: &mut Context<Self>,
1586    ) {
1587        let Some((message_id, state)) = self.editing_message.take() else {
1588            return;
1589        };
1590
1591        let Some(model) = self
1592            .thread
1593            .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
1594        else {
1595            return;
1596        };
1597
1598        if model.provider.must_accept_terms(cx) {
1599            cx.notify();
1600            return;
1601        }
1602
1603        let edited_text = state.editor.read(cx).text(cx);
1604
1605        let creases = state.editor.update(cx, extract_message_creases);
1606
1607        let new_context = self
1608            .context_store
1609            .read(cx)
1610            .new_context_for_thread(self.thread.read(cx), Some(message_id));
1611
1612        let project = self.thread.read(cx).project().clone();
1613        let prompt_store = self.thread_store.read(cx).prompt_store().clone();
1614
1615        let git_store = project.read(cx).git_store().clone();
1616        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
1617
1618        let load_context_task = context::load_context(new_context, &project, &prompt_store, cx);
1619        self._load_edited_message_context_task =
1620            Some(cx.spawn_in(window, async move |this, cx| {
1621                let (context, checkpoint) =
1622                    futures::future::join(load_context_task, checkpoint).await;
1623                let _ = this
1624                    .update_in(cx, |this, window, cx| {
1625                        this.thread.update(cx, |thread, cx| {
1626                            thread.edit_message(
1627                                message_id,
1628                                Role::User,
1629                                vec![MessageSegment::Text(edited_text)],
1630                                creases,
1631                                Some(context.loaded_context),
1632                                checkpoint.ok(),
1633                                cx,
1634                            );
1635                            for message_id in this.messages_after(message_id) {
1636                                thread.delete_message(*message_id, cx);
1637                            }
1638                        });
1639
1640                        this.thread.update(cx, |thread, cx| {
1641                            thread.advance_prompt_id();
1642                            thread.cancel_last_completion(Some(window.window_handle()), cx);
1643                            thread.send_to_model(
1644                                model.model,
1645                                CompletionIntent::UserPrompt,
1646                                Some(window.window_handle()),
1647                                cx,
1648                            );
1649                        });
1650                        this._load_edited_message_context_task = None;
1651                        cx.notify();
1652                    })
1653                    .log_err();
1654            }));
1655
1656        if let Some(workspace) = self.workspace.upgrade() {
1657            workspace.update(cx, |workspace, cx| {
1658                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
1659                    panel.focus_handle(cx).focus(window);
1660                }
1661            });
1662        }
1663    }
1664
1665    fn messages_after(&self, message_id: MessageId) -> &[MessageId] {
1666        self.messages
1667            .iter()
1668            .position(|id| *id == message_id)
1669            .map(|index| &self.messages[index + 1..])
1670            .unwrap_or(&[])
1671    }
1672
1673    fn handle_cancel_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1674        self.cancel_editing_message(&menu::Cancel, window, cx);
1675    }
1676
1677    fn handle_regenerate_click(
1678        &mut self,
1679        _: &ClickEvent,
1680        window: &mut Window,
1681        cx: &mut Context<Self>,
1682    ) {
1683        self.confirm_editing_message(&menu::Confirm, window, cx);
1684    }
1685
1686    fn handle_feedback_click(
1687        &mut self,
1688        message_id: MessageId,
1689        feedback: ThreadFeedback,
1690        window: &mut Window,
1691        cx: &mut Context<Self>,
1692    ) {
1693        let report = self.thread.update(cx, |thread, cx| {
1694            thread.report_message_feedback(message_id, feedback, cx)
1695        });
1696
1697        cx.spawn(async move |this, cx| {
1698            report.await?;
1699            this.update(cx, |_this, cx| cx.notify())
1700        })
1701        .detach_and_log_err(cx);
1702
1703        match feedback {
1704            ThreadFeedback::Positive => {
1705                self.open_feedback_editors.remove(&message_id);
1706            }
1707            ThreadFeedback::Negative => {
1708                self.handle_show_feedback_comments(message_id, window, cx);
1709            }
1710        }
1711    }
1712
1713    fn handle_show_feedback_comments(
1714        &mut self,
1715        message_id: MessageId,
1716        window: &mut Window,
1717        cx: &mut Context<Self>,
1718    ) {
1719        let buffer = cx.new(|cx| {
1720            let empty_string = String::new();
1721            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1722        });
1723
1724        let editor = cx.new(|cx| {
1725            let mut editor = Editor::new(
1726                editor::EditorMode::AutoHeight {
1727                    min_lines: 1,
1728                    max_lines: Some(4),
1729                },
1730                buffer,
1731                None,
1732                window,
1733                cx,
1734            );
1735            editor.set_placeholder_text(
1736                "What went wrong? Share your feedback so we can improve.",
1737                cx,
1738            );
1739            editor
1740        });
1741
1742        editor.read(cx).focus_handle(cx).focus(window);
1743        self.open_feedback_editors.insert(message_id, editor);
1744        cx.notify();
1745    }
1746
1747    fn submit_feedback_message(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
1748        let Some(editor) = self.open_feedback_editors.get(&message_id) else {
1749            return;
1750        };
1751
1752        let report_task = self.thread.update(cx, |thread, cx| {
1753            thread.report_message_feedback(message_id, ThreadFeedback::Negative, cx)
1754        });
1755
1756        let comments = editor.read(cx).text(cx);
1757        if !comments.is_empty() {
1758            let thread_id = self.thread.read(cx).id().clone();
1759            let comments_value = String::from(comments.as_str());
1760
1761            let message_content = self
1762                .thread
1763                .read(cx)
1764                .message(message_id)
1765                .map(|msg| msg.to_string())
1766                .unwrap_or_default();
1767
1768            telemetry::event!(
1769                "Assistant Thread Feedback Comments",
1770                thread_id,
1771                message_id = message_id.as_usize(),
1772                message_content,
1773                comments = comments_value
1774            );
1775
1776            self.open_feedback_editors.remove(&message_id);
1777
1778            cx.spawn(async move |this, cx| {
1779                report_task.await?;
1780                this.update(cx, |_this, cx| cx.notify())
1781            })
1782            .detach_and_log_err(cx);
1783        }
1784    }
1785
1786    fn render_edit_message_editor(
1787        &self,
1788        state: &EditingMessageState,
1789        _window: &mut Window,
1790        cx: &Context<Self>,
1791    ) -> impl IntoElement {
1792        let settings = ThemeSettings::get_global(cx);
1793        let font_size = TextSize::Small
1794            .rems(cx)
1795            .to_pixels(settings.agent_font_size(cx));
1796        let line_height = font_size * 1.75;
1797
1798        let colors = cx.theme().colors();
1799
1800        let text_style = TextStyle {
1801            color: colors.text,
1802            font_family: settings.buffer_font.family.clone(),
1803            font_fallbacks: settings.buffer_font.fallbacks.clone(),
1804            font_features: settings.buffer_font.features.clone(),
1805            font_size: font_size.into(),
1806            line_height: line_height.into(),
1807            ..Default::default()
1808        };
1809
1810        v_flex()
1811            .key_context("EditMessageEditor")
1812            .on_action(cx.listener(Self::toggle_context_picker))
1813            .on_action(cx.listener(Self::remove_all_context))
1814            .on_action(cx.listener(Self::move_up))
1815            .on_action(cx.listener(Self::cancel_editing_message))
1816            .on_action(cx.listener(Self::confirm_editing_message))
1817            .capture_action(cx.listener(Self::paste))
1818            .min_h_6()
1819            .w_full()
1820            .flex_grow()
1821            .gap_2()
1822            .child(state.context_strip.clone())
1823            .child(div().pt(px(-3.)).px_neg_0p5().child(EditorElement::new(
1824                &state.editor,
1825                EditorStyle {
1826                    background: colors.editor_background,
1827                    local_player: cx.theme().players().local(),
1828                    text: text_style,
1829                    syntax: cx.theme().syntax().clone(),
1830                    ..Default::default()
1831                },
1832            )))
1833    }
1834
1835    fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1836        let message_id = self.messages[ix];
1837        let workspace = self.workspace.clone();
1838        let thread = self.thread.read(cx);
1839
1840        let is_first_message = ix == 0;
1841        let is_last_message = ix == self.messages.len() - 1;
1842
1843        let Some(message) = thread.message(message_id) else {
1844            return Empty.into_any();
1845        };
1846
1847        let is_generating = thread.is_generating();
1848        let is_generating_stale = thread.is_generation_stale().unwrap_or(false);
1849
1850        let loading_dots = (is_generating && is_last_message).then(|| {
1851            h_flex()
1852                .h_8()
1853                .my_3()
1854                .mx_5()
1855                .when(is_generating_stale || message.is_hidden, |this| {
1856                    this.child(LoadingLabel::new("").size(LabelSize::Small))
1857                })
1858        });
1859
1860        if message.is_hidden {
1861            return div().children(loading_dots).into_any();
1862        }
1863
1864        let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1865            return Empty.into_any();
1866        };
1867
1868        // Get all the data we need from thread before we start using it in closures
1869        let checkpoint = thread.checkpoint_for_message(message_id);
1870        let configured_model = thread.configured_model().map(|m| m.model);
1871        let added_context = thread
1872            .context_for_message(message_id)
1873            .map(|context| AddedContext::new_attached(context, configured_model.as_ref(), cx))
1874            .collect::<Vec<_>>();
1875
1876        let tool_uses = thread.tool_uses_for_message(message_id, cx);
1877        let has_tool_uses = !tool_uses.is_empty();
1878
1879        let editing_message_state = self
1880            .editing_message
1881            .as_ref()
1882            .filter(|(id, _)| *id == message_id)
1883            .map(|(_, state)| state);
1884
1885        let (editor_bg_color, panel_bg) = {
1886            let colors = cx.theme().colors();
1887            (colors.editor_background, colors.panel_background)
1888        };
1889
1890        let open_as_markdown = IconButton::new(("open-as-markdown", ix), IconName::DocumentText)
1891            .icon_size(IconSize::XSmall)
1892            .icon_color(Color::Ignored)
1893            .tooltip(Tooltip::text("Open Thread as Markdown"))
1894            .on_click({
1895                let thread = self.thread.clone();
1896                let workspace = self.workspace.clone();
1897                move |_, window, cx| {
1898                    if let Some(workspace) = workspace.upgrade() {
1899                        open_active_thread_as_markdown(thread.clone(), workspace, window, cx)
1900                            .detach_and_log_err(cx);
1901                    }
1902                }
1903            });
1904
1905        let scroll_to_top = IconButton::new(("scroll_to_top", ix), IconName::ArrowUpAlt)
1906            .icon_size(IconSize::XSmall)
1907            .icon_color(Color::Ignored)
1908            .tooltip(Tooltip::text("Scroll To Top"))
1909            .on_click(cx.listener(move |this, _, _, cx| {
1910                this.scroll_to_top(cx);
1911            }));
1912
1913        let show_feedback = thread.is_turn_end(ix);
1914        let feedback_container = h_flex()
1915            .group("feedback_container")
1916            .mt_1()
1917            .py_2()
1918            .px(RESPONSE_PADDING_X)
1919            .mr_1()
1920            .opacity(0.4)
1921            .hover(|style| style.opacity(1.))
1922            .gap_1p5()
1923            .flex_wrap()
1924            .justify_end();
1925        let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1926            Some(feedback) => feedback_container
1927                .child(
1928                    div().visible_on_hover("feedback_container").child(
1929                        Label::new(match feedback {
1930                            ThreadFeedback::Positive => "Thanks for your feedback!",
1931                            ThreadFeedback::Negative => {
1932                                "We appreciate your feedback and will use it to improve."
1933                            }
1934                        })
1935                    .color(Color::Muted)
1936                    .size(LabelSize::XSmall)
1937                    .truncate())
1938                )
1939                .child(
1940                    h_flex()
1941                        .child(
1942                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1943                                .icon_size(IconSize::XSmall)
1944                                .icon_color(match feedback {
1945                                    ThreadFeedback::Positive => Color::Accent,
1946                                    ThreadFeedback::Negative => Color::Ignored,
1947                                })
1948                                .tooltip(Tooltip::text("Helpful Response"))
1949                                .on_click(cx.listener(move |this, _, window, cx| {
1950                                    this.handle_feedback_click(
1951                                        message_id,
1952                                        ThreadFeedback::Positive,
1953                                        window,
1954                                        cx,
1955                                    );
1956                                })),
1957                        )
1958                        .child(
1959                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1960                                .icon_size(IconSize::XSmall)
1961                                .icon_color(match feedback {
1962                                    ThreadFeedback::Positive => Color::Ignored,
1963                                    ThreadFeedback::Negative => Color::Accent,
1964                                })
1965                                .tooltip(Tooltip::text("Not Helpful"))
1966                                .on_click(cx.listener(move |this, _, window, cx| {
1967                                    this.handle_feedback_click(
1968                                        message_id,
1969                                        ThreadFeedback::Negative,
1970                                        window,
1971                                        cx,
1972                                    );
1973                                })),
1974                        )
1975                        .child(open_as_markdown),
1976                )
1977                .into_any_element(),
1978            None if AgentSettings::get_global(cx).enable_feedback =>
1979                feedback_container
1980                .child(
1981                    div().visible_on_hover("feedback_container").child(
1982                        Label::new(
1983                            "Rating the thread sends all of your current conversation to the Zed team.",
1984                        )
1985                        .color(Color::Muted)
1986                    .size(LabelSize::XSmall)
1987                    .truncate())
1988                )
1989                .child(
1990                    h_flex()
1991                        .child(
1992                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1993                                .icon_size(IconSize::XSmall)
1994                                .icon_color(Color::Ignored)
1995                                .tooltip(Tooltip::text("Helpful Response"))
1996                                .on_click(cx.listener(move |this, _, window, cx| {
1997                                    this.handle_feedback_click(
1998                                        message_id,
1999                                        ThreadFeedback::Positive,
2000                                        window,
2001                                        cx,
2002                                    );
2003                                })),
2004                        )
2005                        .child(
2006                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
2007                                .icon_size(IconSize::XSmall)
2008                                .icon_color(Color::Ignored)
2009                                .tooltip(Tooltip::text("Not Helpful"))
2010                                .on_click(cx.listener(move |this, _, window, cx| {
2011                                    this.handle_feedback_click(
2012                                        message_id,
2013                                        ThreadFeedback::Negative,
2014                                        window,
2015                                        cx,
2016                                    );
2017                                })),
2018                        )
2019                        .child(open_as_markdown)
2020                        .child(scroll_to_top),
2021                )
2022                .into_any_element(),
2023            None => feedback_container
2024                .child(h_flex()
2025                    .child(open_as_markdown))
2026                    .child(scroll_to_top)
2027                .into_any_element(),
2028        };
2029
2030        let message_is_empty = message.should_display_content();
2031        let has_content = !message_is_empty || !added_context.is_empty();
2032
2033        let message_content = has_content.then(|| {
2034            if let Some(state) = editing_message_state.as_ref() {
2035                self.render_edit_message_editor(state, window, cx)
2036                    .into_any_element()
2037            } else {
2038                v_flex()
2039                    .w_full()
2040                    .gap_1()
2041                    .when(!added_context.is_empty(), |parent| {
2042                        parent.child(h_flex().flex_wrap().gap_1().children(
2043                            added_context.into_iter().map(|added_context| {
2044                                let context = added_context.handle.clone();
2045                                ContextPill::added(added_context, false, false, None).on_click(
2046                                    Rc::new(cx.listener({
2047                                        let workspace = workspace.clone();
2048                                        move |_, _, window, cx| {
2049                                            if let Some(workspace) = workspace.upgrade() {
2050                                                open_context(&context, workspace, window, cx);
2051                                                cx.notify();
2052                                            }
2053                                        }
2054                                    })),
2055                                )
2056                            }),
2057                        ))
2058                    })
2059                    .when(!message_is_empty, |parent| {
2060                        parent.child(div().pt_0p5().min_h_6().child(self.render_message_content(
2061                            message_id,
2062                            rendered_message,
2063                            has_tool_uses,
2064                            workspace.clone(),
2065                            window,
2066                            cx,
2067                        )))
2068                    })
2069                    .into_any_element()
2070            }
2071        });
2072
2073        let styled_message = if message.ui_only {
2074            self.render_ui_notification(message_content, ix, cx)
2075        } else {
2076            match message.role {
2077                Role::User => {
2078                    let colors = cx.theme().colors();
2079                    v_flex()
2080                        .id(("message-container", ix))
2081                        .pt_2()
2082                        .pl_2()
2083                        .pr_2p5()
2084                        .pb_4()
2085                        .child(
2086                            v_flex()
2087                                .id(("user-message", ix))
2088                                .bg(editor_bg_color)
2089                                .rounded_lg()
2090                                .shadow_md()
2091                                .border_1()
2092                                .border_color(colors.border)
2093                                .hover(|hover| hover.border_color(colors.text_accent.opacity(0.5)))
2094                                .child(
2095                                    v_flex()
2096                                        .p_2p5()
2097                                        .gap_1()
2098                                        .children(message_content)
2099                                        .when_some(editing_message_state, |this, state| {
2100                                            let focus_handle = state.editor.focus_handle(cx).clone();
2101
2102                                            this.child(
2103                                                h_flex()
2104                                                    .w_full()
2105                                                    .gap_1()
2106                                                    .justify_between()
2107                                                    .flex_wrap()
2108                                                    .child(
2109                                                        h_flex()
2110                                                            .gap_1p5()
2111                                                            .child(
2112                                                                div()
2113                                                                    .opacity(0.8)
2114                                                                    .child(
2115                                                                        Icon::new(IconName::Warning)
2116                                                                            .size(IconSize::Indicator)
2117                                                                            .color(Color::Warning)
2118                                                                    ),
2119                                                            )
2120                                                            .child(
2121                                                                Label::new("Editing will restart the thread from this point.")
2122                                                                    .color(Color::Muted)
2123                                                                    .size(LabelSize::XSmall),
2124                                                            ),
2125                                                    )
2126                                                    .child(
2127                                                        h_flex()
2128                                                            .gap_0p5()
2129                                                            .child(
2130                                                                IconButton::new(
2131                                                                    "cancel-edit-message",
2132                                                                    IconName::Close,
2133                                                                )
2134                                                                .shape(ui::IconButtonShape::Square)
2135                                                                .icon_color(Color::Error)
2136                                                                .icon_size(IconSize::Small)
2137                                                                .tooltip({
2138                                                                    let focus_handle = focus_handle.clone();
2139                                                                    move |window, cx| {
2140                                                                        Tooltip::for_action_in(
2141                                                                            "Cancel Edit",
2142                                                                            &menu::Cancel,
2143                                                                            &focus_handle,
2144                                                                            window,
2145                                                                            cx,
2146                                                                        )
2147                                                                    }
2148                                                                })
2149                                                                .on_click(cx.listener(Self::handle_cancel_click)),
2150                                                            )
2151                                                            .child(
2152                                                                IconButton::new(
2153                                                                    "confirm-edit-message",
2154                                                                    IconName::Return,
2155                                                                )
2156                                                                .disabled(state.editor.read(cx).is_empty(cx))
2157                                                                .shape(ui::IconButtonShape::Square)
2158                                                                .icon_color(Color::Muted)
2159                                                                .icon_size(IconSize::Small)
2160                                                                .tooltip({
2161                                                                    let focus_handle = focus_handle.clone();
2162                                                                    move |window, cx| {
2163                                                                        Tooltip::for_action_in(
2164                                                                            "Regenerate",
2165                                                                            &menu::Confirm,
2166                                                                            &focus_handle,
2167                                                                            window,
2168                                                                            cx,
2169                                                                        )
2170                                                                    }
2171                                                                })
2172                                                                .on_click(
2173                                                                    cx.listener(Self::handle_regenerate_click),
2174                                                                ),
2175                                                            ),
2176                                                    )
2177                                            )
2178                                        }),
2179                                )
2180                                .on_click(cx.listener({
2181                                    let message_creases = message.creases.clone();
2182                                    move |this, _, window, cx| {
2183                                        if let Some(message_text) =
2184                                            this.thread.read(cx).message(message_id).and_then(|message| {
2185                                                message.segments.first().and_then(|segment| {
2186                                                    match segment {
2187                                                        MessageSegment::Text(message_text) => {
2188                                                            Some(Into::<Arc<str>>::into(message_text.as_str()))
2189                                                        }
2190                                                        _ => {
2191                                                            None
2192                                                        }
2193                                                    }
2194                                                })
2195                                            })
2196                                        {
2197                                            this.start_editing_message(
2198                                                message_id,
2199                                                message_text,
2200                                                &message_creases,
2201                                                window,
2202                                                cx,
2203                                            );
2204                                        }
2205                                    }
2206                                })),
2207                        )
2208                }
2209                Role::Assistant => v_flex()
2210                    .id(("message-container", ix))
2211                    .px(RESPONSE_PADDING_X)
2212                    .gap_2()
2213                    .children(message_content)
2214                    .when(has_tool_uses, |parent| {
2215                        parent.children(tool_uses.into_iter().map(|tool_use| {
2216                            self.render_tool_use(tool_use, window, workspace.clone(), cx)
2217                        }))
2218                    }),
2219                Role::System => {
2220                    let colors = cx.theme().colors();
2221                    div().id(("message-container", ix)).py_1().px_2().child(
2222                        v_flex()
2223                            .bg(colors.editor_background)
2224                            .rounded_sm()
2225                            .child(div().p_4().children(message_content)),
2226                    )
2227                }
2228            }
2229        };
2230
2231        let after_editing_message = self
2232            .editing_message
2233            .as_ref()
2234            .map_or(false, |(editing_message_id, _)| {
2235                message_id > *editing_message_id
2236            });
2237
2238        let backdrop = div()
2239            .id(("backdrop", ix))
2240            .size_full()
2241            .absolute()
2242            .inset_0()
2243            .bg(panel_bg)
2244            .opacity(0.8)
2245            .block_mouse_except_scroll()
2246            .on_click(cx.listener(Self::handle_cancel_click));
2247
2248        v_flex()
2249            .w_full()
2250            .map(|parent| {
2251                if let Some(checkpoint) = checkpoint.filter(|_| !is_generating) {
2252                    let mut is_pending = false;
2253                    let mut error = None;
2254                    if let Some(last_restore_checkpoint) =
2255                        self.thread.read(cx).last_restore_checkpoint()
2256                    {
2257                        if last_restore_checkpoint.message_id() == message_id {
2258                            match last_restore_checkpoint {
2259                                LastRestoreCheckpoint::Pending { .. } => is_pending = true,
2260                                LastRestoreCheckpoint::Error { error: err, .. } => {
2261                                    error = Some(err.clone());
2262                                }
2263                            }
2264                        }
2265                    }
2266
2267                    let restore_checkpoint_button =
2268                        Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
2269                            .icon(if error.is_some() {
2270                                IconName::XCircle
2271                            } else {
2272                                IconName::Undo
2273                            })
2274                            .icon_size(IconSize::XSmall)
2275                            .icon_position(IconPosition::Start)
2276                            .icon_color(if error.is_some() {
2277                                Some(Color::Error)
2278                            } else {
2279                                None
2280                            })
2281                            .label_size(LabelSize::XSmall)
2282                            .disabled(is_pending)
2283                            .on_click(cx.listener(move |this, _, _window, cx| {
2284                                this.thread.update(cx, |thread, cx| {
2285                                    thread
2286                                        .restore_checkpoint(checkpoint.clone(), cx)
2287                                        .detach_and_log_err(cx);
2288                                });
2289                            }));
2290
2291                    let restore_checkpoint_button = if is_pending {
2292                        restore_checkpoint_button
2293                            .with_animation(
2294                                ("pulsating-restore-checkpoint-button", ix),
2295                                Animation::new(Duration::from_secs(2))
2296                                    .repeat()
2297                                    .with_easing(pulsating_between(0.6, 1.)),
2298                                |label, delta| label.alpha(delta),
2299                            )
2300                            .into_any_element()
2301                    } else if let Some(error) = error {
2302                        restore_checkpoint_button
2303                            .tooltip(Tooltip::text(error.to_string()))
2304                            .into_any_element()
2305                    } else {
2306                        restore_checkpoint_button.into_any_element()
2307                    };
2308
2309                    parent.child(
2310                        h_flex()
2311                            .pt_2p5()
2312                            .px_2p5()
2313                            .w_full()
2314                            .gap_1()
2315                            .child(ui::Divider::horizontal())
2316                            .child(restore_checkpoint_button)
2317                            .child(ui::Divider::horizontal()),
2318                    )
2319                } else {
2320                    parent
2321                }
2322            })
2323            .when(is_first_message, |parent| {
2324                parent.child(self.render_rules_item(cx))
2325            })
2326            .child(styled_message)
2327            .children(loading_dots)
2328            .when(show_feedback, move |parent| {
2329                parent.child(feedback_items).when_some(
2330                    self.open_feedback_editors.get(&message_id),
2331                    move |parent, feedback_editor| {
2332                        let focus_handle = feedback_editor.focus_handle(cx);
2333                        parent.child(
2334                            v_flex()
2335                                .key_context("AgentFeedbackMessageEditor")
2336                                .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2337                                    this.open_feedback_editors.remove(&message_id);
2338                                    cx.notify();
2339                                }))
2340                                .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2341                                    this.submit_feedback_message(message_id, cx);
2342                                    cx.notify();
2343                                }))
2344                                .on_action(cx.listener(Self::confirm_editing_message))
2345                                .mb_2()
2346                                .mx_4()
2347                                .p_2()
2348                                .rounded_md()
2349                                .border_1()
2350                                .border_color(cx.theme().colors().border)
2351                                .bg(cx.theme().colors().editor_background)
2352                                .child(feedback_editor.clone())
2353                                .child(
2354                                    h_flex()
2355                                        .gap_1()
2356                                        .justify_end()
2357                                        .child(
2358                                            Button::new("dismiss-feedback-message", "Cancel")
2359                                                .label_size(LabelSize::Small)
2360                                                .key_binding(
2361                                                    KeyBinding::for_action_in(
2362                                                        &menu::Cancel,
2363                                                        &focus_handle,
2364                                                        window,
2365                                                        cx,
2366                                                    )
2367                                                    .map(|kb| kb.size(rems_from_px(10.))),
2368                                                )
2369                                                .on_click(cx.listener(
2370                                                    move |this, _, _window, cx| {
2371                                                        this.open_feedback_editors
2372                                                            .remove(&message_id);
2373                                                        cx.notify();
2374                                                    },
2375                                                )),
2376                                        )
2377                                        .child(
2378                                            Button::new(
2379                                                "submit-feedback-message",
2380                                                "Share Feedback",
2381                                            )
2382                                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2383                                            .label_size(LabelSize::Small)
2384                                            .key_binding(
2385                                                KeyBinding::for_action_in(
2386                                                    &menu::Confirm,
2387                                                    &focus_handle,
2388                                                    window,
2389                                                    cx,
2390                                                )
2391                                                .map(|kb| kb.size(rems_from_px(10.))),
2392                                            )
2393                                            .on_click(
2394                                                cx.listener(move |this, _, _window, cx| {
2395                                                    this.submit_feedback_message(message_id, cx);
2396                                                    cx.notify()
2397                                                }),
2398                                            ),
2399                                        ),
2400                                ),
2401                        )
2402                    },
2403                )
2404            })
2405            .when(after_editing_message, |parent| {
2406                // Backdrop to dim out the whole thread below the editing user message
2407                parent.relative().child(backdrop)
2408            })
2409            .into_any()
2410    }
2411
2412    fn render_message_content(
2413        &self,
2414        message_id: MessageId,
2415        rendered_message: &RenderedMessage,
2416        has_tool_uses: bool,
2417        workspace: WeakEntity<Workspace>,
2418        window: &Window,
2419        cx: &Context<Self>,
2420    ) -> impl IntoElement {
2421        let is_last_message = self.messages.last() == Some(&message_id);
2422        let is_generating = self.thread.read(cx).is_generating();
2423        let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2424            rendered_message
2425                .segments
2426                .iter()
2427                .enumerate()
2428                .next_back()
2429                .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2430                .map(|(index, _)| index)
2431        } else {
2432            None
2433        };
2434
2435        let message_role = self
2436            .thread
2437            .read(cx)
2438            .message(message_id)
2439            .map(|m| m.role)
2440            .unwrap_or(Role::User);
2441
2442        let is_assistant_message = message_role == Role::Assistant;
2443        let is_user_message = message_role == Role::User;
2444
2445        v_flex()
2446            .text_ui(cx)
2447            .gap_2()
2448            .when(is_user_message, |this| this.text_xs())
2449            .children(
2450                rendered_message.segments.iter().enumerate().map(
2451                    |(index, segment)| match segment {
2452                        RenderedMessageSegment::Thinking {
2453                            content,
2454                            scroll_handle,
2455                        } => self
2456                            .render_message_thinking_segment(
2457                                message_id,
2458                                index,
2459                                content.clone(),
2460                                &scroll_handle,
2461                                Some(index) == pending_thinking_segment_index,
2462                                window,
2463                                cx,
2464                            )
2465                            .into_any_element(),
2466                        RenderedMessageSegment::Text(markdown) => {
2467                            let markdown_element = MarkdownElement::new(
2468                                markdown.clone(),
2469                                if is_user_message {
2470                                    let mut style = default_markdown_style(window, cx);
2471                                    let mut text_style = window.text_style();
2472                                    let theme_settings = ThemeSettings::get_global(cx);
2473
2474                                    let buffer_font = theme_settings.buffer_font.family.clone();
2475                                    let buffer_font_size = TextSize::Small.rems(cx);
2476
2477                                    text_style.refine(&TextStyleRefinement {
2478                                        font_family: Some(buffer_font),
2479                                        font_size: Some(buffer_font_size.into()),
2480                                        ..Default::default()
2481                                    });
2482
2483                                    style.base_text_style = text_style;
2484                                    style
2485                                } else {
2486                                    default_markdown_style(window, cx)
2487                                },
2488                            );
2489
2490                            let markdown_element = if is_assistant_message {
2491                                markdown_element.code_block_renderer(
2492                                    markdown::CodeBlockRenderer::Custom {
2493                                        render: Arc::new({
2494                                            let workspace = workspace.clone();
2495                                            let active_thread = cx.entity();
2496                                            move |kind,
2497                                                  parsed_markdown,
2498                                                  range,
2499                                                  metadata,
2500                                                  window,
2501                                                  cx| {
2502                                                render_markdown_code_block(
2503                                                    message_id,
2504                                                    range.start,
2505                                                    kind,
2506                                                    parsed_markdown,
2507                                                    metadata,
2508                                                    active_thread.clone(),
2509                                                    workspace.clone(),
2510                                                    window,
2511                                                    cx,
2512                                                )
2513                                            }
2514                                        }),
2515                                        transform: Some(Arc::new({
2516                                            let active_thread = cx.entity();
2517
2518                                            move |element, range, _, _, cx| {
2519                                                let is_expanded = active_thread
2520                                                    .read(cx)
2521                                                    .is_codeblock_expanded(message_id, range.start);
2522
2523                                                if is_expanded {
2524                                                    return element;
2525                                                }
2526
2527                                                element
2528                                            }
2529                                        })),
2530                                    },
2531                                )
2532                            } else {
2533                                markdown_element.code_block_renderer(
2534                                    markdown::CodeBlockRenderer::Default {
2535                                        copy_button: false,
2536                                        copy_button_on_hover: false,
2537                                        border: true,
2538                                    },
2539                                )
2540                            };
2541
2542                            div()
2543                                .child(markdown_element.on_url_click({
2544                                    let workspace = self.workspace.clone();
2545                                    move |text, window, cx| {
2546                                        open_markdown_link(text, workspace.clone(), window, cx);
2547                                    }
2548                                }))
2549                                .into_any_element()
2550                        }
2551                    },
2552                ),
2553            )
2554    }
2555
2556    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2557        cx.theme().colors().border.opacity(0.5)
2558    }
2559
2560    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2561        cx.theme()
2562            .colors()
2563            .element_background
2564            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2565    }
2566
2567    fn render_ui_notification(
2568        &self,
2569        message_content: impl IntoIterator<Item = impl IntoElement>,
2570        ix: usize,
2571        cx: &mut Context<Self>,
2572    ) -> Stateful<Div> {
2573        let message = div()
2574            .flex_1()
2575            .min_w_0()
2576            .text_size(TextSize::XSmall.rems(cx))
2577            .text_color(cx.theme().colors().text_muted)
2578            .children(message_content);
2579
2580        div()
2581            .id(("message-container", ix))
2582            .py_1()
2583            .px_2p5()
2584            .child(Banner::new().severity(ui::Severity::Warning).child(message))
2585    }
2586
2587    fn render_message_thinking_segment(
2588        &self,
2589        message_id: MessageId,
2590        ix: usize,
2591        markdown: Entity<Markdown>,
2592        scroll_handle: &ScrollHandle,
2593        pending: bool,
2594        window: &Window,
2595        cx: &Context<Self>,
2596    ) -> impl IntoElement {
2597        let is_open = self
2598            .expanded_thinking_segments
2599            .get(&(message_id, ix))
2600            .copied()
2601            .unwrap_or_default();
2602
2603        let editor_bg = cx.theme().colors().panel_background;
2604
2605        div().map(|this| {
2606            if pending {
2607                this.v_flex()
2608                    .mt_neg_2()
2609                    .mb_1p5()
2610                    .child(
2611                        h_flex()
2612                            .group("disclosure-header")
2613                            .justify_between()
2614                            .child(
2615                                h_flex()
2616                                    .gap_1p5()
2617                                    .child(
2618                                        Icon::new(IconName::LightBulb)
2619                                            .size(IconSize::XSmall)
2620                                            .color(Color::Muted),
2621                                    )
2622                                    .child(LoadingLabel::new("Thinking").size(LabelSize::Small)),
2623                            )
2624                            .child(
2625                                h_flex()
2626                                    .gap_1()
2627                                    .child(
2628                                        div().visible_on_hover("disclosure-header").child(
2629                                            Disclosure::new("thinking-disclosure", is_open)
2630                                                .opened_icon(IconName::ChevronUp)
2631                                                .closed_icon(IconName::ChevronDown)
2632                                                .on_click(cx.listener({
2633                                                    move |this, _event, _window, _cx| {
2634                                                        let is_open = this
2635                                                            .expanded_thinking_segments
2636                                                            .entry((message_id, ix))
2637                                                            .or_insert(false);
2638
2639                                                        *is_open = !*is_open;
2640                                                    }
2641                                                })),
2642                                        ),
2643                                    )
2644                                    .child({
2645                                        Icon::new(IconName::ArrowCircle)
2646                                            .color(Color::Accent)
2647                                            .size(IconSize::Small)
2648                                            .with_animation(
2649                                                "arrow-circle",
2650                                                Animation::new(Duration::from_secs(2)).repeat(),
2651                                                |icon, delta| {
2652                                                    icon.transform(Transformation::rotate(
2653                                                        percentage(delta),
2654                                                    ))
2655                                                },
2656                                            )
2657                                    }),
2658                            ),
2659                    )
2660                    .when(!is_open, |this| {
2661                        let gradient_overlay = div()
2662                            .rounded_b_lg()
2663                            .h_full()
2664                            .absolute()
2665                            .w_full()
2666                            .bottom_0()
2667                            .left_0()
2668                            .bg(linear_gradient(
2669                                180.,
2670                                linear_color_stop(editor_bg, 1.),
2671                                linear_color_stop(editor_bg.opacity(0.2), 0.),
2672                            ));
2673
2674                        this.child(
2675                            div()
2676                                .relative()
2677                                .bg(editor_bg)
2678                                .rounded_b_lg()
2679                                .mt_2()
2680                                .pl_4()
2681                                .child(
2682                                    div()
2683                                        .id(("thinking-content", ix))
2684                                        .max_h_20()
2685                                        .track_scroll(scroll_handle)
2686                                        .text_ui_sm(cx)
2687                                        .overflow_hidden()
2688                                        .child(
2689                                            MarkdownElement::new(
2690                                                markdown.clone(),
2691                                                default_markdown_style(window, cx),
2692                                            )
2693                                            .on_url_click({
2694                                                let workspace = self.workspace.clone();
2695                                                move |text, window, cx| {
2696                                                    open_markdown_link(
2697                                                        text,
2698                                                        workspace.clone(),
2699                                                        window,
2700                                                        cx,
2701                                                    );
2702                                                }
2703                                            }),
2704                                        ),
2705                                )
2706                                .child(gradient_overlay),
2707                        )
2708                    })
2709                    .when(is_open, |this| {
2710                        this.child(
2711                            div()
2712                                .id(("thinking-content", ix))
2713                                .h_full()
2714                                .bg(editor_bg)
2715                                .text_ui_sm(cx)
2716                                .child(
2717                                    MarkdownElement::new(
2718                                        markdown.clone(),
2719                                        default_markdown_style(window, cx),
2720                                    )
2721                                    .on_url_click({
2722                                        let workspace = self.workspace.clone();
2723                                        move |text, window, cx| {
2724                                            open_markdown_link(text, workspace.clone(), window, cx);
2725                                        }
2726                                    }),
2727                                ),
2728                        )
2729                    })
2730            } else {
2731                this.v_flex()
2732                    .mt_neg_2()
2733                    .child(
2734                        h_flex()
2735                            .group("disclosure-header")
2736                            .pr_1()
2737                            .justify_between()
2738                            .opacity(0.8)
2739                            .hover(|style| style.opacity(1.))
2740                            .child(
2741                                h_flex()
2742                                    .gap_1p5()
2743                                    .child(
2744                                        Icon::new(IconName::LightBulb)
2745                                            .size(IconSize::XSmall)
2746                                            .color(Color::Muted),
2747                                    )
2748                                    .child(Label::new("Thought Process").size(LabelSize::Small)),
2749                            )
2750                            .child(
2751                                div().visible_on_hover("disclosure-header").child(
2752                                    Disclosure::new("thinking-disclosure", is_open)
2753                                        .opened_icon(IconName::ChevronUp)
2754                                        .closed_icon(IconName::ChevronDown)
2755                                        .on_click(cx.listener({
2756                                            move |this, _event, _window, _cx| {
2757                                                let is_open = this
2758                                                    .expanded_thinking_segments
2759                                                    .entry((message_id, ix))
2760                                                    .or_insert(false);
2761
2762                                                *is_open = !*is_open;
2763                                            }
2764                                        })),
2765                                ),
2766                            ),
2767                    )
2768                    .child(
2769                        div()
2770                            .id(("thinking-content", ix))
2771                            .relative()
2772                            .mt_1p5()
2773                            .ml_1p5()
2774                            .pl_2p5()
2775                            .border_l_1()
2776                            .border_color(cx.theme().colors().border_variant)
2777                            .text_ui_sm(cx)
2778                            .when(is_open, |this| {
2779                                this.child(
2780                                    MarkdownElement::new(
2781                                        markdown.clone(),
2782                                        default_markdown_style(window, cx),
2783                                    )
2784                                    .on_url_click({
2785                                        let workspace = self.workspace.clone();
2786                                        move |text, window, cx| {
2787                                            open_markdown_link(text, workspace.clone(), window, cx);
2788                                        }
2789                                    }),
2790                                )
2791                            }),
2792                    )
2793            }
2794        })
2795    }
2796
2797    fn render_tool_use(
2798        &self,
2799        tool_use: ToolUse,
2800        window: &mut Window,
2801        workspace: WeakEntity<Workspace>,
2802        cx: &mut Context<Self>,
2803    ) -> impl IntoElement + use<> {
2804        if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2805            return card.render(&tool_use.status, window, workspace, cx);
2806        }
2807
2808        let is_open = self
2809            .expanded_tool_uses
2810            .get(&tool_use.id)
2811            .copied()
2812            .unwrap_or_default();
2813
2814        let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2815
2816        let fs = self
2817            .workspace
2818            .upgrade()
2819            .map(|workspace| workspace.read(cx).app_state().fs.clone());
2820        let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2821        let needs_confirmation_tools = tool_use.needs_confirmation;
2822
2823        let status_icons = div().child(match &tool_use.status {
2824            ToolUseStatus::NeedsConfirmation => {
2825                let icon = Icon::new(IconName::Warning)
2826                    .color(Color::Warning)
2827                    .size(IconSize::Small);
2828                icon.into_any_element()
2829            }
2830            ToolUseStatus::Pending
2831            | ToolUseStatus::InputStillStreaming
2832            | ToolUseStatus::Running => {
2833                let icon = Icon::new(IconName::ArrowCircle)
2834                    .color(Color::Accent)
2835                    .size(IconSize::Small);
2836                icon.with_animation(
2837                    "arrow-circle",
2838                    Animation::new(Duration::from_secs(2)).repeat(),
2839                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2840                )
2841                .into_any_element()
2842            }
2843            ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2844            ToolUseStatus::Error(_) => {
2845                let icon = Icon::new(IconName::Close)
2846                    .color(Color::Error)
2847                    .size(IconSize::Small);
2848                icon.into_any_element()
2849            }
2850        });
2851
2852        let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2853        let results_content_container = || v_flex().p_2().gap_0p5();
2854
2855        let results_content = v_flex()
2856            .gap_1()
2857            .child(
2858                results_content_container()
2859                    .child(
2860                        Label::new("Input")
2861                            .size(LabelSize::XSmall)
2862                            .color(Color::Muted)
2863                            .buffer_font(cx),
2864                    )
2865                    .child(
2866                        div()
2867                            .w_full()
2868                            .text_ui_sm(cx)
2869                            .children(rendered_tool_use.as_ref().map(|rendered| {
2870                                MarkdownElement::new(
2871                                    rendered.input.clone(),
2872                                    tool_use_markdown_style(window, cx),
2873                                )
2874                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2875                                    copy_button: false,
2876                                    copy_button_on_hover: false,
2877                                    border: false,
2878                                })
2879                                .on_url_click({
2880                                    let workspace = self.workspace.clone();
2881                                    move |text, window, cx| {
2882                                        open_markdown_link(text, workspace.clone(), window, cx);
2883                                    }
2884                                })
2885                            })),
2886                    ),
2887            )
2888            .map(|container| match tool_use.status {
2889                ToolUseStatus::Finished(_) => container.child(
2890                    results_content_container()
2891                        .border_t_1()
2892                        .border_color(self.tool_card_border_color(cx))
2893                        .child(
2894                            Label::new("Result")
2895                                .size(LabelSize::XSmall)
2896                                .color(Color::Muted)
2897                                .buffer_font(cx),
2898                        )
2899                        .child(div().w_full().text_ui_sm(cx).children(
2900                            rendered_tool_use.as_ref().map(|rendered| {
2901                                MarkdownElement::new(
2902                                    rendered.output.clone(),
2903                                    tool_use_markdown_style(window, cx),
2904                                )
2905                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2906                                    copy_button: false,
2907                                    copy_button_on_hover: false,
2908                                    border: false,
2909                                })
2910                                .on_url_click({
2911                                    let workspace = self.workspace.clone();
2912                                    move |text, window, cx| {
2913                                        open_markdown_link(text, workspace.clone(), window, cx);
2914                                    }
2915                                })
2916                                .into_any_element()
2917                            }),
2918                        )),
2919                ),
2920                ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2921                    results_content_container()
2922                        .border_t_1()
2923                        .border_color(self.tool_card_border_color(cx))
2924                        .child(
2925                            h_flex()
2926                                .gap_1()
2927                                .child(
2928                                    Icon::new(IconName::ArrowCircle)
2929                                        .size(IconSize::Small)
2930                                        .color(Color::Accent)
2931                                        .with_animation(
2932                                            "arrow-circle",
2933                                            Animation::new(Duration::from_secs(2)).repeat(),
2934                                            |icon, delta| {
2935                                                icon.transform(Transformation::rotate(percentage(
2936                                                    delta,
2937                                                )))
2938                                            },
2939                                        ),
2940                                )
2941                                .child(
2942                                    Label::new("Running…")
2943                                        .size(LabelSize::XSmall)
2944                                        .color(Color::Muted)
2945                                        .buffer_font(cx),
2946                                ),
2947                        ),
2948                ),
2949                ToolUseStatus::Error(_) => container.child(
2950                    results_content_container()
2951                        .border_t_1()
2952                        .border_color(self.tool_card_border_color(cx))
2953                        .child(
2954                            Label::new("Error")
2955                                .size(LabelSize::XSmall)
2956                                .color(Color::Muted)
2957                                .buffer_font(cx),
2958                        )
2959                        .child(
2960                            div()
2961                                .text_ui_sm(cx)
2962                                .children(rendered_tool_use.as_ref().map(|rendered| {
2963                                    MarkdownElement::new(
2964                                        rendered.output.clone(),
2965                                        tool_use_markdown_style(window, cx),
2966                                    )
2967                                    .on_url_click({
2968                                        let workspace = self.workspace.clone();
2969                                        move |text, window, cx| {
2970                                            open_markdown_link(text, workspace.clone(), window, cx);
2971                                        }
2972                                    })
2973                                    .into_any_element()
2974                                })),
2975                        ),
2976                ),
2977                ToolUseStatus::Pending => container,
2978                ToolUseStatus::NeedsConfirmation => container.child(
2979                    results_content_container()
2980                        .border_t_1()
2981                        .border_color(self.tool_card_border_color(cx))
2982                        .child(
2983                            Label::new("Asking Permission")
2984                                .size(LabelSize::Small)
2985                                .color(Color::Muted)
2986                                .buffer_font(cx),
2987                        ),
2988                ),
2989            });
2990
2991        let gradient_overlay = |color: Hsla| {
2992            div()
2993                .h_full()
2994                .absolute()
2995                .w_12()
2996                .bottom_0()
2997                .map(|element| {
2998                    if is_status_finished {
2999                        element.right_6()
3000                    } else {
3001                        element.right(px(44.))
3002                    }
3003                })
3004                .bg(linear_gradient(
3005                    90.,
3006                    linear_color_stop(color, 1.),
3007                    linear_color_stop(color.opacity(0.2), 0.),
3008                ))
3009        };
3010
3011        v_flex().gap_1().mb_2().map(|element| {
3012            if !needs_confirmation_tools {
3013                element.child(
3014                    v_flex()
3015                        .child(
3016                            h_flex()
3017                                .group("disclosure-header")
3018                                .relative()
3019                                .gap_1p5()
3020                                .justify_between()
3021                                .opacity(0.8)
3022                                .hover(|style| style.opacity(1.))
3023                                .when(!is_status_finished, |this| this.pr_2())
3024                                .child(
3025                                    h_flex()
3026                                        .id("tool-label-container")
3027                                        .gap_1p5()
3028                                        .max_w_full()
3029                                        .overflow_x_scroll()
3030                                        .child(
3031                                            Icon::new(tool_use.icon)
3032                                                .size(IconSize::XSmall)
3033                                                .color(Color::Muted),
3034                                        )
3035                                        .child(
3036                                            h_flex().pr_8().text_size(rems(0.8125)).children(
3037                                                rendered_tool_use.map(|rendered| MarkdownElement::new(rendered.label, tool_use_markdown_style(window, cx)).on_url_click({let workspace = self.workspace.clone(); move |text, window, cx| {
3038                                                    open_markdown_link(text, workspace.clone(), window, cx);
3039                                                }}))
3040                                            ),
3041                                        ),
3042                                )
3043                                .child(
3044                                    h_flex()
3045                                        .gap_1()
3046                                        .child(
3047                                            div().visible_on_hover("disclosure-header").child(
3048                                                Disclosure::new("tool-use-disclosure", is_open)
3049                                                    .opened_icon(IconName::ChevronUp)
3050                                                    .closed_icon(IconName::ChevronDown)
3051                                                    .on_click(cx.listener({
3052                                                        let tool_use_id = tool_use.id.clone();
3053                                                        move |this, _event, _window, _cx| {
3054                                                            let is_open = this
3055                                                                .expanded_tool_uses
3056                                                                .entry(tool_use_id.clone())
3057                                                                .or_insert(false);
3058
3059                                                            *is_open = !*is_open;
3060                                                        }
3061                                                    })),
3062                                            ),
3063                                        )
3064                                        .child(status_icons),
3065                                )
3066                                .child(gradient_overlay(cx.theme().colors().panel_background)),
3067                        )
3068                        .map(|parent| {
3069                            if !is_open {
3070                                return parent;
3071                            }
3072
3073                            parent.child(
3074                                v_flex()
3075                                    .mt_1()
3076                                    .border_1()
3077                                    .border_color(self.tool_card_border_color(cx))
3078                                    .bg(cx.theme().colors().editor_background)
3079                                    .rounded_lg()
3080                                    .child(results_content),
3081                            )
3082                        }),
3083                )
3084            } else {
3085                v_flex()
3086                    .mb_2()
3087                    .rounded_lg()
3088                    .border_1()
3089                    .border_color(self.tool_card_border_color(cx))
3090                    .overflow_hidden()
3091                    .child(
3092                        h_flex()
3093                            .group("disclosure-header")
3094                            .relative()
3095                            .justify_between()
3096                            .py_1()
3097                            .map(|element| {
3098                                if is_status_finished {
3099                                    element.pl_2().pr_0p5()
3100                                } else {
3101                                    element.px_2()
3102                                }
3103                            })
3104                            .bg(self.tool_card_header_bg(cx))
3105                            .map(|element| {
3106                                if is_open {
3107                                    element.border_b_1().rounded_t_md()
3108                                } else if needs_confirmation {
3109                                    element.rounded_t_md()
3110                                } else {
3111                                    element.rounded_md()
3112                                }
3113                            })
3114                            .border_color(self.tool_card_border_color(cx))
3115                            .child(
3116                                h_flex()
3117                                    .id("tool-label-container")
3118                                    .gap_1p5()
3119                                    .max_w_full()
3120                                    .overflow_x_scroll()
3121                                    .child(
3122                                        Icon::new(tool_use.icon)
3123                                            .size(IconSize::XSmall)
3124                                            .color(Color::Muted),
3125                                    )
3126                                    .child(
3127                                        h_flex().pr_8().text_ui_sm(cx).children(
3128                                            rendered_tool_use.map(|rendered| MarkdownElement::new(rendered.label, tool_use_markdown_style(window, cx)).on_url_click({let workspace = self.workspace.clone(); move |text, window, cx| {
3129                                                open_markdown_link(text, workspace.clone(), window, cx);
3130                                            }}))
3131                                        ),
3132                                    ),
3133                            )
3134                            .child(
3135                                h_flex()
3136                                    .gap_1()
3137                                    .child(
3138                                        div().visible_on_hover("disclosure-header").child(
3139                                            Disclosure::new("tool-use-disclosure", is_open)
3140                                                .opened_icon(IconName::ChevronUp)
3141                                                .closed_icon(IconName::ChevronDown)
3142                                                .on_click(cx.listener({
3143                                                    let tool_use_id = tool_use.id.clone();
3144                                                    move |this, _event, _window, _cx| {
3145                                                        let is_open = this
3146                                                            .expanded_tool_uses
3147                                                            .entry(tool_use_id.clone())
3148                                                            .or_insert(false);
3149
3150                                                        *is_open = !*is_open;
3151                                                    }
3152                                                })),
3153                                        ),
3154                                    )
3155                                    .child(status_icons),
3156                            )
3157                            .child(gradient_overlay(self.tool_card_header_bg(cx))),
3158                    )
3159                    .map(|parent| {
3160                        if !is_open {
3161                            return parent;
3162                        }
3163
3164                        parent.child(
3165                            v_flex()
3166                                .bg(cx.theme().colors().editor_background)
3167                                .map(|element| {
3168                                    if  needs_confirmation {
3169                                        element.rounded_none()
3170                                    } else {
3171                                        element.rounded_b_lg()
3172                                    }
3173                                })
3174                                .child(results_content),
3175                        )
3176                    })
3177                    .when(needs_confirmation, |this| {
3178                        this.child(
3179                            h_flex()
3180                                .py_1()
3181                                .pl_2()
3182                                .pr_1()
3183                                .gap_1()
3184                                .justify_between()
3185                                .flex_wrap()
3186                                .bg(cx.theme().colors().editor_background)
3187                                .border_t_1()
3188                                .border_color(self.tool_card_border_color(cx))
3189                                .rounded_b_lg()
3190                                .child(
3191                                    LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)
3192                                )
3193                                .child(
3194                                    h_flex()
3195                                        .gap_0p5()
3196                                        .child({
3197                                            let tool_id = tool_use.id.clone();
3198                                            Button::new(
3199                                                "always-allow-tool-action",
3200                                                "Always Allow",
3201                                            )
3202                                            .label_size(LabelSize::Small)
3203                                            .icon(IconName::CheckDouble)
3204                                            .icon_position(IconPosition::Start)
3205                                            .icon_size(IconSize::Small)
3206                                            .icon_color(Color::Success)
3207                                            .tooltip(move |window, cx|  {
3208                                                Tooltip::with_meta(
3209                                                    "Never ask for permission",
3210                                                    None,
3211                                                    "Restore the original behavior in your Agent Panel settings",
3212                                                    window,
3213                                                    cx,
3214                                                )
3215                                            })
3216                                            .on_click(cx.listener(
3217                                                move |this, event, window, cx| {
3218                                                    if let Some(fs) = fs.clone() {
3219                                                        update_settings_file::<AgentSettings>(
3220                                                            fs.clone(),
3221                                                            cx,
3222                                                            |settings, _| {
3223                                                                settings.set_always_allow_tool_actions(true);
3224                                                            },
3225                                                        );
3226                                                    }
3227                                                    this.handle_allow_tool(
3228                                                        tool_id.clone(),
3229                                                        event,
3230                                                        window,
3231                                                        cx,
3232                                                    )
3233                                                },
3234                                            ))
3235                                        })
3236                                        .child(ui::Divider::vertical())
3237                                        .child({
3238                                            let tool_id = tool_use.id.clone();
3239                                            Button::new("allow-tool-action", "Allow")
3240                                                .label_size(LabelSize::Small)
3241                                                .icon(IconName::Check)
3242                                                .icon_position(IconPosition::Start)
3243                                                .icon_size(IconSize::Small)
3244                                                .icon_color(Color::Success)
3245                                                .on_click(cx.listener(
3246                                                    move |this, event, window, cx| {
3247                                                        this.handle_allow_tool(
3248                                                            tool_id.clone(),
3249                                                            event,
3250                                                            window,
3251                                                            cx,
3252                                                        )
3253                                                    },
3254                                                ))
3255                                        })
3256                                        .child({
3257                                            let tool_id = tool_use.id.clone();
3258                                            let tool_name: Arc<str> = tool_use.name.into();
3259                                            Button::new("deny-tool", "Deny")
3260                                                .label_size(LabelSize::Small)
3261                                                .icon(IconName::Close)
3262                                                .icon_position(IconPosition::Start)
3263                                                .icon_size(IconSize::Small)
3264                                                .icon_color(Color::Error)
3265                                                .on_click(cx.listener(
3266                                                    move |this, event, window, cx| {
3267                                                        this.handle_deny_tool(
3268                                                            tool_id.clone(),
3269                                                            tool_name.clone(),
3270                                                            event,
3271                                                            window,
3272                                                            cx,
3273                                                        )
3274                                                    },
3275                                                ))
3276                                        }),
3277                                ),
3278                        )
3279                    })
3280            }
3281        }).into_any_element()
3282    }
3283
3284    fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3285        let project_context = self.thread.read(cx).project_context();
3286        let project_context = project_context.borrow();
3287        let Some(project_context) = project_context.as_ref() else {
3288            return div().into_any();
3289        };
3290
3291        let user_rules_text = if project_context.user_rules.is_empty() {
3292            None
3293        } else if project_context.user_rules.len() == 1 {
3294            let user_rules = &project_context.user_rules[0];
3295
3296            match user_rules.title.as_ref() {
3297                Some(title) => Some(format!("Using \"{title}\" user rule")),
3298                None => Some("Using user rule".into()),
3299            }
3300        } else {
3301            Some(format!(
3302                "Using {} user rules",
3303                project_context.user_rules.len()
3304            ))
3305        };
3306
3307        let first_user_rules_id = project_context
3308            .user_rules
3309            .first()
3310            .map(|user_rules| user_rules.uuid.0);
3311
3312        let rules_files = project_context
3313            .worktrees
3314            .iter()
3315            .filter_map(|worktree| worktree.rules_file.as_ref())
3316            .collect::<Vec<_>>();
3317
3318        let rules_file_text = match rules_files.as_slice() {
3319            &[] => None,
3320            &[rules_file] => Some(format!(
3321                "Using project {:?} file",
3322                rules_file.path_in_worktree
3323            )),
3324            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3325        };
3326
3327        if user_rules_text.is_none() && rules_file_text.is_none() {
3328            return div().into_any();
3329        }
3330
3331        v_flex()
3332            .pt_2()
3333            .px_2p5()
3334            .gap_1()
3335            .when_some(user_rules_text, |parent, user_rules_text| {
3336                parent.child(
3337                    h_flex()
3338                        .w_full()
3339                        .child(
3340                            Icon::new(RULES_ICON)
3341                                .size(IconSize::XSmall)
3342                                .color(Color::Disabled),
3343                        )
3344                        .child(
3345                            Label::new(user_rules_text)
3346                                .size(LabelSize::XSmall)
3347                                .color(Color::Muted)
3348                                .truncate()
3349                                .buffer_font(cx)
3350                                .ml_1p5()
3351                                .mr_0p5(),
3352                        )
3353                        .child(
3354                            IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3355                                .shape(ui::IconButtonShape::Square)
3356                                .icon_size(IconSize::XSmall)
3357                                .icon_color(Color::Ignored)
3358                                // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary`  keybinding
3359                                .tooltip(Tooltip::text("View User Rules"))
3360                                .on_click(move |_event, window, cx| {
3361                                    window.dispatch_action(
3362                                        Box::new(OpenRulesLibrary {
3363                                            prompt_to_select: first_user_rules_id,
3364                                        }),
3365                                        cx,
3366                                    )
3367                                }),
3368                        ),
3369                )
3370            })
3371            .when_some(rules_file_text, |parent, rules_file_text| {
3372                parent.child(
3373                    h_flex()
3374                        .w_full()
3375                        .child(
3376                            Icon::new(IconName::File)
3377                                .size(IconSize::XSmall)
3378                                .color(Color::Disabled),
3379                        )
3380                        .child(
3381                            Label::new(rules_file_text)
3382                                .size(LabelSize::XSmall)
3383                                .color(Color::Muted)
3384                                .buffer_font(cx)
3385                                .ml_1p5()
3386                                .mr_0p5(),
3387                        )
3388                        .child(
3389                            IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3390                                .shape(ui::IconButtonShape::Square)
3391                                .icon_size(IconSize::XSmall)
3392                                .icon_color(Color::Ignored)
3393                                .on_click(cx.listener(Self::handle_open_rules))
3394                                .tooltip(Tooltip::text("View Rules")),
3395                        ),
3396                )
3397            })
3398            .into_any()
3399    }
3400
3401    fn handle_allow_tool(
3402        &mut self,
3403        tool_use_id: LanguageModelToolUseId,
3404        _: &ClickEvent,
3405        window: &mut Window,
3406        cx: &mut Context<Self>,
3407    ) {
3408        if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3409            .thread
3410            .read(cx)
3411            .pending_tool(&tool_use_id)
3412            .map(|tool_use| tool_use.status.clone())
3413        {
3414            self.thread.update(cx, |thread, cx| {
3415                if let Some(configured) = thread.get_or_init_configured_model(cx) {
3416                    thread.run_tool(
3417                        c.tool_use_id.clone(),
3418                        c.ui_text.clone(),
3419                        c.input.clone(),
3420                        c.request.clone(),
3421                        c.tool.clone(),
3422                        configured.model,
3423                        Some(window.window_handle()),
3424                        cx,
3425                    );
3426                }
3427            });
3428        }
3429    }
3430
3431    fn handle_deny_tool(
3432        &mut self,
3433        tool_use_id: LanguageModelToolUseId,
3434        tool_name: Arc<str>,
3435        _: &ClickEvent,
3436        window: &mut Window,
3437        cx: &mut Context<Self>,
3438    ) {
3439        let window_handle = window.window_handle();
3440        self.thread.update(cx, |thread, cx| {
3441            thread.deny_tool_use(tool_use_id, tool_name, Some(window_handle), cx);
3442        });
3443    }
3444
3445    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3446        let project_context = self.thread.read(cx).project_context();
3447        let project_context = project_context.borrow();
3448        let Some(project_context) = project_context.as_ref() else {
3449            return;
3450        };
3451
3452        let project_entry_ids = project_context
3453            .worktrees
3454            .iter()
3455            .flat_map(|worktree| worktree.rules_file.as_ref())
3456            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
3457            .collect::<Vec<_>>();
3458
3459        self.workspace
3460            .update(cx, move |workspace, cx| {
3461                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3462                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3463                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3464                let project = workspace.project().read(cx);
3465                let project_paths = project_entry_ids
3466                    .into_iter()
3467                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
3468                    .collect::<Vec<_>>();
3469                for project_path in project_paths {
3470                    workspace
3471                        .open_path(project_path, None, true, window, cx)
3472                        .detach_and_log_err(cx);
3473                }
3474            })
3475            .ok();
3476    }
3477
3478    fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3479        for window in self.notifications.drain(..) {
3480            window
3481                .update(cx, |_, window, _| {
3482                    window.remove_window();
3483                })
3484                .ok();
3485
3486            self.notification_subscriptions.remove(&window);
3487        }
3488    }
3489
3490    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3491        if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3492            return None;
3493        }
3494
3495        Some(
3496            div()
3497                .occlude()
3498                .id("active-thread-scrollbar")
3499                .on_mouse_move(cx.listener(|_, _, _, cx| {
3500                    cx.notify();
3501                    cx.stop_propagation()
3502                }))
3503                .on_hover(|_, _, cx| {
3504                    cx.stop_propagation();
3505                })
3506                .on_any_mouse_down(|_, _, cx| {
3507                    cx.stop_propagation();
3508                })
3509                .on_mouse_up(
3510                    MouseButton::Left,
3511                    cx.listener(|_, _, _, cx| {
3512                        cx.stop_propagation();
3513                    }),
3514                )
3515                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3516                    cx.notify();
3517                }))
3518                .h_full()
3519                .absolute()
3520                .right_1()
3521                .top_1()
3522                .bottom_0()
3523                .w(px(12.))
3524                .cursor_default()
3525                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3526        )
3527    }
3528
3529    fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3530        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3531        self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3532            cx.background_executor()
3533                .timer(SCROLLBAR_SHOW_INTERVAL)
3534                .await;
3535            thread
3536                .update(cx, |thread, cx| {
3537                    if !thread.scrollbar_state.is_dragging() {
3538                        thread.show_scrollbar = false;
3539                        cx.notify();
3540                    }
3541                })
3542                .log_err();
3543        }))
3544    }
3545
3546    pub fn is_codeblock_expanded(&self, message_id: MessageId, ix: usize) -> bool {
3547        self.expanded_code_blocks
3548            .get(&(message_id, ix))
3549            .copied()
3550            .unwrap_or(true)
3551    }
3552
3553    pub fn toggle_codeblock_expanded(&mut self, message_id: MessageId, ix: usize) {
3554        let is_expanded = self
3555            .expanded_code_blocks
3556            .entry((message_id, ix))
3557            .or_insert(true);
3558        *is_expanded = !*is_expanded;
3559    }
3560
3561    pub fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3562        self.list_state.scroll_to(ListOffset::default());
3563        cx.notify();
3564    }
3565
3566    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3567        self.list_state.reset(self.messages.len());
3568        cx.notify();
3569    }
3570}
3571
3572pub enum ActiveThreadEvent {
3573    EditingMessageTokenCountChanged,
3574}
3575
3576impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3577
3578impl Render for ActiveThread {
3579    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3580        v_flex()
3581            .size_full()
3582            .relative()
3583            .bg(cx.theme().colors().panel_background)
3584            .on_mouse_move(cx.listener(|this, _, _, cx| {
3585                this.show_scrollbar = true;
3586                this.hide_scrollbar_later(cx);
3587                cx.notify();
3588            }))
3589            .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3590                this.show_scrollbar = true;
3591                this.hide_scrollbar_later(cx);
3592                cx.notify();
3593            }))
3594            .on_mouse_up(
3595                MouseButton::Left,
3596                cx.listener(|this, _, _, cx| {
3597                    this.hide_scrollbar_later(cx);
3598                }),
3599            )
3600            .child(list(self.list_state.clone()).flex_grow())
3601            .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3602                this.child(scrollbar)
3603            })
3604    }
3605}
3606
3607pub(crate) fn open_active_thread_as_markdown(
3608    thread: Entity<Thread>,
3609    workspace: Entity<Workspace>,
3610    window: &mut Window,
3611    cx: &mut App,
3612) -> Task<anyhow::Result<()>> {
3613    let markdown_language_task = workspace
3614        .read(cx)
3615        .app_state()
3616        .languages
3617        .language_for_name("Markdown");
3618
3619    window.spawn(cx, async move |cx| {
3620        let markdown_language = markdown_language_task.await?;
3621
3622        workspace.update_in(cx, |workspace, window, cx| {
3623            let thread = thread.read(cx);
3624            let markdown = thread.to_markdown(cx)?;
3625            let thread_summary = thread.summary().or_default().to_string();
3626
3627            let project = workspace.project().clone();
3628
3629            if !project.read(cx).is_local() {
3630                anyhow::bail!("failed to open active thread as markdown in remote project");
3631            }
3632
3633            let buffer = project.update(cx, |project, cx| {
3634                project.create_local_buffer(&markdown, Some(markdown_language), cx)
3635            });
3636            let buffer =
3637                cx.new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone()));
3638
3639            workspace.add_item_to_active_pane(
3640                Box::new(cx.new(|cx| {
3641                    let mut editor =
3642                        Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3643                    editor.set_breadcrumb_header(thread_summary);
3644                    editor
3645                })),
3646                None,
3647                true,
3648                window,
3649                cx,
3650            );
3651
3652            anyhow::Ok(())
3653        })??;
3654        anyhow::Ok(())
3655    })
3656}
3657
3658pub(crate) fn open_context(
3659    context: &AgentContextHandle,
3660    workspace: Entity<Workspace>,
3661    window: &mut Window,
3662    cx: &mut App,
3663) {
3664    match context {
3665        AgentContextHandle::File(file_context) => {
3666            if let Some(project_path) = file_context.project_path(cx) {
3667                workspace.update(cx, |workspace, cx| {
3668                    workspace
3669                        .open_path(project_path, None, true, window, cx)
3670                        .detach_and_log_err(cx);
3671                });
3672            }
3673        }
3674
3675        AgentContextHandle::Directory(directory_context) => {
3676            let entry_id = directory_context.entry_id;
3677            workspace.update(cx, |workspace, cx| {
3678                workspace.project().update(cx, |_project, cx| {
3679                    cx.emit(project::Event::RevealInProjectPanel(entry_id));
3680                })
3681            })
3682        }
3683
3684        AgentContextHandle::Symbol(symbol_context) => {
3685            let buffer = symbol_context.buffer.read(cx);
3686            if let Some(project_path) = buffer.project_path(cx) {
3687                let snapshot = buffer.snapshot();
3688                let target_position = symbol_context.range.start.to_point(&snapshot);
3689                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3690                    .detach();
3691            }
3692        }
3693
3694        AgentContextHandle::Selection(selection_context) => {
3695            let buffer = selection_context.buffer.read(cx);
3696            if let Some(project_path) = buffer.project_path(cx) {
3697                let snapshot = buffer.snapshot();
3698                let target_position = selection_context.range.start.to_point(&snapshot);
3699
3700                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3701                    .detach();
3702            }
3703        }
3704
3705        AgentContextHandle::FetchedUrl(fetched_url_context) => {
3706            cx.open_url(&fetched_url_context.url);
3707        }
3708
3709        AgentContextHandle::Thread(thread_context) => workspace.update(cx, |workspace, cx| {
3710            if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3711                panel.update(cx, |panel, cx| {
3712                    panel.open_thread(thread_context.thread.clone(), window, cx);
3713                });
3714            }
3715        }),
3716
3717        AgentContextHandle::TextThread(text_thread_context) => {
3718            workspace.update(cx, |workspace, cx| {
3719                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3720                    panel.update(cx, |panel, cx| {
3721                        panel.open_prompt_editor(text_thread_context.context.clone(), window, cx)
3722                    });
3723                }
3724            })
3725        }
3726
3727        AgentContextHandle::Rules(rules_context) => window.dispatch_action(
3728            Box::new(OpenRulesLibrary {
3729                prompt_to_select: Some(rules_context.prompt_id.0),
3730            }),
3731            cx,
3732        ),
3733
3734        AgentContextHandle::Image(_) => {}
3735    }
3736}
3737
3738pub(crate) fn attach_pasted_images_as_context(
3739    context_store: &Entity<ContextStore>,
3740    cx: &mut App,
3741) -> bool {
3742    let images = cx
3743        .read_from_clipboard()
3744        .map(|item| {
3745            item.into_entries()
3746                .filter_map(|entry| {
3747                    if let ClipboardEntry::Image(image) = entry {
3748                        Some(image)
3749                    } else {
3750                        None
3751                    }
3752                })
3753                .collect::<Vec<_>>()
3754        })
3755        .unwrap_or_default();
3756
3757    if images.is_empty() {
3758        return false;
3759    }
3760    cx.stop_propagation();
3761
3762    context_store.update(cx, |store, cx| {
3763        for image in images {
3764            store.add_image_instance(Arc::new(image), cx);
3765        }
3766    });
3767    true
3768}
3769
3770fn open_editor_at_position(
3771    project_path: project::ProjectPath,
3772    target_position: Point,
3773    workspace: &Entity<Workspace>,
3774    window: &mut Window,
3775    cx: &mut App,
3776) -> Task<()> {
3777    let open_task = workspace.update(cx, |workspace, cx| {
3778        workspace.open_path(project_path, None, true, window, cx)
3779    });
3780    window.spawn(cx, async move |cx| {
3781        if let Some(active_editor) = open_task
3782            .await
3783            .log_err()
3784            .and_then(|item| item.downcast::<Editor>())
3785        {
3786            active_editor
3787                .downgrade()
3788                .update_in(cx, |editor, window, cx| {
3789                    editor.go_to_singleton_buffer_point(target_position, window, cx);
3790                })
3791                .log_err();
3792        }
3793    })
3794}
3795
3796#[cfg(test)]
3797mod tests {
3798    use super::*;
3799    use agent::{MessageSegment, context::ContextLoadResult, thread_store};
3800    use assistant_tool::{ToolRegistry, ToolWorkingSet};
3801    use editor::EditorSettings;
3802    use fs::FakeFs;
3803    use gpui::{AppContext, TestAppContext, VisualTestContext};
3804    use language_model::{
3805        ConfiguredModel, LanguageModel, LanguageModelRegistry,
3806        fake_provider::{FakeLanguageModel, FakeLanguageModelProvider},
3807    };
3808    use project::Project;
3809    use prompt_store::PromptBuilder;
3810    use serde_json::json;
3811    use settings::SettingsStore;
3812    use util::path;
3813    use workspace::CollaboratorId;
3814
3815    #[gpui::test]
3816    async fn test_agent_is_unfollowed_after_cancelling_completion(cx: &mut TestAppContext) {
3817        init_test_settings(cx);
3818
3819        let project = create_test_project(
3820            cx,
3821            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3822        )
3823        .await;
3824
3825        let (cx, _active_thread, workspace, thread, model) =
3826            setup_test_environment(cx, project.clone()).await;
3827
3828        // Insert user message without any context (empty context vector)
3829        thread.update(cx, |thread, cx| {
3830            thread.insert_user_message(
3831                "What is the best way to learn Rust?",
3832                ContextLoadResult::default(),
3833                None,
3834                vec![],
3835                cx,
3836            );
3837        });
3838
3839        // Stream response to user message
3840        thread.update(cx, |thread, cx| {
3841            let intent = CompletionIntent::UserPrompt;
3842            let request = thread.to_completion_request(model.clone(), intent, cx);
3843            thread.stream_completion(request, model, intent, cx.active_window(), cx)
3844        });
3845        // Follow the agent
3846        cx.update(|window, cx| {
3847            workspace.update(cx, |workspace, cx| {
3848                workspace.follow(CollaboratorId::Agent, window, cx);
3849            })
3850        });
3851        assert!(cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3852
3853        // Cancel the current completion
3854        thread.update(cx, |thread, cx| {
3855            thread.cancel_last_completion(cx.active_window(), cx)
3856        });
3857
3858        cx.executor().run_until_parked();
3859
3860        // No longer following the agent
3861        assert!(!cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3862    }
3863
3864    #[gpui::test]
3865    async fn test_reinserting_creases_for_edited_message(cx: &mut TestAppContext) {
3866        init_test_settings(cx);
3867
3868        let project = create_test_project(cx, json!({})).await;
3869
3870        let (cx, active_thread, _, thread, model) =
3871            setup_test_environment(cx, project.clone()).await;
3872        cx.update(|_, cx| {
3873            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3874                registry.set_default_model(
3875                    Some(ConfiguredModel {
3876                        provider: Arc::new(FakeLanguageModelProvider),
3877                        model,
3878                    }),
3879                    cx,
3880                );
3881            });
3882        });
3883
3884        let creases = vec![MessageCrease {
3885            range: 14..22,
3886            icon_path: "icon".into(),
3887            label: "foo.txt".into(),
3888            context: None,
3889        }];
3890
3891        let message = thread.update(cx, |thread, cx| {
3892            let message_id = thread.insert_user_message(
3893                "Tell me about @foo.txt",
3894                ContextLoadResult::default(),
3895                None,
3896                creases,
3897                cx,
3898            );
3899            thread.message(message_id).cloned().unwrap()
3900        });
3901
3902        active_thread.update_in(cx, |active_thread, window, cx| {
3903            if let Some(message_text) = message.segments.first().and_then(MessageSegment::text) {
3904                active_thread.start_editing_message(
3905                    message.id,
3906                    message_text,
3907                    message.creases.as_slice(),
3908                    window,
3909                    cx,
3910                );
3911            }
3912            let editor = active_thread
3913                .editing_message
3914                .as_ref()
3915                .unwrap()
3916                .1
3917                .editor
3918                .clone();
3919            editor.update(cx, |editor, cx| editor.edit([(0..13, "modified")], cx));
3920            active_thread.confirm_editing_message(&Default::default(), window, cx);
3921        });
3922        cx.run_until_parked();
3923
3924        let message = thread.update(cx, |thread, _| thread.message(message.id).cloned().unwrap());
3925        active_thread.update_in(cx, |active_thread, window, cx| {
3926            if let Some(message_text) = message.segments.first().and_then(MessageSegment::text) {
3927                active_thread.start_editing_message(
3928                    message.id,
3929                    message_text,
3930                    message.creases.as_slice(),
3931                    window,
3932                    cx,
3933                );
3934            }
3935            let editor = active_thread
3936                .editing_message
3937                .as_ref()
3938                .unwrap()
3939                .1
3940                .editor
3941                .clone();
3942            let text = editor.update(cx, |editor, cx| editor.text(cx));
3943            assert_eq!(text, "modified @foo.txt");
3944        });
3945    }
3946
3947    #[gpui::test]
3948    async fn test_editing_message_cancels_previous_completion(cx: &mut TestAppContext) {
3949        init_test_settings(cx);
3950
3951        let project = create_test_project(cx, json!({})).await;
3952
3953        let (cx, active_thread, _, thread, model) =
3954            setup_test_environment(cx, project.clone()).await;
3955
3956        cx.update(|_, cx| {
3957            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3958                registry.set_default_model(
3959                    Some(ConfiguredModel {
3960                        provider: Arc::new(FakeLanguageModelProvider),
3961                        model: model.clone(),
3962                    }),
3963                    cx,
3964                );
3965            });
3966        });
3967
3968        // Track thread events to verify cancellation
3969        let cancellation_events = Arc::new(std::sync::Mutex::new(Vec::new()));
3970        let new_request_events = Arc::new(std::sync::Mutex::new(Vec::new()));
3971
3972        let _subscription = cx.update(|_, cx| {
3973            let cancellation_events = cancellation_events.clone();
3974            let new_request_events = new_request_events.clone();
3975            cx.subscribe(
3976                &thread,
3977                move |_thread, event: &ThreadEvent, _cx| match event {
3978                    ThreadEvent::CompletionCanceled => {
3979                        cancellation_events.lock().unwrap().push(());
3980                    }
3981                    ThreadEvent::NewRequest => {
3982                        new_request_events.lock().unwrap().push(());
3983                    }
3984                    _ => {}
3985                },
3986            )
3987        });
3988
3989        // Insert a user message and start streaming a response
3990        let message = thread.update(cx, |thread, cx| {
3991            let message_id = thread.insert_user_message(
3992                "Hello, how are you?",
3993                ContextLoadResult::default(),
3994                None,
3995                vec![],
3996                cx,
3997            );
3998            thread.advance_prompt_id();
3999            thread.send_to_model(
4000                model.clone(),
4001                CompletionIntent::UserPrompt,
4002                cx.active_window(),
4003                cx,
4004            );
4005            thread.message(message_id).cloned().unwrap()
4006        });
4007
4008        cx.run_until_parked();
4009
4010        // Verify that a completion is in progress
4011        assert!(cx.read(|cx| thread.read(cx).is_generating()));
4012        assert_eq!(new_request_events.lock().unwrap().len(), 1);
4013
4014        // Edit the message while the completion is still running
4015        active_thread.update_in(cx, |active_thread, window, cx| {
4016            if let Some(message_text) = message.segments.first().and_then(MessageSegment::text) {
4017                active_thread.start_editing_message(
4018                    message.id,
4019                    message_text,
4020                    message.creases.as_slice(),
4021                    window,
4022                    cx,
4023                );
4024            }
4025            let editor = active_thread
4026                .editing_message
4027                .as_ref()
4028                .unwrap()
4029                .1
4030                .editor
4031                .clone();
4032            editor.update(cx, |editor, cx| {
4033                editor.set_text("What is the weather like?", window, cx);
4034            });
4035            active_thread.confirm_editing_message(&Default::default(), window, cx);
4036        });
4037
4038        cx.run_until_parked();
4039
4040        // Verify that the previous completion was cancelled
4041        assert_eq!(cancellation_events.lock().unwrap().len(), 1);
4042
4043        // Verify that a new request was started after cancellation
4044        assert_eq!(new_request_events.lock().unwrap().len(), 2);
4045
4046        // Verify that the edited message contains the new text
4047        let edited_message =
4048            thread.update(cx, |thread, _| thread.message(message.id).cloned().unwrap());
4049        match &edited_message.segments[0] {
4050            MessageSegment::Text(text) => {
4051                assert_eq!(text, "What is the weather like?");
4052            }
4053            _ => panic!("Expected text segment"),
4054        }
4055    }
4056
4057    fn init_test_settings(cx: &mut TestAppContext) {
4058        cx.update(|cx| {
4059            let settings_store = SettingsStore::test(cx);
4060            cx.set_global(settings_store);
4061            language::init(cx);
4062            Project::init_settings(cx);
4063            AgentSettings::register(cx);
4064            prompt_store::init(cx);
4065            thread_store::init(cx);
4066            workspace::init_settings(cx);
4067            language_model::init_settings(cx);
4068            ThemeSettings::register(cx);
4069            EditorSettings::register(cx);
4070            ToolRegistry::default_global(cx);
4071        });
4072    }
4073
4074    // Helper to create a test project with test files
4075    async fn create_test_project(
4076        cx: &mut TestAppContext,
4077        files: serde_json::Value,
4078    ) -> Entity<Project> {
4079        let fs = FakeFs::new(cx.executor());
4080        fs.insert_tree(path!("/test"), files).await;
4081        Project::test(fs, [path!("/test").as_ref()], cx).await
4082    }
4083
4084    async fn setup_test_environment(
4085        cx: &mut TestAppContext,
4086        project: Entity<Project>,
4087    ) -> (
4088        &mut VisualTestContext,
4089        Entity<ActiveThread>,
4090        Entity<Workspace>,
4091        Entity<Thread>,
4092        Arc<dyn LanguageModel>,
4093    ) {
4094        let (workspace, cx) =
4095            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4096
4097        let thread_store = cx
4098            .update(|_, cx| {
4099                ThreadStore::load(
4100                    project.clone(),
4101                    cx.new(|_| ToolWorkingSet::default()),
4102                    None,
4103                    Arc::new(PromptBuilder::new(None).unwrap()),
4104                    cx,
4105                )
4106            })
4107            .await
4108            .unwrap();
4109
4110        let text_thread_store = cx
4111            .update(|_, cx| {
4112                TextThreadStore::new(
4113                    project.clone(),
4114                    Arc::new(PromptBuilder::new(None).unwrap()),
4115                    Default::default(),
4116                    cx,
4117                )
4118            })
4119            .await
4120            .unwrap();
4121
4122        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
4123        let context_store =
4124            cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
4125
4126        let model = FakeLanguageModel::default();
4127        let model: Arc<dyn LanguageModel> = Arc::new(model);
4128
4129        let language_registry = LanguageRegistry::new(cx.executor());
4130        let language_registry = Arc::new(language_registry);
4131
4132        let active_thread = cx.update(|window, cx| {
4133            cx.new(|cx| {
4134                ActiveThread::new(
4135                    thread.clone(),
4136                    thread_store.clone(),
4137                    text_thread_store,
4138                    context_store.clone(),
4139                    language_registry.clone(),
4140                    workspace.downgrade(),
4141                    window,
4142                    cx,
4143                )
4144            })
4145        });
4146
4147        (cx, active_thread, workspace, thread, model)
4148    }
4149}