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) => match reason {
 987                Ok(StopReason::EndTurn | StopReason::MaxTokens) => {
 988                    let used_tools = self.thread.read(cx).used_tools_since_last_user_message();
 989                    self.play_notification_sound(window, cx);
 990                    self.show_notification(
 991                        if used_tools {
 992                            "Finished running tools"
 993                        } else {
 994                            "New message"
 995                        },
 996                        IconName::ZedAssistant,
 997                        window,
 998                        cx,
 999                    );
1000                }
1001                _ => {}
1002            },
1003            ThreadEvent::ToolConfirmationNeeded => {
1004                self.play_notification_sound(window, cx);
1005                self.show_notification("Waiting for tool confirmation", IconName::Info, window, cx);
1006            }
1007            ThreadEvent::ToolUseLimitReached => {
1008                self.play_notification_sound(window, cx);
1009                self.show_notification(
1010                    "Consecutive tool use limit reached.",
1011                    IconName::Warning,
1012                    window,
1013                    cx,
1014                );
1015            }
1016            ThreadEvent::StreamedAssistantText(message_id, text) => {
1017                if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
1018                    rendered_message.append_text(text, cx);
1019                }
1020            }
1021            ThreadEvent::StreamedAssistantThinking(message_id, text) => {
1022                if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
1023                    rendered_message.append_thinking(text, cx);
1024                }
1025            }
1026            ThreadEvent::MessageAdded(message_id) => {
1027                self.clear_last_error();
1028                if let Some(rendered_message) = self.thread.update(cx, |thread, cx| {
1029                    thread.message(*message_id).map(|message| {
1030                        RenderedMessage::from_segments(
1031                            &message.segments,
1032                            self.language_registry.clone(),
1033                            cx,
1034                        )
1035                    })
1036                }) {
1037                    self.push_rendered_message(*message_id, rendered_message);
1038                }
1039
1040                self.save_thread(cx);
1041                cx.notify();
1042            }
1043            ThreadEvent::MessageEdited(message_id) => {
1044                self.clear_last_error();
1045                if let Some(index) = self.messages.iter().position(|id| id == message_id) {
1046                    if let Some(rendered_message) = self.thread.update(cx, |thread, cx| {
1047                        thread.message(*message_id).map(|message| {
1048                            let mut rendered_message = RenderedMessage {
1049                                language_registry: self.language_registry.clone(),
1050                                segments: Vec::with_capacity(message.segments.len()),
1051                            };
1052                            for segment in &message.segments {
1053                                rendered_message.push_segment(segment, cx);
1054                            }
1055                            rendered_message
1056                        })
1057                    }) {
1058                        self.list_state.splice(index..index + 1, 1);
1059                        self.rendered_messages_by_id
1060                            .insert(*message_id, rendered_message);
1061                        self.scroll_to_bottom(cx);
1062                        self.save_thread(cx);
1063                        cx.notify();
1064                    }
1065                }
1066            }
1067            ThreadEvent::MessageDeleted(message_id) => {
1068                self.deleted_message(message_id);
1069                self.save_thread(cx);
1070                cx.notify();
1071            }
1072            ThreadEvent::UsePendingTools { tool_uses } => {
1073                for tool_use in tool_uses {
1074                    self.render_tool_use_markdown(
1075                        tool_use.id.clone(),
1076                        tool_use.ui_text.clone(),
1077                        &serde_json::to_string_pretty(&tool_use.input).unwrap_or_default(),
1078                        "".into(),
1079                        cx,
1080                    );
1081                }
1082            }
1083            ThreadEvent::StreamedToolUse {
1084                tool_use_id,
1085                ui_text,
1086                input,
1087            } => {
1088                self.render_tool_use_markdown(
1089                    tool_use_id.clone(),
1090                    ui_text.clone(),
1091                    &serde_json::to_string_pretty(&input).unwrap_or_default(),
1092                    "".into(),
1093                    cx,
1094                );
1095            }
1096            ThreadEvent::ToolFinished {
1097                pending_tool_use, ..
1098            } => {
1099                if let Some(tool_use) = pending_tool_use {
1100                    self.render_tool_use_markdown(
1101                        tool_use.id.clone(),
1102                        tool_use.ui_text.clone(),
1103                        &serde_json::to_string_pretty(&tool_use.input).unwrap_or_default(),
1104                        self.thread
1105                            .read(cx)
1106                            .output_for_tool(&tool_use.id)
1107                            .map(|output| output.clone().into())
1108                            .unwrap_or("".into()),
1109                        cx,
1110                    );
1111                }
1112            }
1113            ThreadEvent::CheckpointChanged => cx.notify(),
1114            ThreadEvent::ReceivedTextChunk => {}
1115            ThreadEvent::InvalidToolInput {
1116                tool_use_id,
1117                ui_text,
1118                invalid_input_json,
1119            } => {
1120                self.render_tool_use_markdown(
1121                    tool_use_id.clone(),
1122                    ui_text,
1123                    invalid_input_json,
1124                    self.thread
1125                        .read(cx)
1126                        .output_for_tool(tool_use_id)
1127                        .map(|output| output.clone().into())
1128                        .unwrap_or("".into()),
1129                    cx,
1130                );
1131            }
1132            ThreadEvent::MissingToolUse {
1133                tool_use_id,
1134                ui_text,
1135            } => {
1136                self.render_tool_use_markdown(
1137                    tool_use_id.clone(),
1138                    ui_text,
1139                    "",
1140                    self.thread
1141                        .read(cx)
1142                        .output_for_tool(tool_use_id)
1143                        .map(|output| output.clone().into())
1144                        .unwrap_or("".into()),
1145                    cx,
1146                );
1147            }
1148            ThreadEvent::ProfileChanged => {
1149                self.save_thread(cx);
1150                cx.notify();
1151            }
1152            ThreadEvent::RetriesFailed { message } => {
1153                self.show_notification(message, ui::IconName::Warning, window, cx);
1154            }
1155        }
1156    }
1157
1158    fn handle_rules_loading_error(
1159        &mut self,
1160        _thread_store: Entity<ThreadStore>,
1161        error: &RulesLoadingError,
1162        cx: &mut Context<Self>,
1163    ) {
1164        self.last_error = Some(ThreadError::Message {
1165            header: "Error loading rules file".into(),
1166            message: error.message.clone(),
1167        });
1168        cx.notify();
1169    }
1170
1171    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
1172        let settings = AgentSettings::get_global(cx);
1173        if settings.play_sound_when_agent_done && !window.is_window_active() {
1174            Audio::play_sound(Sound::AgentDone, cx);
1175        }
1176    }
1177
1178    fn show_notification(
1179        &mut self,
1180        caption: impl Into<SharedString>,
1181        icon: IconName,
1182        window: &mut Window,
1183        cx: &mut Context<ActiveThread>,
1184    ) {
1185        if window.is_window_active() || !self.notifications.is_empty() {
1186            return;
1187        }
1188
1189        let title = self.thread.read(cx).summary().unwrap_or("Agent Panel");
1190
1191        match AgentSettings::get_global(cx).notify_when_agent_waiting {
1192            NotifyWhenAgentWaiting::PrimaryScreen => {
1193                if let Some(primary) = cx.primary_display() {
1194                    self.pop_up(icon, caption.into(), title.clone(), window, primary, cx);
1195                }
1196            }
1197            NotifyWhenAgentWaiting::AllScreens => {
1198                let caption = caption.into();
1199                for screen in cx.displays() {
1200                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
1201                }
1202            }
1203            NotifyWhenAgentWaiting::Never => {
1204                // Don't show anything
1205            }
1206        }
1207    }
1208
1209    fn pop_up(
1210        &mut self,
1211        icon: IconName,
1212        caption: SharedString,
1213        title: SharedString,
1214        window: &mut Window,
1215        screen: Rc<dyn PlatformDisplay>,
1216        cx: &mut Context<'_, ActiveThread>,
1217    ) {
1218        let options = AgentNotification::window_options(screen, cx);
1219
1220        let project_name = self.workspace.upgrade().and_then(|workspace| {
1221            workspace
1222                .read(cx)
1223                .project()
1224                .read(cx)
1225                .visible_worktrees(cx)
1226                .next()
1227                .map(|worktree| worktree.read(cx).root_name().to_string())
1228        });
1229
1230        if let Some(screen_window) = cx
1231            .open_window(options, |_, cx| {
1232                cx.new(|_| {
1233                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
1234                })
1235            })
1236            .log_err()
1237        {
1238            if let Some(pop_up) = screen_window.entity(cx).log_err() {
1239                self.notification_subscriptions
1240                    .entry(screen_window)
1241                    .or_insert_with(Vec::new)
1242                    .push(cx.subscribe_in(&pop_up, window, {
1243                        |this, _, event, window, cx| match event {
1244                            AgentNotificationEvent::Accepted => {
1245                                let handle = window.window_handle();
1246                                cx.activate(true);
1247
1248                                let workspace_handle = this.workspace.clone();
1249
1250                                // If there are multiple Zed windows, activate the correct one.
1251                                cx.defer(move |cx| {
1252                                    handle
1253                                        .update(cx, |_view, window, _cx| {
1254                                            window.activate_window();
1255
1256                                            if let Some(workspace) = workspace_handle.upgrade() {
1257                                                workspace.update(_cx, |workspace, cx| {
1258                                                    workspace.focus_panel::<AgentPanel>(window, cx);
1259                                                });
1260                                            }
1261                                        })
1262                                        .log_err();
1263                                });
1264
1265                                this.dismiss_notifications(cx);
1266                            }
1267                            AgentNotificationEvent::Dismissed => {
1268                                this.dismiss_notifications(cx);
1269                            }
1270                        }
1271                    }));
1272
1273                self.notifications.push(screen_window);
1274
1275                // If the user manually refocuses the original window, dismiss the popup.
1276                self.notification_subscriptions
1277                    .entry(screen_window)
1278                    .or_insert_with(Vec::new)
1279                    .push({
1280                        let pop_up_weak = pop_up.downgrade();
1281
1282                        cx.observe_window_activation(window, move |_, window, cx| {
1283                            if window.is_window_active() {
1284                                if let Some(pop_up) = pop_up_weak.upgrade() {
1285                                    pop_up.update(cx, |_, cx| {
1286                                        cx.emit(AgentNotificationEvent::Dismissed);
1287                                    });
1288                                }
1289                            }
1290                        })
1291                    });
1292            }
1293        }
1294    }
1295
1296    /// Spawns a task to save the active thread.
1297    ///
1298    /// Only one task to save the thread will be in flight at a time.
1299    fn save_thread(&mut self, cx: &mut Context<Self>) {
1300        let thread = self.thread.clone();
1301        self.save_thread_task = Some(cx.spawn(async move |this, cx| {
1302            let task = this
1303                .update(cx, |this, cx| {
1304                    this.thread_store
1305                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
1306                })
1307                .ok();
1308
1309            if let Some(task) = task {
1310                task.await.log_err();
1311            }
1312        }));
1313    }
1314
1315    fn start_editing_message(
1316        &mut self,
1317        message_id: MessageId,
1318        message_text: impl Into<Arc<str>>,
1319        message_creases: &[MessageCrease],
1320        window: &mut Window,
1321        cx: &mut Context<Self>,
1322    ) {
1323        let editor = crate::message_editor::create_editor(
1324            self.workspace.clone(),
1325            self.context_store.downgrade(),
1326            self.thread_store.downgrade(),
1327            self.text_thread_store.downgrade(),
1328            EDIT_PREVIOUS_MESSAGE_MIN_LINES,
1329            None,
1330            window,
1331            cx,
1332        );
1333        editor.update(cx, |editor, cx| {
1334            editor.set_text(message_text, window, cx);
1335            insert_message_creases(editor, message_creases, &self.context_store, window, cx);
1336            editor.focus_handle(cx).focus(window);
1337            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
1338        });
1339        let buffer_edited_subscription = cx.subscribe(&editor, |this, _, event, cx| match event {
1340            EditorEvent::BufferEdited => {
1341                this.update_editing_message_token_count(true, cx);
1342            }
1343            _ => {}
1344        });
1345
1346        let context_picker_menu_handle = PopoverMenuHandle::default();
1347        let context_strip = cx.new(|cx| {
1348            ContextStrip::new(
1349                self.context_store.clone(),
1350                self.workspace.clone(),
1351                Some(self.thread_store.downgrade()),
1352                Some(self.text_thread_store.downgrade()),
1353                context_picker_menu_handle.clone(),
1354                SuggestContextKind::File,
1355                ModelUsageContext::Thread(self.thread.clone()),
1356                window,
1357                cx,
1358            )
1359        });
1360
1361        let context_strip_subscription =
1362            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event);
1363
1364        self.editing_message = Some((
1365            message_id,
1366            EditingMessageState {
1367                editor: editor.clone(),
1368                context_strip,
1369                context_picker_menu_handle,
1370                last_estimated_token_count: None,
1371                _subscriptions: [buffer_edited_subscription, context_strip_subscription],
1372                _update_token_count_task: None,
1373            },
1374        ));
1375        self.update_editing_message_token_count(false, cx);
1376        cx.notify();
1377    }
1378
1379    fn handle_context_strip_event(
1380        &mut self,
1381        _context_strip: &Entity<ContextStrip>,
1382        event: &ContextStripEvent,
1383        window: &mut Window,
1384        cx: &mut Context<Self>,
1385    ) {
1386        if let Some((_, state)) = self.editing_message.as_ref() {
1387            match event {
1388                ContextStripEvent::PickerDismissed
1389                | ContextStripEvent::BlurredEmpty
1390                | ContextStripEvent::BlurredDown => {
1391                    let editor_focus_handle = state.editor.focus_handle(cx);
1392                    window.focus(&editor_focus_handle);
1393                }
1394                ContextStripEvent::BlurredUp => {}
1395            }
1396        }
1397    }
1398
1399    fn update_editing_message_token_count(&mut self, debounce: bool, cx: &mut Context<Self>) {
1400        let Some((message_id, state)) = self.editing_message.as_mut() else {
1401            return;
1402        };
1403
1404        cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1405        state._update_token_count_task.take();
1406
1407        let Some(configured_model) = self.thread.read(cx).configured_model() else {
1408            state.last_estimated_token_count.take();
1409            return;
1410        };
1411
1412        let editor = state.editor.clone();
1413        let thread = self.thread.clone();
1414        let message_id = *message_id;
1415
1416        state._update_token_count_task = Some(cx.spawn(async move |this, cx| {
1417            if debounce {
1418                cx.background_executor()
1419                    .timer(Duration::from_millis(200))
1420                    .await;
1421            }
1422
1423            let token_count = if let Some(task) = cx
1424                .update(|cx| {
1425                    let Some(message) = thread.read(cx).message(message_id) else {
1426                        log::error!("Message that was being edited no longer exists");
1427                        return None;
1428                    };
1429                    let message_text = editor.read(cx).text(cx);
1430
1431                    if message_text.is_empty() && message.loaded_context.is_empty() {
1432                        return None;
1433                    }
1434
1435                    let mut request_message = LanguageModelRequestMessage {
1436                        role: language_model::Role::User,
1437                        content: Vec::new(),
1438                        cache: false,
1439                    };
1440
1441                    message
1442                        .loaded_context
1443                        .add_to_request_message(&mut request_message);
1444
1445                    if !message_text.is_empty() {
1446                        request_message
1447                            .content
1448                            .push(MessageContent::Text(message_text));
1449                    }
1450
1451                    let request = language_model::LanguageModelRequest {
1452                        thread_id: None,
1453                        prompt_id: None,
1454                        intent: None,
1455                        mode: None,
1456                        messages: vec![request_message],
1457                        tools: vec![],
1458                        tool_choice: None,
1459                        stop: vec![],
1460                        temperature: AgentSettings::temperature_for_model(
1461                            &configured_model.model,
1462                            cx,
1463                        ),
1464                    };
1465
1466                    Some(configured_model.model.count_tokens(request, cx))
1467                })
1468                .ok()
1469                .flatten()
1470            {
1471                task.await.log_err()
1472            } else {
1473                Some(0)
1474            };
1475
1476            if let Some(token_count) = token_count {
1477                this.update(cx, |this, cx| {
1478                    let Some((_message_id, state)) = this.editing_message.as_mut() else {
1479                        return;
1480                    };
1481
1482                    state.last_estimated_token_count = Some(token_count);
1483                    cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1484                })
1485                .ok();
1486            };
1487        }));
1488    }
1489
1490    fn toggle_context_picker(
1491        &mut self,
1492        _: &crate::ToggleContextPicker,
1493        window: &mut Window,
1494        cx: &mut Context<Self>,
1495    ) {
1496        if let Some((_, state)) = self.editing_message.as_mut() {
1497            let handle = state.context_picker_menu_handle.clone();
1498            window.defer(cx, move |window, cx| {
1499                handle.toggle(window, cx);
1500            });
1501        }
1502    }
1503
1504    fn remove_all_context(
1505        &mut self,
1506        _: &crate::RemoveAllContext,
1507        _window: &mut Window,
1508        cx: &mut Context<Self>,
1509    ) {
1510        self.context_store.update(cx, |store, cx| store.clear(cx));
1511        cx.notify();
1512    }
1513
1514    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
1515        if let Some((_, state)) = self.editing_message.as_mut() {
1516            if state.context_picker_menu_handle.is_deployed() {
1517                cx.propagate();
1518            } else {
1519                state.context_strip.focus_handle(cx).focus(window);
1520            }
1521        }
1522    }
1523
1524    fn paste(&mut self, _: &Paste, _window: &mut Window, cx: &mut Context<Self>) {
1525        attach_pasted_images_as_context(&self.context_store, cx);
1526    }
1527
1528    fn cancel_editing_message(
1529        &mut self,
1530        _: &menu::Cancel,
1531        window: &mut Window,
1532        cx: &mut Context<Self>,
1533    ) {
1534        self.editing_message.take();
1535        cx.notify();
1536
1537        if let Some(workspace) = self.workspace.upgrade() {
1538            workspace.update(cx, |workspace, cx| {
1539                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
1540                    panel.focus_handle(cx).focus(window);
1541                }
1542            });
1543        }
1544    }
1545
1546    fn confirm_editing_message(
1547        &mut self,
1548        _: &menu::Confirm,
1549        window: &mut Window,
1550        cx: &mut Context<Self>,
1551    ) {
1552        let Some((message_id, state)) = self.editing_message.take() else {
1553            return;
1554        };
1555
1556        let Some(model) = self
1557            .thread
1558            .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
1559        else {
1560            return;
1561        };
1562
1563        if model.provider.must_accept_terms(cx) {
1564            cx.notify();
1565            return;
1566        }
1567
1568        let edited_text = state.editor.read(cx).text(cx);
1569
1570        let creases = state.editor.update(cx, extract_message_creases);
1571
1572        let new_context = self
1573            .context_store
1574            .read(cx)
1575            .new_context_for_thread(self.thread.read(cx), Some(message_id));
1576
1577        let project = self.thread.read(cx).project().clone();
1578        let prompt_store = self.thread_store.read(cx).prompt_store().clone();
1579
1580        let git_store = project.read(cx).git_store().clone();
1581        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
1582
1583        let load_context_task = context::load_context(new_context, &project, &prompt_store, cx);
1584        self._load_edited_message_context_task =
1585            Some(cx.spawn_in(window, async move |this, cx| {
1586                let (context, checkpoint) =
1587                    futures::future::join(load_context_task, checkpoint).await;
1588                let _ = this
1589                    .update_in(cx, |this, window, cx| {
1590                        this.thread.update(cx, |thread, cx| {
1591                            thread.edit_message(
1592                                message_id,
1593                                Role::User,
1594                                vec![MessageSegment::Text(edited_text)],
1595                                creases,
1596                                Some(context.loaded_context),
1597                                checkpoint.ok(),
1598                                cx,
1599                            );
1600                            for message_id in this.messages_after(message_id) {
1601                                thread.delete_message(*message_id, cx);
1602                            }
1603                        });
1604
1605                        this.thread.update(cx, |thread, cx| {
1606                            thread.advance_prompt_id();
1607                            thread.cancel_last_completion(Some(window.window_handle()), cx);
1608                            thread.send_to_model(
1609                                model.model,
1610                                CompletionIntent::UserPrompt,
1611                                Some(window.window_handle()),
1612                                cx,
1613                            );
1614                        });
1615                        this._load_edited_message_context_task = None;
1616                        cx.notify();
1617                    })
1618                    .log_err();
1619            }));
1620
1621        if let Some(workspace) = self.workspace.upgrade() {
1622            workspace.update(cx, |workspace, cx| {
1623                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
1624                    panel.focus_handle(cx).focus(window);
1625                }
1626            });
1627        }
1628    }
1629
1630    fn messages_after(&self, message_id: MessageId) -> &[MessageId] {
1631        self.messages
1632            .iter()
1633            .position(|id| *id == message_id)
1634            .map(|index| &self.messages[index + 1..])
1635            .unwrap_or(&[])
1636    }
1637
1638    fn handle_cancel_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1639        self.cancel_editing_message(&menu::Cancel, window, cx);
1640    }
1641
1642    fn handle_regenerate_click(
1643        &mut self,
1644        _: &ClickEvent,
1645        window: &mut Window,
1646        cx: &mut Context<Self>,
1647    ) {
1648        self.confirm_editing_message(&menu::Confirm, window, cx);
1649    }
1650
1651    fn handle_feedback_click(
1652        &mut self,
1653        message_id: MessageId,
1654        feedback: ThreadFeedback,
1655        window: &mut Window,
1656        cx: &mut Context<Self>,
1657    ) {
1658        let report = self.thread.update(cx, |thread, cx| {
1659            thread.report_message_feedback(message_id, feedback, cx)
1660        });
1661
1662        cx.spawn(async move |this, cx| {
1663            report.await?;
1664            this.update(cx, |_this, cx| cx.notify())
1665        })
1666        .detach_and_log_err(cx);
1667
1668        match feedback {
1669            ThreadFeedback::Positive => {
1670                self.open_feedback_editors.remove(&message_id);
1671            }
1672            ThreadFeedback::Negative => {
1673                self.handle_show_feedback_comments(message_id, window, cx);
1674            }
1675        }
1676    }
1677
1678    fn handle_show_feedback_comments(
1679        &mut self,
1680        message_id: MessageId,
1681        window: &mut Window,
1682        cx: &mut Context<Self>,
1683    ) {
1684        let buffer = cx.new(|cx| {
1685            let empty_string = String::new();
1686            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1687        });
1688
1689        let editor = cx.new(|cx| {
1690            let mut editor = Editor::new(
1691                editor::EditorMode::AutoHeight {
1692                    min_lines: 1,
1693                    max_lines: Some(4),
1694                },
1695                buffer,
1696                None,
1697                window,
1698                cx,
1699            );
1700            editor.set_placeholder_text(
1701                "What went wrong? Share your feedback so we can improve.",
1702                cx,
1703            );
1704            editor
1705        });
1706
1707        editor.read(cx).focus_handle(cx).focus(window);
1708        self.open_feedback_editors.insert(message_id, editor);
1709        cx.notify();
1710    }
1711
1712    fn submit_feedback_message(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
1713        let Some(editor) = self.open_feedback_editors.get(&message_id) else {
1714            return;
1715        };
1716
1717        let report_task = self.thread.update(cx, |thread, cx| {
1718            thread.report_message_feedback(message_id, ThreadFeedback::Negative, cx)
1719        });
1720
1721        let comments = editor.read(cx).text(cx);
1722        if !comments.is_empty() {
1723            let thread_id = self.thread.read(cx).id().clone();
1724            let comments_value = String::from(comments.as_str());
1725
1726            let message_content = self
1727                .thread
1728                .read(cx)
1729                .message(message_id)
1730                .map(|msg| msg.to_string())
1731                .unwrap_or_default();
1732
1733            telemetry::event!(
1734                "Assistant Thread Feedback Comments",
1735                thread_id,
1736                message_id = message_id.as_usize(),
1737                message_content,
1738                comments = comments_value
1739            );
1740
1741            self.open_feedback_editors.remove(&message_id);
1742
1743            cx.spawn(async move |this, cx| {
1744                report_task.await?;
1745                this.update(cx, |_this, cx| cx.notify())
1746            })
1747            .detach_and_log_err(cx);
1748        }
1749    }
1750
1751    fn render_edit_message_editor(
1752        &self,
1753        state: &EditingMessageState,
1754        _window: &mut Window,
1755        cx: &Context<Self>,
1756    ) -> impl IntoElement {
1757        let settings = ThemeSettings::get_global(cx);
1758        let font_size = TextSize::Small
1759            .rems(cx)
1760            .to_pixels(settings.agent_font_size(cx));
1761        let line_height = font_size * 1.75;
1762
1763        let colors = cx.theme().colors();
1764
1765        let text_style = TextStyle {
1766            color: colors.text,
1767            font_family: settings.buffer_font.family.clone(),
1768            font_fallbacks: settings.buffer_font.fallbacks.clone(),
1769            font_features: settings.buffer_font.features.clone(),
1770            font_size: font_size.into(),
1771            line_height: line_height.into(),
1772            ..Default::default()
1773        };
1774
1775        v_flex()
1776            .key_context("EditMessageEditor")
1777            .on_action(cx.listener(Self::toggle_context_picker))
1778            .on_action(cx.listener(Self::remove_all_context))
1779            .on_action(cx.listener(Self::move_up))
1780            .on_action(cx.listener(Self::cancel_editing_message))
1781            .on_action(cx.listener(Self::confirm_editing_message))
1782            .capture_action(cx.listener(Self::paste))
1783            .min_h_6()
1784            .w_full()
1785            .flex_grow()
1786            .gap_2()
1787            .child(state.context_strip.clone())
1788            .child(div().pt(px(-3.)).px_neg_0p5().child(EditorElement::new(
1789                &state.editor,
1790                EditorStyle {
1791                    background: colors.editor_background,
1792                    local_player: cx.theme().players().local(),
1793                    text: text_style,
1794                    syntax: cx.theme().syntax().clone(),
1795                    ..Default::default()
1796                },
1797            )))
1798    }
1799
1800    fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1801        let message_id = self.messages[ix];
1802        let workspace = self.workspace.clone();
1803        let thread = self.thread.read(cx);
1804
1805        let is_first_message = ix == 0;
1806        let is_last_message = ix == self.messages.len() - 1;
1807
1808        let Some(message) = thread.message(message_id) else {
1809            return Empty.into_any();
1810        };
1811
1812        let is_generating = thread.is_generating();
1813        let is_generating_stale = thread.is_generation_stale().unwrap_or(false);
1814
1815        let loading_dots = (is_generating && is_last_message).then(|| {
1816            h_flex()
1817                .h_8()
1818                .my_3()
1819                .mx_5()
1820                .when(is_generating_stale || message.is_hidden, |this| {
1821                    this.child(LoadingLabel::new("").size(LabelSize::Small))
1822                })
1823        });
1824
1825        if message.is_hidden {
1826            return div().children(loading_dots).into_any();
1827        }
1828
1829        let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1830            return Empty.into_any();
1831        };
1832
1833        // Get all the data we need from thread before we start using it in closures
1834        let checkpoint = thread.checkpoint_for_message(message_id);
1835        let configured_model = thread.configured_model().map(|m| m.model);
1836        let added_context = thread
1837            .context_for_message(message_id)
1838            .map(|context| AddedContext::new_attached(context, configured_model.as_ref(), cx))
1839            .collect::<Vec<_>>();
1840
1841        let tool_uses = thread.tool_uses_for_message(message_id, cx);
1842        let has_tool_uses = !tool_uses.is_empty();
1843
1844        let editing_message_state = self
1845            .editing_message
1846            .as_ref()
1847            .filter(|(id, _)| *id == message_id)
1848            .map(|(_, state)| state);
1849
1850        let (editor_bg_color, panel_bg) = {
1851            let colors = cx.theme().colors();
1852            (colors.editor_background, colors.panel_background)
1853        };
1854
1855        let open_as_markdown = IconButton::new(("open-as-markdown", ix), IconName::DocumentText)
1856            .icon_size(IconSize::XSmall)
1857            .icon_color(Color::Ignored)
1858            .tooltip(Tooltip::text("Open Thread as Markdown"))
1859            .on_click({
1860                let thread = self.thread.clone();
1861                let workspace = self.workspace.clone();
1862                move |_, window, cx| {
1863                    if let Some(workspace) = workspace.upgrade() {
1864                        open_active_thread_as_markdown(thread.clone(), workspace, window, cx)
1865                            .detach_and_log_err(cx);
1866                    }
1867                }
1868            });
1869
1870        let scroll_to_top = IconButton::new(("scroll_to_top", ix), IconName::ArrowUpAlt)
1871            .icon_size(IconSize::XSmall)
1872            .icon_color(Color::Ignored)
1873            .tooltip(Tooltip::text("Scroll To Top"))
1874            .on_click(cx.listener(move |this, _, _, cx| {
1875                this.scroll_to_top(cx);
1876            }));
1877
1878        let show_feedback = thread.is_turn_end(ix);
1879        let feedback_container = h_flex()
1880            .group("feedback_container")
1881            .mt_1()
1882            .py_2()
1883            .px(RESPONSE_PADDING_X)
1884            .mr_1()
1885            .opacity(0.4)
1886            .hover(|style| style.opacity(1.))
1887            .gap_1p5()
1888            .flex_wrap()
1889            .justify_end();
1890        let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1891            Some(feedback) => feedback_container
1892                .child(
1893                    div().visible_on_hover("feedback_container").child(
1894                        Label::new(match feedback {
1895                            ThreadFeedback::Positive => "Thanks for your feedback!",
1896                            ThreadFeedback::Negative => {
1897                                "We appreciate your feedback and will use it to improve."
1898                            }
1899                        })
1900                    .color(Color::Muted)
1901                    .size(LabelSize::XSmall)
1902                    .truncate())
1903                )
1904                .child(
1905                    h_flex()
1906                        .child(
1907                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1908                                .icon_size(IconSize::XSmall)
1909                                .icon_color(match feedback {
1910                                    ThreadFeedback::Positive => Color::Accent,
1911                                    ThreadFeedback::Negative => Color::Ignored,
1912                                })
1913                                .tooltip(Tooltip::text("Helpful Response"))
1914                                .on_click(cx.listener(move |this, _, window, cx| {
1915                                    this.handle_feedback_click(
1916                                        message_id,
1917                                        ThreadFeedback::Positive,
1918                                        window,
1919                                        cx,
1920                                    );
1921                                })),
1922                        )
1923                        .child(
1924                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1925                                .icon_size(IconSize::XSmall)
1926                                .icon_color(match feedback {
1927                                    ThreadFeedback::Positive => Color::Ignored,
1928                                    ThreadFeedback::Negative => Color::Accent,
1929                                })
1930                                .tooltip(Tooltip::text("Not Helpful"))
1931                                .on_click(cx.listener(move |this, _, window, cx| {
1932                                    this.handle_feedback_click(
1933                                        message_id,
1934                                        ThreadFeedback::Negative,
1935                                        window,
1936                                        cx,
1937                                    );
1938                                })),
1939                        )
1940                        .child(open_as_markdown),
1941                )
1942                .into_any_element(),
1943            None if AgentSettings::get_global(cx).enable_feedback =>
1944                feedback_container
1945                .child(
1946                    div().visible_on_hover("feedback_container").child(
1947                        Label::new(
1948                            "Rating the thread sends all of your current conversation to the Zed team.",
1949                        )
1950                        .color(Color::Muted)
1951                    .size(LabelSize::XSmall)
1952                    .truncate())
1953                )
1954                .child(
1955                    h_flex()
1956                        .child(
1957                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1958                                .icon_size(IconSize::XSmall)
1959                                .icon_color(Color::Ignored)
1960                                .tooltip(Tooltip::text("Helpful Response"))
1961                                .on_click(cx.listener(move |this, _, window, cx| {
1962                                    this.handle_feedback_click(
1963                                        message_id,
1964                                        ThreadFeedback::Positive,
1965                                        window,
1966                                        cx,
1967                                    );
1968                                })),
1969                        )
1970                        .child(
1971                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1972                                .icon_size(IconSize::XSmall)
1973                                .icon_color(Color::Ignored)
1974                                .tooltip(Tooltip::text("Not Helpful"))
1975                                .on_click(cx.listener(move |this, _, window, cx| {
1976                                    this.handle_feedback_click(
1977                                        message_id,
1978                                        ThreadFeedback::Negative,
1979                                        window,
1980                                        cx,
1981                                    );
1982                                })),
1983                        )
1984                        .child(open_as_markdown)
1985                        .child(scroll_to_top),
1986                )
1987                .into_any_element(),
1988            None => feedback_container
1989                .child(h_flex()
1990                    .child(open_as_markdown))
1991                    .child(scroll_to_top)
1992                .into_any_element(),
1993        };
1994
1995        let message_is_empty = message.should_display_content();
1996        let has_content = !message_is_empty || !added_context.is_empty();
1997
1998        let message_content = has_content.then(|| {
1999            if let Some(state) = editing_message_state.as_ref() {
2000                self.render_edit_message_editor(state, window, cx)
2001                    .into_any_element()
2002            } else {
2003                v_flex()
2004                    .w_full()
2005                    .gap_1()
2006                    .when(!added_context.is_empty(), |parent| {
2007                        parent.child(h_flex().flex_wrap().gap_1().children(
2008                            added_context.into_iter().map(|added_context| {
2009                                let context = added_context.handle.clone();
2010                                ContextPill::added(added_context, false, false, None).on_click(
2011                                    Rc::new(cx.listener({
2012                                        let workspace = workspace.clone();
2013                                        move |_, _, window, cx| {
2014                                            if let Some(workspace) = workspace.upgrade() {
2015                                                open_context(&context, workspace, window, cx);
2016                                                cx.notify();
2017                                            }
2018                                        }
2019                                    })),
2020                                )
2021                            }),
2022                        ))
2023                    })
2024                    .when(!message_is_empty, |parent| {
2025                        parent.child(div().pt_0p5().min_h_6().child(self.render_message_content(
2026                            message_id,
2027                            rendered_message,
2028                            has_tool_uses,
2029                            workspace.clone(),
2030                            window,
2031                            cx,
2032                        )))
2033                    })
2034                    .into_any_element()
2035            }
2036        });
2037
2038        let styled_message = if message.ui_only {
2039            self.render_ui_notification(message_content, ix, cx)
2040        } else {
2041            match message.role {
2042                Role::User => {
2043                    let colors = cx.theme().colors();
2044                    v_flex()
2045                        .id(("message-container", ix))
2046                        .pt_2()
2047                        .pl_2()
2048                        .pr_2p5()
2049                        .pb_4()
2050                        .child(
2051                            v_flex()
2052                                .id(("user-message", ix))
2053                                .bg(editor_bg_color)
2054                                .rounded_lg()
2055                                .shadow_md()
2056                                .border_1()
2057                                .border_color(colors.border)
2058                                .hover(|hover| hover.border_color(colors.text_accent.opacity(0.5)))
2059                                .child(
2060                                    v_flex()
2061                                        .p_2p5()
2062                                        .gap_1()
2063                                        .children(message_content)
2064                                        .when_some(editing_message_state, |this, state| {
2065                                            let focus_handle = state.editor.focus_handle(cx).clone();
2066
2067                                            this.child(
2068                                                h_flex()
2069                                                    .w_full()
2070                                                    .gap_1()
2071                                                    .justify_between()
2072                                                    .flex_wrap()
2073                                                    .child(
2074                                                        h_flex()
2075                                                            .gap_1p5()
2076                                                            .child(
2077                                                                div()
2078                                                                    .opacity(0.8)
2079                                                                    .child(
2080                                                                        Icon::new(IconName::Warning)
2081                                                                            .size(IconSize::Indicator)
2082                                                                            .color(Color::Warning)
2083                                                                    ),
2084                                                            )
2085                                                            .child(
2086                                                                Label::new("Editing will restart the thread from this point.")
2087                                                                    .color(Color::Muted)
2088                                                                    .size(LabelSize::XSmall),
2089                                                            ),
2090                                                    )
2091                                                    .child(
2092                                                        h_flex()
2093                                                            .gap_0p5()
2094                                                            .child(
2095                                                                IconButton::new(
2096                                                                    "cancel-edit-message",
2097                                                                    IconName::Close,
2098                                                                )
2099                                                                .shape(ui::IconButtonShape::Square)
2100                                                                .icon_color(Color::Error)
2101                                                                .icon_size(IconSize::Small)
2102                                                                .tooltip({
2103                                                                    let focus_handle = focus_handle.clone();
2104                                                                    move |window, cx| {
2105                                                                        Tooltip::for_action_in(
2106                                                                            "Cancel Edit",
2107                                                                            &menu::Cancel,
2108                                                                            &focus_handle,
2109                                                                            window,
2110                                                                            cx,
2111                                                                        )
2112                                                                    }
2113                                                                })
2114                                                                .on_click(cx.listener(Self::handle_cancel_click)),
2115                                                            )
2116                                                            .child(
2117                                                                IconButton::new(
2118                                                                    "confirm-edit-message",
2119                                                                    IconName::Return,
2120                                                                )
2121                                                                .disabled(state.editor.read(cx).is_empty(cx))
2122                                                                .shape(ui::IconButtonShape::Square)
2123                                                                .icon_color(Color::Muted)
2124                                                                .icon_size(IconSize::Small)
2125                                                                .tooltip({
2126                                                                    let focus_handle = focus_handle.clone();
2127                                                                    move |window, cx| {
2128                                                                        Tooltip::for_action_in(
2129                                                                            "Regenerate",
2130                                                                            &menu::Confirm,
2131                                                                            &focus_handle,
2132                                                                            window,
2133                                                                            cx,
2134                                                                        )
2135                                                                    }
2136                                                                })
2137                                                                .on_click(
2138                                                                    cx.listener(Self::handle_regenerate_click),
2139                                                                ),
2140                                                            ),
2141                                                    )
2142                                            )
2143                                        }),
2144                                )
2145                                .on_click(cx.listener({
2146                                    let message_creases = message.creases.clone();
2147                                    move |this, _, window, cx| {
2148                                        if let Some(message_text) =
2149                                            this.thread.read(cx).message(message_id).and_then(|message| {
2150                                                message.segments.first().and_then(|segment| {
2151                                                    match segment {
2152                                                        MessageSegment::Text(message_text) => {
2153                                                            Some(Into::<Arc<str>>::into(message_text.as_str()))
2154                                                        }
2155                                                        _ => {
2156                                                            None
2157                                                        }
2158                                                    }
2159                                                })
2160                                            })
2161                                        {
2162                                            this.start_editing_message(
2163                                                message_id,
2164                                                message_text,
2165                                                &message_creases,
2166                                                window,
2167                                                cx,
2168                                            );
2169                                        }
2170                                    }
2171                                })),
2172                        )
2173                }
2174                Role::Assistant => v_flex()
2175                    .id(("message-container", ix))
2176                    .px(RESPONSE_PADDING_X)
2177                    .gap_2()
2178                    .children(message_content)
2179                    .when(has_tool_uses, |parent| {
2180                        parent.children(tool_uses.into_iter().map(|tool_use| {
2181                            self.render_tool_use(tool_use, window, workspace.clone(), cx)
2182                        }))
2183                    }),
2184                Role::System => {
2185                    let colors = cx.theme().colors();
2186                    div().id(("message-container", ix)).py_1().px_2().child(
2187                        v_flex()
2188                            .bg(colors.editor_background)
2189                            .rounded_sm()
2190                            .child(div().p_4().children(message_content)),
2191                    )
2192                }
2193            }
2194        };
2195
2196        let after_editing_message = self
2197            .editing_message
2198            .as_ref()
2199            .map_or(false, |(editing_message_id, _)| {
2200                message_id > *editing_message_id
2201            });
2202
2203        let backdrop = div()
2204            .id(("backdrop", ix))
2205            .size_full()
2206            .absolute()
2207            .inset_0()
2208            .bg(panel_bg)
2209            .opacity(0.8)
2210            .block_mouse_except_scroll()
2211            .on_click(cx.listener(Self::handle_cancel_click));
2212
2213        v_flex()
2214            .w_full()
2215            .map(|parent| {
2216                if let Some(checkpoint) = checkpoint.filter(|_| !is_generating) {
2217                    let mut is_pending = false;
2218                    let mut error = None;
2219                    if let Some(last_restore_checkpoint) =
2220                        self.thread.read(cx).last_restore_checkpoint()
2221                    {
2222                        if last_restore_checkpoint.message_id() == message_id {
2223                            match last_restore_checkpoint {
2224                                LastRestoreCheckpoint::Pending { .. } => is_pending = true,
2225                                LastRestoreCheckpoint::Error { error: err, .. } => {
2226                                    error = Some(err.clone());
2227                                }
2228                            }
2229                        }
2230                    }
2231
2232                    let restore_checkpoint_button =
2233                        Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
2234                            .icon(if error.is_some() {
2235                                IconName::XCircle
2236                            } else {
2237                                IconName::Undo
2238                            })
2239                            .icon_size(IconSize::XSmall)
2240                            .icon_position(IconPosition::Start)
2241                            .icon_color(if error.is_some() {
2242                                Some(Color::Error)
2243                            } else {
2244                                None
2245                            })
2246                            .label_size(LabelSize::XSmall)
2247                            .disabled(is_pending)
2248                            .on_click(cx.listener(move |this, _, _window, cx| {
2249                                this.thread.update(cx, |thread, cx| {
2250                                    thread
2251                                        .restore_checkpoint(checkpoint.clone(), cx)
2252                                        .detach_and_log_err(cx);
2253                                });
2254                            }));
2255
2256                    let restore_checkpoint_button = if is_pending {
2257                        restore_checkpoint_button
2258                            .with_animation(
2259                                ("pulsating-restore-checkpoint-button", ix),
2260                                Animation::new(Duration::from_secs(2))
2261                                    .repeat()
2262                                    .with_easing(pulsating_between(0.6, 1.)),
2263                                |label, delta| label.alpha(delta),
2264                            )
2265                            .into_any_element()
2266                    } else if let Some(error) = error {
2267                        restore_checkpoint_button
2268                            .tooltip(Tooltip::text(error.to_string()))
2269                            .into_any_element()
2270                    } else {
2271                        restore_checkpoint_button.into_any_element()
2272                    };
2273
2274                    parent.child(
2275                        h_flex()
2276                            .pt_2p5()
2277                            .px_2p5()
2278                            .w_full()
2279                            .gap_1()
2280                            .child(ui::Divider::horizontal())
2281                            .child(restore_checkpoint_button)
2282                            .child(ui::Divider::horizontal()),
2283                    )
2284                } else {
2285                    parent
2286                }
2287            })
2288            .when(is_first_message, |parent| {
2289                parent.child(self.render_rules_item(cx))
2290            })
2291            .child(styled_message)
2292            .children(loading_dots)
2293            .when(show_feedback, move |parent| {
2294                parent.child(feedback_items).when_some(
2295                    self.open_feedback_editors.get(&message_id),
2296                    move |parent, feedback_editor| {
2297                        let focus_handle = feedback_editor.focus_handle(cx);
2298                        parent.child(
2299                            v_flex()
2300                                .key_context("AgentFeedbackMessageEditor")
2301                                .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2302                                    this.open_feedback_editors.remove(&message_id);
2303                                    cx.notify();
2304                                }))
2305                                .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2306                                    this.submit_feedback_message(message_id, cx);
2307                                    cx.notify();
2308                                }))
2309                                .on_action(cx.listener(Self::confirm_editing_message))
2310                                .mb_2()
2311                                .mx_4()
2312                                .p_2()
2313                                .rounded_md()
2314                                .border_1()
2315                                .border_color(cx.theme().colors().border)
2316                                .bg(cx.theme().colors().editor_background)
2317                                .child(feedback_editor.clone())
2318                                .child(
2319                                    h_flex()
2320                                        .gap_1()
2321                                        .justify_end()
2322                                        .child(
2323                                            Button::new("dismiss-feedback-message", "Cancel")
2324                                                .label_size(LabelSize::Small)
2325                                                .key_binding(
2326                                                    KeyBinding::for_action_in(
2327                                                        &menu::Cancel,
2328                                                        &focus_handle,
2329                                                        window,
2330                                                        cx,
2331                                                    )
2332                                                    .map(|kb| kb.size(rems_from_px(10.))),
2333                                                )
2334                                                .on_click(cx.listener(
2335                                                    move |this, _, _window, cx| {
2336                                                        this.open_feedback_editors
2337                                                            .remove(&message_id);
2338                                                        cx.notify();
2339                                                    },
2340                                                )),
2341                                        )
2342                                        .child(
2343                                            Button::new(
2344                                                "submit-feedback-message",
2345                                                "Share Feedback",
2346                                            )
2347                                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2348                                            .label_size(LabelSize::Small)
2349                                            .key_binding(
2350                                                KeyBinding::for_action_in(
2351                                                    &menu::Confirm,
2352                                                    &focus_handle,
2353                                                    window,
2354                                                    cx,
2355                                                )
2356                                                .map(|kb| kb.size(rems_from_px(10.))),
2357                                            )
2358                                            .on_click(
2359                                                cx.listener(move |this, _, _window, cx| {
2360                                                    this.submit_feedback_message(message_id, cx);
2361                                                    cx.notify()
2362                                                }),
2363                                            ),
2364                                        ),
2365                                ),
2366                        )
2367                    },
2368                )
2369            })
2370            .when(after_editing_message, |parent| {
2371                // Backdrop to dim out the whole thread below the editing user message
2372                parent.relative().child(backdrop)
2373            })
2374            .into_any()
2375    }
2376
2377    fn render_message_content(
2378        &self,
2379        message_id: MessageId,
2380        rendered_message: &RenderedMessage,
2381        has_tool_uses: bool,
2382        workspace: WeakEntity<Workspace>,
2383        window: &Window,
2384        cx: &Context<Self>,
2385    ) -> impl IntoElement {
2386        let is_last_message = self.messages.last() == Some(&message_id);
2387        let is_generating = self.thread.read(cx).is_generating();
2388        let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2389            rendered_message
2390                .segments
2391                .iter()
2392                .enumerate()
2393                .next_back()
2394                .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2395                .map(|(index, _)| index)
2396        } else {
2397            None
2398        };
2399
2400        let message_role = self
2401            .thread
2402            .read(cx)
2403            .message(message_id)
2404            .map(|m| m.role)
2405            .unwrap_or(Role::User);
2406
2407        let is_assistant_message = message_role == Role::Assistant;
2408        let is_user_message = message_role == Role::User;
2409
2410        v_flex()
2411            .text_ui(cx)
2412            .gap_2()
2413            .when(is_user_message, |this| this.text_xs())
2414            .children(
2415                rendered_message.segments.iter().enumerate().map(
2416                    |(index, segment)| match segment {
2417                        RenderedMessageSegment::Thinking {
2418                            content,
2419                            scroll_handle,
2420                        } => self
2421                            .render_message_thinking_segment(
2422                                message_id,
2423                                index,
2424                                content.clone(),
2425                                &scroll_handle,
2426                                Some(index) == pending_thinking_segment_index,
2427                                window,
2428                                cx,
2429                            )
2430                            .into_any_element(),
2431                        RenderedMessageSegment::Text(markdown) => {
2432                            let markdown_element = MarkdownElement::new(
2433                                markdown.clone(),
2434                                if is_user_message {
2435                                    let mut style = default_markdown_style(window, cx);
2436                                    let mut text_style = window.text_style();
2437                                    let theme_settings = ThemeSettings::get_global(cx);
2438
2439                                    let buffer_font = theme_settings.buffer_font.family.clone();
2440                                    let buffer_font_size = TextSize::Small.rems(cx);
2441
2442                                    text_style.refine(&TextStyleRefinement {
2443                                        font_family: Some(buffer_font),
2444                                        font_size: Some(buffer_font_size.into()),
2445                                        ..Default::default()
2446                                    });
2447
2448                                    style.base_text_style = text_style;
2449                                    style
2450                                } else {
2451                                    default_markdown_style(window, cx)
2452                                },
2453                            );
2454
2455                            let markdown_element = if is_assistant_message {
2456                                markdown_element.code_block_renderer(
2457                                    markdown::CodeBlockRenderer::Custom {
2458                                        render: Arc::new({
2459                                            let workspace = workspace.clone();
2460                                            let active_thread = cx.entity();
2461                                            move |kind,
2462                                                  parsed_markdown,
2463                                                  range,
2464                                                  metadata,
2465                                                  window,
2466                                                  cx| {
2467                                                render_markdown_code_block(
2468                                                    message_id,
2469                                                    range.start,
2470                                                    kind,
2471                                                    parsed_markdown,
2472                                                    metadata,
2473                                                    active_thread.clone(),
2474                                                    workspace.clone(),
2475                                                    window,
2476                                                    cx,
2477                                                )
2478                                            }
2479                                        }),
2480                                        transform: Some(Arc::new({
2481                                            let active_thread = cx.entity();
2482
2483                                            move |element, range, _, _, cx| {
2484                                                let is_expanded = active_thread
2485                                                    .read(cx)
2486                                                    .is_codeblock_expanded(message_id, range.start);
2487
2488                                                if is_expanded {
2489                                                    return element;
2490                                                }
2491
2492                                                element
2493                                            }
2494                                        })),
2495                                    },
2496                                )
2497                            } else {
2498                                markdown_element.code_block_renderer(
2499                                    markdown::CodeBlockRenderer::Default {
2500                                        copy_button: false,
2501                                        copy_button_on_hover: false,
2502                                        border: true,
2503                                    },
2504                                )
2505                            };
2506
2507                            div()
2508                                .child(markdown_element.on_url_click({
2509                                    let workspace = self.workspace.clone();
2510                                    move |text, window, cx| {
2511                                        open_markdown_link(text, workspace.clone(), window, cx);
2512                                    }
2513                                }))
2514                                .into_any_element()
2515                        }
2516                    },
2517                ),
2518            )
2519    }
2520
2521    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2522        cx.theme().colors().border.opacity(0.5)
2523    }
2524
2525    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2526        cx.theme()
2527            .colors()
2528            .element_background
2529            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2530    }
2531
2532    fn render_ui_notification(
2533        &self,
2534        message_content: impl IntoIterator<Item = impl IntoElement>,
2535        ix: usize,
2536        cx: &mut Context<Self>,
2537    ) -> Stateful<Div> {
2538        let message = div()
2539            .flex_1()
2540            .min_w_0()
2541            .text_size(TextSize::XSmall.rems(cx))
2542            .text_color(cx.theme().colors().text_muted)
2543            .children(message_content);
2544
2545        div()
2546            .id(("message-container", ix))
2547            .py_1()
2548            .px_2p5()
2549            .child(Banner::new().severity(ui::Severity::Warning).child(message))
2550    }
2551
2552    fn render_message_thinking_segment(
2553        &self,
2554        message_id: MessageId,
2555        ix: usize,
2556        markdown: Entity<Markdown>,
2557        scroll_handle: &ScrollHandle,
2558        pending: bool,
2559        window: &Window,
2560        cx: &Context<Self>,
2561    ) -> impl IntoElement {
2562        let is_open = self
2563            .expanded_thinking_segments
2564            .get(&(message_id, ix))
2565            .copied()
2566            .unwrap_or_default();
2567
2568        let editor_bg = cx.theme().colors().panel_background;
2569
2570        div().map(|this| {
2571            if pending {
2572                this.v_flex()
2573                    .mt_neg_2()
2574                    .mb_1p5()
2575                    .child(
2576                        h_flex()
2577                            .group("disclosure-header")
2578                            .justify_between()
2579                            .child(
2580                                h_flex()
2581                                    .gap_1p5()
2582                                    .child(
2583                                        Icon::new(IconName::LightBulb)
2584                                            .size(IconSize::XSmall)
2585                                            .color(Color::Muted),
2586                                    )
2587                                    .child(LoadingLabel::new("Thinking").size(LabelSize::Small)),
2588                            )
2589                            .child(
2590                                h_flex()
2591                                    .gap_1()
2592                                    .child(
2593                                        div().visible_on_hover("disclosure-header").child(
2594                                            Disclosure::new("thinking-disclosure", is_open)
2595                                                .opened_icon(IconName::ChevronUp)
2596                                                .closed_icon(IconName::ChevronDown)
2597                                                .on_click(cx.listener({
2598                                                    move |this, _event, _window, _cx| {
2599                                                        let is_open = this
2600                                                            .expanded_thinking_segments
2601                                                            .entry((message_id, ix))
2602                                                            .or_insert(false);
2603
2604                                                        *is_open = !*is_open;
2605                                                    }
2606                                                })),
2607                                        ),
2608                                    )
2609                                    .child({
2610                                        Icon::new(IconName::ArrowCircle)
2611                                            .color(Color::Accent)
2612                                            .size(IconSize::Small)
2613                                            .with_animation(
2614                                                "arrow-circle",
2615                                                Animation::new(Duration::from_secs(2)).repeat(),
2616                                                |icon, delta| {
2617                                                    icon.transform(Transformation::rotate(
2618                                                        percentage(delta),
2619                                                    ))
2620                                                },
2621                                            )
2622                                    }),
2623                            ),
2624                    )
2625                    .when(!is_open, |this| {
2626                        let gradient_overlay = div()
2627                            .rounded_b_lg()
2628                            .h_full()
2629                            .absolute()
2630                            .w_full()
2631                            .bottom_0()
2632                            .left_0()
2633                            .bg(linear_gradient(
2634                                180.,
2635                                linear_color_stop(editor_bg, 1.),
2636                                linear_color_stop(editor_bg.opacity(0.2), 0.),
2637                            ));
2638
2639                        this.child(
2640                            div()
2641                                .relative()
2642                                .bg(editor_bg)
2643                                .rounded_b_lg()
2644                                .mt_2()
2645                                .pl_4()
2646                                .child(
2647                                    div()
2648                                        .id(("thinking-content", ix))
2649                                        .max_h_20()
2650                                        .track_scroll(scroll_handle)
2651                                        .text_ui_sm(cx)
2652                                        .overflow_hidden()
2653                                        .child(
2654                                            MarkdownElement::new(
2655                                                markdown.clone(),
2656                                                default_markdown_style(window, cx),
2657                                            )
2658                                            .on_url_click({
2659                                                let workspace = self.workspace.clone();
2660                                                move |text, window, cx| {
2661                                                    open_markdown_link(
2662                                                        text,
2663                                                        workspace.clone(),
2664                                                        window,
2665                                                        cx,
2666                                                    );
2667                                                }
2668                                            }),
2669                                        ),
2670                                )
2671                                .child(gradient_overlay),
2672                        )
2673                    })
2674                    .when(is_open, |this| {
2675                        this.child(
2676                            div()
2677                                .id(("thinking-content", ix))
2678                                .h_full()
2679                                .bg(editor_bg)
2680                                .text_ui_sm(cx)
2681                                .child(
2682                                    MarkdownElement::new(
2683                                        markdown.clone(),
2684                                        default_markdown_style(window, cx),
2685                                    )
2686                                    .on_url_click({
2687                                        let workspace = self.workspace.clone();
2688                                        move |text, window, cx| {
2689                                            open_markdown_link(text, workspace.clone(), window, cx);
2690                                        }
2691                                    }),
2692                                ),
2693                        )
2694                    })
2695            } else {
2696                this.v_flex()
2697                    .mt_neg_2()
2698                    .child(
2699                        h_flex()
2700                            .group("disclosure-header")
2701                            .pr_1()
2702                            .justify_between()
2703                            .opacity(0.8)
2704                            .hover(|style| style.opacity(1.))
2705                            .child(
2706                                h_flex()
2707                                    .gap_1p5()
2708                                    .child(
2709                                        Icon::new(IconName::LightBulb)
2710                                            .size(IconSize::XSmall)
2711                                            .color(Color::Muted),
2712                                    )
2713                                    .child(Label::new("Thought Process").size(LabelSize::Small)),
2714                            )
2715                            .child(
2716                                div().visible_on_hover("disclosure-header").child(
2717                                    Disclosure::new("thinking-disclosure", is_open)
2718                                        .opened_icon(IconName::ChevronUp)
2719                                        .closed_icon(IconName::ChevronDown)
2720                                        .on_click(cx.listener({
2721                                            move |this, _event, _window, _cx| {
2722                                                let is_open = this
2723                                                    .expanded_thinking_segments
2724                                                    .entry((message_id, ix))
2725                                                    .or_insert(false);
2726
2727                                                *is_open = !*is_open;
2728                                            }
2729                                        })),
2730                                ),
2731                            ),
2732                    )
2733                    .child(
2734                        div()
2735                            .id(("thinking-content", ix))
2736                            .relative()
2737                            .mt_1p5()
2738                            .ml_1p5()
2739                            .pl_2p5()
2740                            .border_l_1()
2741                            .border_color(cx.theme().colors().border_variant)
2742                            .text_ui_sm(cx)
2743                            .when(is_open, |this| {
2744                                this.child(
2745                                    MarkdownElement::new(
2746                                        markdown.clone(),
2747                                        default_markdown_style(window, cx),
2748                                    )
2749                                    .on_url_click({
2750                                        let workspace = self.workspace.clone();
2751                                        move |text, window, cx| {
2752                                            open_markdown_link(text, workspace.clone(), window, cx);
2753                                        }
2754                                    }),
2755                                )
2756                            }),
2757                    )
2758            }
2759        })
2760    }
2761
2762    fn render_tool_use(
2763        &self,
2764        tool_use: ToolUse,
2765        window: &mut Window,
2766        workspace: WeakEntity<Workspace>,
2767        cx: &mut Context<Self>,
2768    ) -> impl IntoElement + use<> {
2769        if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2770            return card.render(&tool_use.status, window, workspace, cx);
2771        }
2772
2773        let is_open = self
2774            .expanded_tool_uses
2775            .get(&tool_use.id)
2776            .copied()
2777            .unwrap_or_default();
2778
2779        let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2780
2781        let fs = self
2782            .workspace
2783            .upgrade()
2784            .map(|workspace| workspace.read(cx).app_state().fs.clone());
2785        let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2786        let needs_confirmation_tools = tool_use.needs_confirmation;
2787
2788        let status_icons = div().child(match &tool_use.status {
2789            ToolUseStatus::NeedsConfirmation => {
2790                let icon = Icon::new(IconName::Warning)
2791                    .color(Color::Warning)
2792                    .size(IconSize::Small);
2793                icon.into_any_element()
2794            }
2795            ToolUseStatus::Pending
2796            | ToolUseStatus::InputStillStreaming
2797            | ToolUseStatus::Running => {
2798                let icon = Icon::new(IconName::ArrowCircle)
2799                    .color(Color::Accent)
2800                    .size(IconSize::Small);
2801                icon.with_animation(
2802                    "arrow-circle",
2803                    Animation::new(Duration::from_secs(2)).repeat(),
2804                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2805                )
2806                .into_any_element()
2807            }
2808            ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2809            ToolUseStatus::Error(_) => {
2810                let icon = Icon::new(IconName::Close)
2811                    .color(Color::Error)
2812                    .size(IconSize::Small);
2813                icon.into_any_element()
2814            }
2815        });
2816
2817        let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2818        let results_content_container = || v_flex().p_2().gap_0p5();
2819
2820        let results_content = v_flex()
2821            .gap_1()
2822            .child(
2823                results_content_container()
2824                    .child(
2825                        Label::new("Input")
2826                            .size(LabelSize::XSmall)
2827                            .color(Color::Muted)
2828                            .buffer_font(cx),
2829                    )
2830                    .child(
2831                        div()
2832                            .w_full()
2833                            .text_ui_sm(cx)
2834                            .children(rendered_tool_use.as_ref().map(|rendered| {
2835                                MarkdownElement::new(
2836                                    rendered.input.clone(),
2837                                    tool_use_markdown_style(window, cx),
2838                                )
2839                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2840                                    copy_button: false,
2841                                    copy_button_on_hover: false,
2842                                    border: false,
2843                                })
2844                                .on_url_click({
2845                                    let workspace = self.workspace.clone();
2846                                    move |text, window, cx| {
2847                                        open_markdown_link(text, workspace.clone(), window, cx);
2848                                    }
2849                                })
2850                            })),
2851                    ),
2852            )
2853            .map(|container| match tool_use.status {
2854                ToolUseStatus::Finished(_) => container.child(
2855                    results_content_container()
2856                        .border_t_1()
2857                        .border_color(self.tool_card_border_color(cx))
2858                        .child(
2859                            Label::new("Result")
2860                                .size(LabelSize::XSmall)
2861                                .color(Color::Muted)
2862                                .buffer_font(cx),
2863                        )
2864                        .child(div().w_full().text_ui_sm(cx).children(
2865                            rendered_tool_use.as_ref().map(|rendered| {
2866                                MarkdownElement::new(
2867                                    rendered.output.clone(),
2868                                    tool_use_markdown_style(window, cx),
2869                                )
2870                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2871                                    copy_button: false,
2872                                    copy_button_on_hover: false,
2873                                    border: false,
2874                                })
2875                                .on_url_click({
2876                                    let workspace = self.workspace.clone();
2877                                    move |text, window, cx| {
2878                                        open_markdown_link(text, workspace.clone(), window, cx);
2879                                    }
2880                                })
2881                                .into_any_element()
2882                            }),
2883                        )),
2884                ),
2885                ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2886                    results_content_container()
2887                        .border_t_1()
2888                        .border_color(self.tool_card_border_color(cx))
2889                        .child(
2890                            h_flex()
2891                                .gap_1()
2892                                .child(
2893                                    Icon::new(IconName::ArrowCircle)
2894                                        .size(IconSize::Small)
2895                                        .color(Color::Accent)
2896                                        .with_animation(
2897                                            "arrow-circle",
2898                                            Animation::new(Duration::from_secs(2)).repeat(),
2899                                            |icon, delta| {
2900                                                icon.transform(Transformation::rotate(percentage(
2901                                                    delta,
2902                                                )))
2903                                            },
2904                                        ),
2905                                )
2906                                .child(
2907                                    Label::new("Running…")
2908                                        .size(LabelSize::XSmall)
2909                                        .color(Color::Muted)
2910                                        .buffer_font(cx),
2911                                ),
2912                        ),
2913                ),
2914                ToolUseStatus::Error(_) => container.child(
2915                    results_content_container()
2916                        .border_t_1()
2917                        .border_color(self.tool_card_border_color(cx))
2918                        .child(
2919                            Label::new("Error")
2920                                .size(LabelSize::XSmall)
2921                                .color(Color::Muted)
2922                                .buffer_font(cx),
2923                        )
2924                        .child(
2925                            div()
2926                                .text_ui_sm(cx)
2927                                .children(rendered_tool_use.as_ref().map(|rendered| {
2928                                    MarkdownElement::new(
2929                                        rendered.output.clone(),
2930                                        tool_use_markdown_style(window, cx),
2931                                    )
2932                                    .on_url_click({
2933                                        let workspace = self.workspace.clone();
2934                                        move |text, window, cx| {
2935                                            open_markdown_link(text, workspace.clone(), window, cx);
2936                                        }
2937                                    })
2938                                    .into_any_element()
2939                                })),
2940                        ),
2941                ),
2942                ToolUseStatus::Pending => container,
2943                ToolUseStatus::NeedsConfirmation => container.child(
2944                    results_content_container()
2945                        .border_t_1()
2946                        .border_color(self.tool_card_border_color(cx))
2947                        .child(
2948                            Label::new("Asking Permission")
2949                                .size(LabelSize::Small)
2950                                .color(Color::Muted)
2951                                .buffer_font(cx),
2952                        ),
2953                ),
2954            });
2955
2956        let gradient_overlay = |color: Hsla| {
2957            div()
2958                .h_full()
2959                .absolute()
2960                .w_12()
2961                .bottom_0()
2962                .map(|element| {
2963                    if is_status_finished {
2964                        element.right_6()
2965                    } else {
2966                        element.right(px(44.))
2967                    }
2968                })
2969                .bg(linear_gradient(
2970                    90.,
2971                    linear_color_stop(color, 1.),
2972                    linear_color_stop(color.opacity(0.2), 0.),
2973                ))
2974        };
2975
2976        v_flex().gap_1().mb_2().map(|element| {
2977            if !needs_confirmation_tools {
2978                element.child(
2979                    v_flex()
2980                        .child(
2981                            h_flex()
2982                                .group("disclosure-header")
2983                                .relative()
2984                                .gap_1p5()
2985                                .justify_between()
2986                                .opacity(0.8)
2987                                .hover(|style| style.opacity(1.))
2988                                .when(!is_status_finished, |this| this.pr_2())
2989                                .child(
2990                                    h_flex()
2991                                        .id("tool-label-container")
2992                                        .gap_1p5()
2993                                        .max_w_full()
2994                                        .overflow_x_scroll()
2995                                        .child(
2996                                            Icon::new(tool_use.icon)
2997                                                .size(IconSize::XSmall)
2998                                                .color(Color::Muted),
2999                                        )
3000                                        .child(
3001                                            h_flex().pr_8().text_size(rems(0.8125)).children(
3002                                                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| {
3003                                                    open_markdown_link(text, workspace.clone(), window, cx);
3004                                                }}))
3005                                            ),
3006                                        ),
3007                                )
3008                                .child(
3009                                    h_flex()
3010                                        .gap_1()
3011                                        .child(
3012                                            div().visible_on_hover("disclosure-header").child(
3013                                                Disclosure::new("tool-use-disclosure", is_open)
3014                                                    .opened_icon(IconName::ChevronUp)
3015                                                    .closed_icon(IconName::ChevronDown)
3016                                                    .on_click(cx.listener({
3017                                                        let tool_use_id = tool_use.id.clone();
3018                                                        move |this, _event, _window, _cx| {
3019                                                            let is_open = this
3020                                                                .expanded_tool_uses
3021                                                                .entry(tool_use_id.clone())
3022                                                                .or_insert(false);
3023
3024                                                            *is_open = !*is_open;
3025                                                        }
3026                                                    })),
3027                                            ),
3028                                        )
3029                                        .child(status_icons),
3030                                )
3031                                .child(gradient_overlay(cx.theme().colors().panel_background)),
3032                        )
3033                        .map(|parent| {
3034                            if !is_open {
3035                                return parent;
3036                            }
3037
3038                            parent.child(
3039                                v_flex()
3040                                    .mt_1()
3041                                    .border_1()
3042                                    .border_color(self.tool_card_border_color(cx))
3043                                    .bg(cx.theme().colors().editor_background)
3044                                    .rounded_lg()
3045                                    .child(results_content),
3046                            )
3047                        }),
3048                )
3049            } else {
3050                v_flex()
3051                    .mb_2()
3052                    .rounded_lg()
3053                    .border_1()
3054                    .border_color(self.tool_card_border_color(cx))
3055                    .overflow_hidden()
3056                    .child(
3057                        h_flex()
3058                            .group("disclosure-header")
3059                            .relative()
3060                            .justify_between()
3061                            .py_1()
3062                            .map(|element| {
3063                                if is_status_finished {
3064                                    element.pl_2().pr_0p5()
3065                                } else {
3066                                    element.px_2()
3067                                }
3068                            })
3069                            .bg(self.tool_card_header_bg(cx))
3070                            .map(|element| {
3071                                if is_open {
3072                                    element.border_b_1().rounded_t_md()
3073                                } else if needs_confirmation {
3074                                    element.rounded_t_md()
3075                                } else {
3076                                    element.rounded_md()
3077                                }
3078                            })
3079                            .border_color(self.tool_card_border_color(cx))
3080                            .child(
3081                                h_flex()
3082                                    .id("tool-label-container")
3083                                    .gap_1p5()
3084                                    .max_w_full()
3085                                    .overflow_x_scroll()
3086                                    .child(
3087                                        Icon::new(tool_use.icon)
3088                                            .size(IconSize::XSmall)
3089                                            .color(Color::Muted),
3090                                    )
3091                                    .child(
3092                                        h_flex().pr_8().text_ui_sm(cx).children(
3093                                            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| {
3094                                                open_markdown_link(text, workspace.clone(), window, cx);
3095                                            }}))
3096                                        ),
3097                                    ),
3098                            )
3099                            .child(
3100                                h_flex()
3101                                    .gap_1()
3102                                    .child(
3103                                        div().visible_on_hover("disclosure-header").child(
3104                                            Disclosure::new("tool-use-disclosure", is_open)
3105                                                .opened_icon(IconName::ChevronUp)
3106                                                .closed_icon(IconName::ChevronDown)
3107                                                .on_click(cx.listener({
3108                                                    let tool_use_id = tool_use.id.clone();
3109                                                    move |this, _event, _window, _cx| {
3110                                                        let is_open = this
3111                                                            .expanded_tool_uses
3112                                                            .entry(tool_use_id.clone())
3113                                                            .or_insert(false);
3114
3115                                                        *is_open = !*is_open;
3116                                                    }
3117                                                })),
3118                                        ),
3119                                    )
3120                                    .child(status_icons),
3121                            )
3122                            .child(gradient_overlay(self.tool_card_header_bg(cx))),
3123                    )
3124                    .map(|parent| {
3125                        if !is_open {
3126                            return parent;
3127                        }
3128
3129                        parent.child(
3130                            v_flex()
3131                                .bg(cx.theme().colors().editor_background)
3132                                .map(|element| {
3133                                    if  needs_confirmation {
3134                                        element.rounded_none()
3135                                    } else {
3136                                        element.rounded_b_lg()
3137                                    }
3138                                })
3139                                .child(results_content),
3140                        )
3141                    })
3142                    .when(needs_confirmation, |this| {
3143                        this.child(
3144                            h_flex()
3145                                .py_1()
3146                                .pl_2()
3147                                .pr_1()
3148                                .gap_1()
3149                                .justify_between()
3150                                .flex_wrap()
3151                                .bg(cx.theme().colors().editor_background)
3152                                .border_t_1()
3153                                .border_color(self.tool_card_border_color(cx))
3154                                .rounded_b_lg()
3155                                .child(
3156                                    LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)
3157                                )
3158                                .child(
3159                                    h_flex()
3160                                        .gap_0p5()
3161                                        .child({
3162                                            let tool_id = tool_use.id.clone();
3163                                            Button::new(
3164                                                "always-allow-tool-action",
3165                                                "Always Allow",
3166                                            )
3167                                            .label_size(LabelSize::Small)
3168                                            .icon(IconName::CheckDouble)
3169                                            .icon_position(IconPosition::Start)
3170                                            .icon_size(IconSize::Small)
3171                                            .icon_color(Color::Success)
3172                                            .tooltip(move |window, cx|  {
3173                                                Tooltip::with_meta(
3174                                                    "Never ask for permission",
3175                                                    None,
3176                                                    "Restore the original behavior in your Agent Panel settings",
3177                                                    window,
3178                                                    cx,
3179                                                )
3180                                            })
3181                                            .on_click(cx.listener(
3182                                                move |this, event, window, cx| {
3183                                                    if let Some(fs) = fs.clone() {
3184                                                        update_settings_file::<AgentSettings>(
3185                                                            fs.clone(),
3186                                                            cx,
3187                                                            |settings, _| {
3188                                                                settings.set_always_allow_tool_actions(true);
3189                                                            },
3190                                                        );
3191                                                    }
3192                                                    this.handle_allow_tool(
3193                                                        tool_id.clone(),
3194                                                        event,
3195                                                        window,
3196                                                        cx,
3197                                                    )
3198                                                },
3199                                            ))
3200                                        })
3201                                        .child(ui::Divider::vertical())
3202                                        .child({
3203                                            let tool_id = tool_use.id.clone();
3204                                            Button::new("allow-tool-action", "Allow")
3205                                                .label_size(LabelSize::Small)
3206                                                .icon(IconName::Check)
3207                                                .icon_position(IconPosition::Start)
3208                                                .icon_size(IconSize::Small)
3209                                                .icon_color(Color::Success)
3210                                                .on_click(cx.listener(
3211                                                    move |this, event, window, cx| {
3212                                                        this.handle_allow_tool(
3213                                                            tool_id.clone(),
3214                                                            event,
3215                                                            window,
3216                                                            cx,
3217                                                        )
3218                                                    },
3219                                                ))
3220                                        })
3221                                        .child({
3222                                            let tool_id = tool_use.id.clone();
3223                                            let tool_name: Arc<str> = tool_use.name.into();
3224                                            Button::new("deny-tool", "Deny")
3225                                                .label_size(LabelSize::Small)
3226                                                .icon(IconName::Close)
3227                                                .icon_position(IconPosition::Start)
3228                                                .icon_size(IconSize::Small)
3229                                                .icon_color(Color::Error)
3230                                                .on_click(cx.listener(
3231                                                    move |this, event, window, cx| {
3232                                                        this.handle_deny_tool(
3233                                                            tool_id.clone(),
3234                                                            tool_name.clone(),
3235                                                            event,
3236                                                            window,
3237                                                            cx,
3238                                                        )
3239                                                    },
3240                                                ))
3241                                        }),
3242                                ),
3243                        )
3244                    })
3245            }
3246        }).into_any_element()
3247    }
3248
3249    fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3250        let project_context = self.thread.read(cx).project_context();
3251        let project_context = project_context.borrow();
3252        let Some(project_context) = project_context.as_ref() else {
3253            return div().into_any();
3254        };
3255
3256        let user_rules_text = if project_context.user_rules.is_empty() {
3257            None
3258        } else if project_context.user_rules.len() == 1 {
3259            let user_rules = &project_context.user_rules[0];
3260
3261            match user_rules.title.as_ref() {
3262                Some(title) => Some(format!("Using \"{title}\" user rule")),
3263                None => Some("Using user rule".into()),
3264            }
3265        } else {
3266            Some(format!(
3267                "Using {} user rules",
3268                project_context.user_rules.len()
3269            ))
3270        };
3271
3272        let first_user_rules_id = project_context
3273            .user_rules
3274            .first()
3275            .map(|user_rules| user_rules.uuid.0);
3276
3277        let rules_files = project_context
3278            .worktrees
3279            .iter()
3280            .filter_map(|worktree| worktree.rules_file.as_ref())
3281            .collect::<Vec<_>>();
3282
3283        let rules_file_text = match rules_files.as_slice() {
3284            &[] => None,
3285            &[rules_file] => Some(format!(
3286                "Using project {:?} file",
3287                rules_file.path_in_worktree
3288            )),
3289            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3290        };
3291
3292        if user_rules_text.is_none() && rules_file_text.is_none() {
3293            return div().into_any();
3294        }
3295
3296        v_flex()
3297            .pt_2()
3298            .px_2p5()
3299            .gap_1()
3300            .when_some(user_rules_text, |parent, user_rules_text| {
3301                parent.child(
3302                    h_flex()
3303                        .w_full()
3304                        .child(
3305                            Icon::new(RULES_ICON)
3306                                .size(IconSize::XSmall)
3307                                .color(Color::Disabled),
3308                        )
3309                        .child(
3310                            Label::new(user_rules_text)
3311                                .size(LabelSize::XSmall)
3312                                .color(Color::Muted)
3313                                .truncate()
3314                                .buffer_font(cx)
3315                                .ml_1p5()
3316                                .mr_0p5(),
3317                        )
3318                        .child(
3319                            IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3320                                .shape(ui::IconButtonShape::Square)
3321                                .icon_size(IconSize::XSmall)
3322                                .icon_color(Color::Ignored)
3323                                // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary`  keybinding
3324                                .tooltip(Tooltip::text("View User Rules"))
3325                                .on_click(move |_event, window, cx| {
3326                                    window.dispatch_action(
3327                                        Box::new(OpenRulesLibrary {
3328                                            prompt_to_select: first_user_rules_id,
3329                                        }),
3330                                        cx,
3331                                    )
3332                                }),
3333                        ),
3334                )
3335            })
3336            .when_some(rules_file_text, |parent, rules_file_text| {
3337                parent.child(
3338                    h_flex()
3339                        .w_full()
3340                        .child(
3341                            Icon::new(IconName::File)
3342                                .size(IconSize::XSmall)
3343                                .color(Color::Disabled),
3344                        )
3345                        .child(
3346                            Label::new(rules_file_text)
3347                                .size(LabelSize::XSmall)
3348                                .color(Color::Muted)
3349                                .buffer_font(cx)
3350                                .ml_1p5()
3351                                .mr_0p5(),
3352                        )
3353                        .child(
3354                            IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3355                                .shape(ui::IconButtonShape::Square)
3356                                .icon_size(IconSize::XSmall)
3357                                .icon_color(Color::Ignored)
3358                                .on_click(cx.listener(Self::handle_open_rules))
3359                                .tooltip(Tooltip::text("View Rules")),
3360                        ),
3361                )
3362            })
3363            .into_any()
3364    }
3365
3366    fn handle_allow_tool(
3367        &mut self,
3368        tool_use_id: LanguageModelToolUseId,
3369        _: &ClickEvent,
3370        window: &mut Window,
3371        cx: &mut Context<Self>,
3372    ) {
3373        if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3374            .thread
3375            .read(cx)
3376            .pending_tool(&tool_use_id)
3377            .map(|tool_use| tool_use.status.clone())
3378        {
3379            self.thread.update(cx, |thread, cx| {
3380                if let Some(configured) = thread.get_or_init_configured_model(cx) {
3381                    thread.run_tool(
3382                        c.tool_use_id.clone(),
3383                        c.ui_text.clone(),
3384                        c.input.clone(),
3385                        c.request.clone(),
3386                        c.tool.clone(),
3387                        configured.model,
3388                        Some(window.window_handle()),
3389                        cx,
3390                    );
3391                }
3392            });
3393        }
3394    }
3395
3396    fn handle_deny_tool(
3397        &mut self,
3398        tool_use_id: LanguageModelToolUseId,
3399        tool_name: Arc<str>,
3400        _: &ClickEvent,
3401        window: &mut Window,
3402        cx: &mut Context<Self>,
3403    ) {
3404        let window_handle = window.window_handle();
3405        self.thread.update(cx, |thread, cx| {
3406            thread.deny_tool_use(tool_use_id, tool_name, Some(window_handle), cx);
3407        });
3408    }
3409
3410    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3411        let project_context = self.thread.read(cx).project_context();
3412        let project_context = project_context.borrow();
3413        let Some(project_context) = project_context.as_ref() else {
3414            return;
3415        };
3416
3417        let project_entry_ids = project_context
3418            .worktrees
3419            .iter()
3420            .flat_map(|worktree| worktree.rules_file.as_ref())
3421            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
3422            .collect::<Vec<_>>();
3423
3424        self.workspace
3425            .update(cx, move |workspace, cx| {
3426                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3427                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3428                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3429                let project = workspace.project().read(cx);
3430                let project_paths = project_entry_ids
3431                    .into_iter()
3432                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
3433                    .collect::<Vec<_>>();
3434                for project_path in project_paths {
3435                    workspace
3436                        .open_path(project_path, None, true, window, cx)
3437                        .detach_and_log_err(cx);
3438                }
3439            })
3440            .ok();
3441    }
3442
3443    fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3444        for window in self.notifications.drain(..) {
3445            window
3446                .update(cx, |_, window, _| {
3447                    window.remove_window();
3448                })
3449                .ok();
3450
3451            self.notification_subscriptions.remove(&window);
3452        }
3453    }
3454
3455    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3456        if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3457            return None;
3458        }
3459
3460        Some(
3461            div()
3462                .occlude()
3463                .id("active-thread-scrollbar")
3464                .on_mouse_move(cx.listener(|_, _, _, cx| {
3465                    cx.notify();
3466                    cx.stop_propagation()
3467                }))
3468                .on_hover(|_, _, cx| {
3469                    cx.stop_propagation();
3470                })
3471                .on_any_mouse_down(|_, _, cx| {
3472                    cx.stop_propagation();
3473                })
3474                .on_mouse_up(
3475                    MouseButton::Left,
3476                    cx.listener(|_, _, _, cx| {
3477                        cx.stop_propagation();
3478                    }),
3479                )
3480                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3481                    cx.notify();
3482                }))
3483                .h_full()
3484                .absolute()
3485                .right_1()
3486                .top_1()
3487                .bottom_0()
3488                .w(px(12.))
3489                .cursor_default()
3490                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3491        )
3492    }
3493
3494    fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3495        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3496        self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3497            cx.background_executor()
3498                .timer(SCROLLBAR_SHOW_INTERVAL)
3499                .await;
3500            thread
3501                .update(cx, |thread, cx| {
3502                    if !thread.scrollbar_state.is_dragging() {
3503                        thread.show_scrollbar = false;
3504                        cx.notify();
3505                    }
3506                })
3507                .log_err();
3508        }))
3509    }
3510
3511    pub fn is_codeblock_expanded(&self, message_id: MessageId, ix: usize) -> bool {
3512        self.expanded_code_blocks
3513            .get(&(message_id, ix))
3514            .copied()
3515            .unwrap_or(true)
3516    }
3517
3518    pub fn toggle_codeblock_expanded(&mut self, message_id: MessageId, ix: usize) {
3519        let is_expanded = self
3520            .expanded_code_blocks
3521            .entry((message_id, ix))
3522            .or_insert(true);
3523        *is_expanded = !*is_expanded;
3524    }
3525
3526    pub fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3527        self.list_state.scroll_to(ListOffset::default());
3528        cx.notify();
3529    }
3530
3531    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3532        self.list_state.reset(self.messages.len());
3533        cx.notify();
3534    }
3535}
3536
3537pub enum ActiveThreadEvent {
3538    EditingMessageTokenCountChanged,
3539}
3540
3541impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3542
3543impl Render for ActiveThread {
3544    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3545        v_flex()
3546            .size_full()
3547            .relative()
3548            .bg(cx.theme().colors().panel_background)
3549            .on_mouse_move(cx.listener(|this, _, _, cx| {
3550                this.show_scrollbar = true;
3551                this.hide_scrollbar_later(cx);
3552                cx.notify();
3553            }))
3554            .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3555                this.show_scrollbar = true;
3556                this.hide_scrollbar_later(cx);
3557                cx.notify();
3558            }))
3559            .on_mouse_up(
3560                MouseButton::Left,
3561                cx.listener(|this, _, _, cx| {
3562                    this.hide_scrollbar_later(cx);
3563                }),
3564            )
3565            .child(list(self.list_state.clone()).flex_grow())
3566            .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3567                this.child(scrollbar)
3568            })
3569    }
3570}
3571
3572pub(crate) fn open_active_thread_as_markdown(
3573    thread: Entity<Thread>,
3574    workspace: Entity<Workspace>,
3575    window: &mut Window,
3576    cx: &mut App,
3577) -> Task<anyhow::Result<()>> {
3578    let markdown_language_task = workspace
3579        .read(cx)
3580        .app_state()
3581        .languages
3582        .language_for_name("Markdown");
3583
3584    window.spawn(cx, async move |cx| {
3585        let markdown_language = markdown_language_task.await?;
3586
3587        workspace.update_in(cx, |workspace, window, cx| {
3588            let thread = thread.read(cx);
3589            let markdown = thread.to_markdown(cx)?;
3590            let thread_summary = thread.summary().or_default().to_string();
3591
3592            let project = workspace.project().clone();
3593
3594            if !project.read(cx).is_local() {
3595                anyhow::bail!("failed to open active thread as markdown in remote project");
3596            }
3597
3598            let buffer = project.update(cx, |project, cx| {
3599                project.create_local_buffer(&markdown, Some(markdown_language), cx)
3600            });
3601            let buffer =
3602                cx.new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone()));
3603
3604            workspace.add_item_to_active_pane(
3605                Box::new(cx.new(|cx| {
3606                    let mut editor =
3607                        Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3608                    editor.set_breadcrumb_header(thread_summary);
3609                    editor
3610                })),
3611                None,
3612                true,
3613                window,
3614                cx,
3615            );
3616
3617            anyhow::Ok(())
3618        })??;
3619        anyhow::Ok(())
3620    })
3621}
3622
3623pub(crate) fn open_context(
3624    context: &AgentContextHandle,
3625    workspace: Entity<Workspace>,
3626    window: &mut Window,
3627    cx: &mut App,
3628) {
3629    match context {
3630        AgentContextHandle::File(file_context) => {
3631            if let Some(project_path) = file_context.project_path(cx) {
3632                workspace.update(cx, |workspace, cx| {
3633                    workspace
3634                        .open_path(project_path, None, true, window, cx)
3635                        .detach_and_log_err(cx);
3636                });
3637            }
3638        }
3639
3640        AgentContextHandle::Directory(directory_context) => {
3641            let entry_id = directory_context.entry_id;
3642            workspace.update(cx, |workspace, cx| {
3643                workspace.project().update(cx, |_project, cx| {
3644                    cx.emit(project::Event::RevealInProjectPanel(entry_id));
3645                })
3646            })
3647        }
3648
3649        AgentContextHandle::Symbol(symbol_context) => {
3650            let buffer = symbol_context.buffer.read(cx);
3651            if let Some(project_path) = buffer.project_path(cx) {
3652                let snapshot = buffer.snapshot();
3653                let target_position = symbol_context.range.start.to_point(&snapshot);
3654                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3655                    .detach();
3656            }
3657        }
3658
3659        AgentContextHandle::Selection(selection_context) => {
3660            let buffer = selection_context.buffer.read(cx);
3661            if let Some(project_path) = buffer.project_path(cx) {
3662                let snapshot = buffer.snapshot();
3663                let target_position = selection_context.range.start.to_point(&snapshot);
3664
3665                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3666                    .detach();
3667            }
3668        }
3669
3670        AgentContextHandle::FetchedUrl(fetched_url_context) => {
3671            cx.open_url(&fetched_url_context.url);
3672        }
3673
3674        AgentContextHandle::Thread(thread_context) => workspace.update(cx, |workspace, cx| {
3675            if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3676                panel.update(cx, |panel, cx| {
3677                    panel.open_thread(thread_context.thread.clone(), window, cx);
3678                });
3679            }
3680        }),
3681
3682        AgentContextHandle::TextThread(text_thread_context) => {
3683            workspace.update(cx, |workspace, cx| {
3684                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3685                    panel.update(cx, |panel, cx| {
3686                        panel.open_prompt_editor(text_thread_context.context.clone(), window, cx)
3687                    });
3688                }
3689            })
3690        }
3691
3692        AgentContextHandle::Rules(rules_context) => window.dispatch_action(
3693            Box::new(OpenRulesLibrary {
3694                prompt_to_select: Some(rules_context.prompt_id.0),
3695            }),
3696            cx,
3697        ),
3698
3699        AgentContextHandle::Image(_) => {}
3700    }
3701}
3702
3703pub(crate) fn attach_pasted_images_as_context(
3704    context_store: &Entity<ContextStore>,
3705    cx: &mut App,
3706) -> bool {
3707    let images = cx
3708        .read_from_clipboard()
3709        .map(|item| {
3710            item.into_entries()
3711                .filter_map(|entry| {
3712                    if let ClipboardEntry::Image(image) = entry {
3713                        Some(image)
3714                    } else {
3715                        None
3716                    }
3717                })
3718                .collect::<Vec<_>>()
3719        })
3720        .unwrap_or_default();
3721
3722    if images.is_empty() {
3723        return false;
3724    }
3725    cx.stop_propagation();
3726
3727    context_store.update(cx, |store, cx| {
3728        for image in images {
3729            store.add_image_instance(Arc::new(image), cx);
3730        }
3731    });
3732    true
3733}
3734
3735fn open_editor_at_position(
3736    project_path: project::ProjectPath,
3737    target_position: Point,
3738    workspace: &Entity<Workspace>,
3739    window: &mut Window,
3740    cx: &mut App,
3741) -> Task<()> {
3742    let open_task = workspace.update(cx, |workspace, cx| {
3743        workspace.open_path(project_path, None, true, window, cx)
3744    });
3745    window.spawn(cx, async move |cx| {
3746        if let Some(active_editor) = open_task
3747            .await
3748            .log_err()
3749            .and_then(|item| item.downcast::<Editor>())
3750        {
3751            active_editor
3752                .downgrade()
3753                .update_in(cx, |editor, window, cx| {
3754                    editor.go_to_singleton_buffer_point(target_position, window, cx);
3755                })
3756                .log_err();
3757        }
3758    })
3759}
3760
3761#[cfg(test)]
3762mod tests {
3763    use super::*;
3764    use agent::{MessageSegment, context::ContextLoadResult, thread_store};
3765    use assistant_tool::{ToolRegistry, ToolWorkingSet};
3766    use editor::EditorSettings;
3767    use fs::FakeFs;
3768    use gpui::{AppContext, TestAppContext, VisualTestContext};
3769    use language_model::{
3770        ConfiguredModel, LanguageModel, LanguageModelRegistry,
3771        fake_provider::{FakeLanguageModel, FakeLanguageModelProvider},
3772    };
3773    use project::Project;
3774    use prompt_store::PromptBuilder;
3775    use serde_json::json;
3776    use settings::SettingsStore;
3777    use util::path;
3778    use workspace::CollaboratorId;
3779
3780    #[gpui::test]
3781    async fn test_agent_is_unfollowed_after_cancelling_completion(cx: &mut TestAppContext) {
3782        init_test_settings(cx);
3783
3784        let project = create_test_project(
3785            cx,
3786            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3787        )
3788        .await;
3789
3790        let (cx, _active_thread, workspace, thread, model) =
3791            setup_test_environment(cx, project.clone()).await;
3792
3793        // Insert user message without any context (empty context vector)
3794        thread.update(cx, |thread, cx| {
3795            thread.insert_user_message(
3796                "What is the best way to learn Rust?",
3797                ContextLoadResult::default(),
3798                None,
3799                vec![],
3800                cx,
3801            );
3802        });
3803
3804        // Stream response to user message
3805        thread.update(cx, |thread, cx| {
3806            let intent = CompletionIntent::UserPrompt;
3807            let request = thread.to_completion_request(model.clone(), intent, cx);
3808            thread.stream_completion(request, model, intent, cx.active_window(), cx)
3809        });
3810        // Follow the agent
3811        cx.update(|window, cx| {
3812            workspace.update(cx, |workspace, cx| {
3813                workspace.follow(CollaboratorId::Agent, window, cx);
3814            })
3815        });
3816        assert!(cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3817
3818        // Cancel the current completion
3819        thread.update(cx, |thread, cx| {
3820            thread.cancel_last_completion(cx.active_window(), cx)
3821        });
3822
3823        cx.executor().run_until_parked();
3824
3825        // No longer following the agent
3826        assert!(!cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3827    }
3828
3829    #[gpui::test]
3830    async fn test_reinserting_creases_for_edited_message(cx: &mut TestAppContext) {
3831        init_test_settings(cx);
3832
3833        let project = create_test_project(cx, json!({})).await;
3834
3835        let (cx, active_thread, _, thread, model) =
3836            setup_test_environment(cx, project.clone()).await;
3837        cx.update(|_, cx| {
3838            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3839                registry.set_default_model(
3840                    Some(ConfiguredModel {
3841                        provider: Arc::new(FakeLanguageModelProvider),
3842                        model,
3843                    }),
3844                    cx,
3845                );
3846            });
3847        });
3848
3849        let creases = vec![MessageCrease {
3850            range: 14..22,
3851            icon_path: "icon".into(),
3852            label: "foo.txt".into(),
3853            context: None,
3854        }];
3855
3856        let message = thread.update(cx, |thread, cx| {
3857            let message_id = thread.insert_user_message(
3858                "Tell me about @foo.txt",
3859                ContextLoadResult::default(),
3860                None,
3861                creases,
3862                cx,
3863            );
3864            thread.message(message_id).cloned().unwrap()
3865        });
3866
3867        active_thread.update_in(cx, |active_thread, window, cx| {
3868            if let Some(message_text) = message.segments.first().and_then(MessageSegment::text) {
3869                active_thread.start_editing_message(
3870                    message.id,
3871                    message_text,
3872                    message.creases.as_slice(),
3873                    window,
3874                    cx,
3875                );
3876            }
3877            let editor = active_thread
3878                .editing_message
3879                .as_ref()
3880                .unwrap()
3881                .1
3882                .editor
3883                .clone();
3884            editor.update(cx, |editor, cx| editor.edit([(0..13, "modified")], cx));
3885            active_thread.confirm_editing_message(&Default::default(), window, cx);
3886        });
3887        cx.run_until_parked();
3888
3889        let message = thread.update(cx, |thread, _| thread.message(message.id).cloned().unwrap());
3890        active_thread.update_in(cx, |active_thread, window, cx| {
3891            if let Some(message_text) = message.segments.first().and_then(MessageSegment::text) {
3892                active_thread.start_editing_message(
3893                    message.id,
3894                    message_text,
3895                    message.creases.as_slice(),
3896                    window,
3897                    cx,
3898                );
3899            }
3900            let editor = active_thread
3901                .editing_message
3902                .as_ref()
3903                .unwrap()
3904                .1
3905                .editor
3906                .clone();
3907            let text = editor.update(cx, |editor, cx| editor.text(cx));
3908            assert_eq!(text, "modified @foo.txt");
3909        });
3910    }
3911
3912    #[gpui::test]
3913    async fn test_editing_message_cancels_previous_completion(cx: &mut TestAppContext) {
3914        init_test_settings(cx);
3915
3916        let project = create_test_project(cx, json!({})).await;
3917
3918        let (cx, active_thread, _, thread, model) =
3919            setup_test_environment(cx, project.clone()).await;
3920
3921        cx.update(|_, cx| {
3922            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3923                registry.set_default_model(
3924                    Some(ConfiguredModel {
3925                        provider: Arc::new(FakeLanguageModelProvider),
3926                        model: model.clone(),
3927                    }),
3928                    cx,
3929                );
3930            });
3931        });
3932
3933        // Track thread events to verify cancellation
3934        let cancellation_events = Arc::new(std::sync::Mutex::new(Vec::new()));
3935        let new_request_events = Arc::new(std::sync::Mutex::new(Vec::new()));
3936
3937        let _subscription = cx.update(|_, cx| {
3938            let cancellation_events = cancellation_events.clone();
3939            let new_request_events = new_request_events.clone();
3940            cx.subscribe(
3941                &thread,
3942                move |_thread, event: &ThreadEvent, _cx| match event {
3943                    ThreadEvent::CompletionCanceled => {
3944                        cancellation_events.lock().unwrap().push(());
3945                    }
3946                    ThreadEvent::NewRequest => {
3947                        new_request_events.lock().unwrap().push(());
3948                    }
3949                    _ => {}
3950                },
3951            )
3952        });
3953
3954        // Insert a user message and start streaming a response
3955        let message = thread.update(cx, |thread, cx| {
3956            let message_id = thread.insert_user_message(
3957                "Hello, how are you?",
3958                ContextLoadResult::default(),
3959                None,
3960                vec![],
3961                cx,
3962            );
3963            thread.advance_prompt_id();
3964            thread.send_to_model(
3965                model.clone(),
3966                CompletionIntent::UserPrompt,
3967                cx.active_window(),
3968                cx,
3969            );
3970            thread.message(message_id).cloned().unwrap()
3971        });
3972
3973        cx.run_until_parked();
3974
3975        // Verify that a completion is in progress
3976        assert!(cx.read(|cx| thread.read(cx).is_generating()));
3977        assert_eq!(new_request_events.lock().unwrap().len(), 1);
3978
3979        // Edit the message while the completion is still running
3980        active_thread.update_in(cx, |active_thread, window, cx| {
3981            if let Some(message_text) = message.segments.first().and_then(MessageSegment::text) {
3982                active_thread.start_editing_message(
3983                    message.id,
3984                    message_text,
3985                    message.creases.as_slice(),
3986                    window,
3987                    cx,
3988                );
3989            }
3990            let editor = active_thread
3991                .editing_message
3992                .as_ref()
3993                .unwrap()
3994                .1
3995                .editor
3996                .clone();
3997            editor.update(cx, |editor, cx| {
3998                editor.set_text("What is the weather like?", window, cx);
3999            });
4000            active_thread.confirm_editing_message(&Default::default(), window, cx);
4001        });
4002
4003        cx.run_until_parked();
4004
4005        // Verify that the previous completion was cancelled
4006        assert_eq!(cancellation_events.lock().unwrap().len(), 1);
4007
4008        // Verify that a new request was started after cancellation
4009        assert_eq!(new_request_events.lock().unwrap().len(), 2);
4010
4011        // Verify that the edited message contains the new text
4012        let edited_message =
4013            thread.update(cx, |thread, _| thread.message(message.id).cloned().unwrap());
4014        match &edited_message.segments[0] {
4015            MessageSegment::Text(text) => {
4016                assert_eq!(text, "What is the weather like?");
4017            }
4018            _ => panic!("Expected text segment"),
4019        }
4020    }
4021
4022    fn init_test_settings(cx: &mut TestAppContext) {
4023        cx.update(|cx| {
4024            let settings_store = SettingsStore::test(cx);
4025            cx.set_global(settings_store);
4026            language::init(cx);
4027            Project::init_settings(cx);
4028            AgentSettings::register(cx);
4029            prompt_store::init(cx);
4030            thread_store::init(cx);
4031            workspace::init_settings(cx);
4032            language_model::init_settings(cx);
4033            ThemeSettings::register(cx);
4034            EditorSettings::register(cx);
4035            ToolRegistry::default_global(cx);
4036        });
4037    }
4038
4039    // Helper to create a test project with test files
4040    async fn create_test_project(
4041        cx: &mut TestAppContext,
4042        files: serde_json::Value,
4043    ) -> Entity<Project> {
4044        let fs = FakeFs::new(cx.executor());
4045        fs.insert_tree(path!("/test"), files).await;
4046        Project::test(fs, [path!("/test").as_ref()], cx).await
4047    }
4048
4049    async fn setup_test_environment(
4050        cx: &mut TestAppContext,
4051        project: Entity<Project>,
4052    ) -> (
4053        &mut VisualTestContext,
4054        Entity<ActiveThread>,
4055        Entity<Workspace>,
4056        Entity<Thread>,
4057        Arc<dyn LanguageModel>,
4058    ) {
4059        let (workspace, cx) =
4060            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4061
4062        let thread_store = cx
4063            .update(|_, cx| {
4064                ThreadStore::load(
4065                    project.clone(),
4066                    cx.new(|_| ToolWorkingSet::default()),
4067                    None,
4068                    Arc::new(PromptBuilder::new(None).unwrap()),
4069                    cx,
4070                )
4071            })
4072            .await
4073            .unwrap();
4074
4075        let text_thread_store = cx
4076            .update(|_, cx| {
4077                TextThreadStore::new(
4078                    project.clone(),
4079                    Arc::new(PromptBuilder::new(None).unwrap()),
4080                    Default::default(),
4081                    cx,
4082                )
4083            })
4084            .await
4085            .unwrap();
4086
4087        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
4088        let context_store =
4089            cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
4090
4091        let model = FakeLanguageModel::default();
4092        let model: Arc<dyn LanguageModel> = Arc::new(model);
4093
4094        let language_registry = LanguageRegistry::new(cx.executor());
4095        let language_registry = Arc::new(language_registry);
4096
4097        let active_thread = cx.update(|window, cx| {
4098            cx.new(|cx| {
4099                ActiveThread::new(
4100                    thread.clone(),
4101                    thread_store.clone(),
4102                    text_thread_store,
4103                    context_store.clone(),
4104                    language_registry.clone(),
4105                    workspace.downgrade(),
4106                    window,
4107                    cx,
4108                )
4109            })
4110        });
4111
4112        (cx, active_thread, workspace, thread, model)
4113    }
4114}