active_thread.rs

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