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, ListOffset, 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, KeyBinding, PopoverMenuHandle, Scrollbar, ScrollbarState, TextSize, Tooltip,
  52    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        let scroll_to_top = IconButton::new(("scroll_to_top", ix), IconName::ArrowUpAlt)
1877            .icon_size(IconSize::XSmall)
1878            .icon_color(Color::Ignored)
1879            .tooltip(Tooltip::text("Scroll To Top"))
1880            .on_click(cx.listener(move |this, _, _, cx| {
1881                this.scroll_to_top(cx);
1882            }));
1883
1884        // For all items that should be aligned with the LLM's response.
1885        const RESPONSE_PADDING_X: Pixels = px(19.);
1886
1887        let show_feedback = thread.is_turn_end(ix);
1888        let feedback_container = h_flex()
1889            .group("feedback_container")
1890            .mt_1()
1891            .py_2()
1892            .px(RESPONSE_PADDING_X)
1893            .mr_1()
1894            .opacity(0.4)
1895            .hover(|style| style.opacity(1.))
1896            .gap_1p5()
1897            .flex_wrap()
1898            .justify_end();
1899        let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1900            Some(feedback) => feedback_container
1901                .child(
1902                    div().visible_on_hover("feedback_container").child(
1903                        Label::new(match feedback {
1904                            ThreadFeedback::Positive => "Thanks for your feedback!",
1905                            ThreadFeedback::Negative => {
1906                                "We appreciate your feedback and will use it to improve."
1907                            }
1908                        })
1909                    .color(Color::Muted)
1910                    .size(LabelSize::XSmall)
1911                    .truncate())
1912                )
1913                .child(
1914                    h_flex()
1915                        .child(
1916                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1917                                .icon_size(IconSize::XSmall)
1918                                .icon_color(match feedback {
1919                                    ThreadFeedback::Positive => Color::Accent,
1920                                    ThreadFeedback::Negative => Color::Ignored,
1921                                })
1922                                .tooltip(Tooltip::text("Helpful Response"))
1923                                .on_click(cx.listener(move |this, _, window, cx| {
1924                                    this.handle_feedback_click(
1925                                        message_id,
1926                                        ThreadFeedback::Positive,
1927                                        window,
1928                                        cx,
1929                                    );
1930                                })),
1931                        )
1932                        .child(
1933                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1934                                .icon_size(IconSize::XSmall)
1935                                .icon_color(match feedback {
1936                                    ThreadFeedback::Positive => Color::Ignored,
1937                                    ThreadFeedback::Negative => Color::Accent,
1938                                })
1939                                .tooltip(Tooltip::text("Not Helpful"))
1940                                .on_click(cx.listener(move |this, _, window, cx| {
1941                                    this.handle_feedback_click(
1942                                        message_id,
1943                                        ThreadFeedback::Negative,
1944                                        window,
1945                                        cx,
1946                                    );
1947                                })),
1948                        )
1949                        .child(open_as_markdown),
1950                )
1951                .into_any_element(),
1952            None if AgentSettings::get_global(cx).enable_feedback =>
1953                feedback_container
1954                .child(
1955                    div().visible_on_hover("feedback_container").child(
1956                        Label::new(
1957                            "Rating the thread sends all of your current conversation to the Zed team.",
1958                        )
1959                        .color(Color::Muted)
1960                    .size(LabelSize::XSmall)
1961                    .truncate())
1962                )
1963                .child(
1964                    h_flex()
1965                        .child(
1966                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1967                                .icon_size(IconSize::XSmall)
1968                                .icon_color(Color::Ignored)
1969                                .tooltip(Tooltip::text("Helpful Response"))
1970                                .on_click(cx.listener(move |this, _, window, cx| {
1971                                    this.handle_feedback_click(
1972                                        message_id,
1973                                        ThreadFeedback::Positive,
1974                                        window,
1975                                        cx,
1976                                    );
1977                                })),
1978                        )
1979                        .child(
1980                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1981                                .icon_size(IconSize::XSmall)
1982                                .icon_color(Color::Ignored)
1983                                .tooltip(Tooltip::text("Not Helpful"))
1984                                .on_click(cx.listener(move |this, _, window, cx| {
1985                                    this.handle_feedback_click(
1986                                        message_id,
1987                                        ThreadFeedback::Negative,
1988                                        window,
1989                                        cx,
1990                                    );
1991                                })),
1992                        )
1993                        .child(open_as_markdown)
1994                        .child(scroll_to_top),
1995                )
1996                .into_any_element(),
1997            None => feedback_container
1998                .child(h_flex()
1999                    .child(open_as_markdown))
2000                    .child(scroll_to_top)
2001                .into_any_element(),
2002        };
2003
2004        let message_is_empty = message.should_display_content();
2005        let has_content = !message_is_empty || !added_context.is_empty();
2006
2007        let message_content = has_content.then(|| {
2008            if let Some(state) = editing_message_state.as_ref() {
2009                self.render_edit_message_editor(state, window, cx)
2010                    .into_any_element()
2011            } else {
2012                v_flex()
2013                    .w_full()
2014                    .gap_1()
2015                    .when(!added_context.is_empty(), |parent| {
2016                        parent.child(h_flex().flex_wrap().gap_1().children(
2017                            added_context.into_iter().map(|added_context| {
2018                                let context = added_context.handle.clone();
2019                                ContextPill::added(added_context, false, false, None).on_click(
2020                                    Rc::new(cx.listener({
2021                                        let workspace = workspace.clone();
2022                                        move |_, _, window, cx| {
2023                                            if let Some(workspace) = workspace.upgrade() {
2024                                                open_context(&context, workspace, window, cx);
2025                                                cx.notify();
2026                                            }
2027                                        }
2028                                    })),
2029                                )
2030                            }),
2031                        ))
2032                    })
2033                    .when(!message_is_empty, |parent| {
2034                        parent.child(div().pt_0p5().min_h_6().child(self.render_message_content(
2035                            message_id,
2036                            rendered_message,
2037                            has_tool_uses,
2038                            workspace.clone(),
2039                            window,
2040                            cx,
2041                        )))
2042                    })
2043                    .into_any_element()
2044            }
2045        });
2046
2047        let styled_message = match message.role {
2048            Role::User => v_flex()
2049                .id(("message-container", ix))
2050                .pt_2()
2051                .pl_2()
2052                .pr_2p5()
2053                .pb_4()
2054                .child(
2055                    v_flex()
2056                        .id(("user-message", ix))
2057                        .bg(editor_bg_color)
2058                        .rounded_lg()
2059                        .shadow_md()
2060                        .border_1()
2061                        .border_color(colors.border)
2062                        .hover(|hover| hover.border_color(colors.text_accent.opacity(0.5)))
2063                        .child(
2064                            v_flex()
2065                                .p_2p5()
2066                                .gap_1()
2067                                .children(message_content)
2068                                .when_some(editing_message_state, |this, state| {
2069                                    let focus_handle = state.editor.focus_handle(cx).clone();
2070
2071                                    this.child(
2072                                        h_flex()
2073                                            .w_full()
2074                                            .gap_1()
2075                                            .justify_between()
2076                                            .flex_wrap()
2077                                            .child(
2078                                                h_flex()
2079                                                    .gap_1p5()
2080                                                    .child(
2081                                                        div()
2082                                                            .opacity(0.8)
2083                                                            .child(
2084                                                                Icon::new(IconName::Warning)
2085                                                                    .size(IconSize::Indicator)
2086                                                                    .color(Color::Warning)
2087                                                            ),
2088                                                    )
2089                                                    .child(
2090                                                        Label::new("Editing will restart the thread from this point.")
2091                                                            .color(Color::Muted)
2092                                                            .size(LabelSize::XSmall),
2093                                                    ),
2094                                            )
2095                                            .child(
2096                                                h_flex()
2097                                                    .gap_0p5()
2098                                                    .child(
2099                                                        IconButton::new(
2100                                                            "cancel-edit-message",
2101                                                            IconName::Close,
2102                                                        )
2103                                                        .shape(ui::IconButtonShape::Square)
2104                                                        .icon_color(Color::Error)
2105                                                        .icon_size(IconSize::Small)
2106                                                        .tooltip({
2107                                                            let focus_handle = focus_handle.clone();
2108                                                            move |window, cx| {
2109                                                                Tooltip::for_action_in(
2110                                                                    "Cancel Edit",
2111                                                                    &menu::Cancel,
2112                                                                    &focus_handle,
2113                                                                    window,
2114                                                                    cx,
2115                                                                )
2116                                                            }
2117                                                        })
2118                                                        .on_click(cx.listener(Self::handle_cancel_click)),
2119                                                    )
2120                                                    .child(
2121                                                        IconButton::new(
2122                                                            "confirm-edit-message",
2123                                                            IconName::Return,
2124                                                        )
2125                                                        .disabled(state.editor.read(cx).is_empty(cx))
2126                                                        .shape(ui::IconButtonShape::Square)
2127                                                        .icon_color(Color::Muted)
2128                                                        .icon_size(IconSize::Small)
2129                                                        .tooltip({
2130                                                            let focus_handle = focus_handle.clone();
2131                                                            move |window, cx| {
2132                                                                Tooltip::for_action_in(
2133                                                                    "Regenerate",
2134                                                                    &menu::Confirm,
2135                                                                    &focus_handle,
2136                                                                    window,
2137                                                                    cx,
2138                                                                )
2139                                                            }
2140                                                        })
2141                                                        .on_click(
2142                                                            cx.listener(Self::handle_regenerate_click),
2143                                                        ),
2144                                                    ),
2145                                            )
2146                                    )
2147                                }),
2148                        )
2149                        .on_click(cx.listener({
2150                            let message_segments = message.segments.clone();
2151                            move |this, _, window, cx| {
2152                                this.start_editing_message(
2153                                    message_id,
2154                                    &message_segments,
2155                                    &message_creases,
2156                                    window,
2157                                    cx,
2158                                );
2159                            }
2160                        })),
2161                ),
2162            Role::Assistant => v_flex()
2163                .id(("message-container", ix))
2164                .px(RESPONSE_PADDING_X)
2165                .gap_2()
2166                .children(message_content)
2167                .when(has_tool_uses, |parent| {
2168                    parent.children(tool_uses.into_iter().map(|tool_use| {
2169                        self.render_tool_use(tool_use, window, workspace.clone(), cx)
2170                    }))
2171                }),
2172            Role::System => div().id(("message-container", ix)).py_1().px_2().child(
2173                v_flex()
2174                    .bg(colors.editor_background)
2175                    .rounded_sm()
2176                    .child(div().p_4().children(message_content)),
2177            ),
2178        };
2179
2180        let after_editing_message = self
2181            .editing_message
2182            .as_ref()
2183            .map_or(false, |(editing_message_id, _)| {
2184                message_id > *editing_message_id
2185            });
2186
2187        let backdrop = div()
2188            .id(("backdrop", ix))
2189            .size_full()
2190            .absolute()
2191            .inset_0()
2192            .bg(panel_bg)
2193            .opacity(0.8)
2194            .block_mouse_except_scroll()
2195            .on_click(cx.listener(Self::handle_cancel_click));
2196
2197        v_flex()
2198            .w_full()
2199            .map(|parent| {
2200                if let Some(checkpoint) = checkpoint.filter(|_| !is_generating) {
2201                    let mut is_pending = false;
2202                    let mut error = None;
2203                    if let Some(last_restore_checkpoint) =
2204                        self.thread.read(cx).last_restore_checkpoint()
2205                    {
2206                        if last_restore_checkpoint.message_id() == message_id {
2207                            match last_restore_checkpoint {
2208                                LastRestoreCheckpoint::Pending { .. } => is_pending = true,
2209                                LastRestoreCheckpoint::Error { error: err, .. } => {
2210                                    error = Some(err.clone());
2211                                }
2212                            }
2213                        }
2214                    }
2215
2216                    let restore_checkpoint_button =
2217                        Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
2218                            .icon(if error.is_some() {
2219                                IconName::XCircle
2220                            } else {
2221                                IconName::Undo
2222                            })
2223                            .icon_size(IconSize::XSmall)
2224                            .icon_position(IconPosition::Start)
2225                            .icon_color(if error.is_some() {
2226                                Some(Color::Error)
2227                            } else {
2228                                None
2229                            })
2230                            .label_size(LabelSize::XSmall)
2231                            .disabled(is_pending)
2232                            .on_click(cx.listener(move |this, _, _window, cx| {
2233                                this.thread.update(cx, |thread, cx| {
2234                                    thread
2235                                        .restore_checkpoint(checkpoint.clone(), cx)
2236                                        .detach_and_log_err(cx);
2237                                });
2238                            }));
2239
2240                    let restore_checkpoint_button = if is_pending {
2241                        restore_checkpoint_button
2242                            .with_animation(
2243                                ("pulsating-restore-checkpoint-button", ix),
2244                                Animation::new(Duration::from_secs(2))
2245                                    .repeat()
2246                                    .with_easing(pulsating_between(0.6, 1.)),
2247                                |label, delta| label.alpha(delta),
2248                            )
2249                            .into_any_element()
2250                    } else if let Some(error) = error {
2251                        restore_checkpoint_button
2252                            .tooltip(Tooltip::text(error.to_string()))
2253                            .into_any_element()
2254                    } else {
2255                        restore_checkpoint_button.into_any_element()
2256                    };
2257
2258                    parent.child(
2259                        h_flex()
2260                            .pt_2p5()
2261                            .px_2p5()
2262                            .w_full()
2263                            .gap_1()
2264                            .child(ui::Divider::horizontal())
2265                            .child(restore_checkpoint_button)
2266                            .child(ui::Divider::horizontal()),
2267                    )
2268                } else {
2269                    parent
2270                }
2271            })
2272            .when(is_first_message, |parent| {
2273                parent.child(self.render_rules_item(cx))
2274            })
2275            .child(styled_message)
2276            .children(loading_dots)
2277            .when(show_feedback, move |parent| {
2278                parent.child(feedback_items).when_some(
2279                    self.open_feedback_editors.get(&message_id),
2280                    move |parent, feedback_editor| {
2281                        let focus_handle = feedback_editor.focus_handle(cx);
2282                        parent.child(
2283                            v_flex()
2284                                .key_context("AgentFeedbackMessageEditor")
2285                                .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2286                                    this.open_feedback_editors.remove(&message_id);
2287                                    cx.notify();
2288                                }))
2289                                .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2290                                    this.submit_feedback_message(message_id, cx);
2291                                    cx.notify();
2292                                }))
2293                                .on_action(cx.listener(Self::confirm_editing_message))
2294                                .mb_2()
2295                                .mx_4()
2296                                .p_2()
2297                                .rounded_md()
2298                                .border_1()
2299                                .border_color(cx.theme().colors().border)
2300                                .bg(cx.theme().colors().editor_background)
2301                                .child(feedback_editor.clone())
2302                                .child(
2303                                    h_flex()
2304                                        .gap_1()
2305                                        .justify_end()
2306                                        .child(
2307                                            Button::new("dismiss-feedback-message", "Cancel")
2308                                                .label_size(LabelSize::Small)
2309                                                .key_binding(
2310                                                    KeyBinding::for_action_in(
2311                                                        &menu::Cancel,
2312                                                        &focus_handle,
2313                                                        window,
2314                                                        cx,
2315                                                    )
2316                                                    .map(|kb| kb.size(rems_from_px(10.))),
2317                                                )
2318                                                .on_click(cx.listener(
2319                                                    move |this, _, _window, cx| {
2320                                                        this.open_feedback_editors
2321                                                            .remove(&message_id);
2322                                                        cx.notify();
2323                                                    },
2324                                                )),
2325                                        )
2326                                        .child(
2327                                            Button::new(
2328                                                "submit-feedback-message",
2329                                                "Share Feedback",
2330                                            )
2331                                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2332                                            .label_size(LabelSize::Small)
2333                                            .key_binding(
2334                                                KeyBinding::for_action_in(
2335                                                    &menu::Confirm,
2336                                                    &focus_handle,
2337                                                    window,
2338                                                    cx,
2339                                                )
2340                                                .map(|kb| kb.size(rems_from_px(10.))),
2341                                            )
2342                                            .on_click(
2343                                                cx.listener(move |this, _, _window, cx| {
2344                                                    this.submit_feedback_message(message_id, cx);
2345                                                    cx.notify()
2346                                                }),
2347                                            ),
2348                                        ),
2349                                ),
2350                        )
2351                    },
2352                )
2353            })
2354            .when(after_editing_message, |parent| {
2355                // Backdrop to dim out the whole thread below the editing user message
2356                parent.relative().child(backdrop)
2357            })
2358            .into_any()
2359    }
2360
2361    fn render_message_content(
2362        &self,
2363        message_id: MessageId,
2364        rendered_message: &RenderedMessage,
2365        has_tool_uses: bool,
2366        workspace: WeakEntity<Workspace>,
2367        window: &Window,
2368        cx: &Context<Self>,
2369    ) -> impl IntoElement {
2370        let is_last_message = self.messages.last() == Some(&message_id);
2371        let is_generating = self.thread.read(cx).is_generating();
2372        let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2373            rendered_message
2374                .segments
2375                .iter()
2376                .enumerate()
2377                .next_back()
2378                .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2379                .map(|(index, _)| index)
2380        } else {
2381            None
2382        };
2383
2384        let message_role = self
2385            .thread
2386            .read(cx)
2387            .message(message_id)
2388            .map(|m| m.role)
2389            .unwrap_or(Role::User);
2390
2391        let is_assistant_message = message_role == Role::Assistant;
2392        let is_user_message = message_role == Role::User;
2393
2394        v_flex()
2395            .text_ui(cx)
2396            .gap_2()
2397            .when(is_user_message, |this| this.text_xs())
2398            .children(
2399                rendered_message.segments.iter().enumerate().map(
2400                    |(index, segment)| match segment {
2401                        RenderedMessageSegment::Thinking {
2402                            content,
2403                            scroll_handle,
2404                        } => self
2405                            .render_message_thinking_segment(
2406                                message_id,
2407                                index,
2408                                content.clone(),
2409                                &scroll_handle,
2410                                Some(index) == pending_thinking_segment_index,
2411                                window,
2412                                cx,
2413                            )
2414                            .into_any_element(),
2415                        RenderedMessageSegment::Text(markdown) => {
2416                            let markdown_element = MarkdownElement::new(
2417                                markdown.clone(),
2418                                if is_user_message {
2419                                    let mut style = default_markdown_style(window, cx);
2420                                    let mut text_style = window.text_style();
2421                                    let theme_settings = ThemeSettings::get_global(cx);
2422
2423                                    let buffer_font = theme_settings.buffer_font.family.clone();
2424                                    let buffer_font_size = TextSize::Small.rems(cx);
2425
2426                                    text_style.refine(&TextStyleRefinement {
2427                                        font_family: Some(buffer_font),
2428                                        font_size: Some(buffer_font_size.into()),
2429                                        ..Default::default()
2430                                    });
2431
2432                                    style.base_text_style = text_style;
2433                                    style
2434                                } else {
2435                                    default_markdown_style(window, cx)
2436                                },
2437                            );
2438
2439                            let markdown_element = if is_assistant_message {
2440                                markdown_element.code_block_renderer(
2441                                    markdown::CodeBlockRenderer::Custom {
2442                                        render: Arc::new({
2443                                            let workspace = workspace.clone();
2444                                            let active_thread = cx.entity();
2445                                            move |kind,
2446                                                  parsed_markdown,
2447                                                  range,
2448                                                  metadata,
2449                                                  window,
2450                                                  cx| {
2451                                                render_markdown_code_block(
2452                                                    message_id,
2453                                                    range.start,
2454                                                    kind,
2455                                                    parsed_markdown,
2456                                                    metadata,
2457                                                    active_thread.clone(),
2458                                                    workspace.clone(),
2459                                                    window,
2460                                                    cx,
2461                                                )
2462                                            }
2463                                        }),
2464                                        transform: Some(Arc::new({
2465                                            let active_thread = cx.entity();
2466
2467                                            move |element, range, _, _, cx| {
2468                                                let is_expanded = active_thread
2469                                                    .read(cx)
2470                                                    .is_codeblock_expanded(message_id, range.start);
2471
2472                                                if is_expanded {
2473                                                    return element;
2474                                                }
2475
2476                                                element
2477                                            }
2478                                        })),
2479                                    },
2480                                )
2481                            } else {
2482                                markdown_element.code_block_renderer(
2483                                    markdown::CodeBlockRenderer::Default {
2484                                        copy_button: false,
2485                                        copy_button_on_hover: false,
2486                                        border: true,
2487                                    },
2488                                )
2489                            };
2490
2491                            div()
2492                                .child(markdown_element.on_url_click({
2493                                    let workspace = self.workspace.clone();
2494                                    move |text, window, cx| {
2495                                        open_markdown_link(text, workspace.clone(), window, cx);
2496                                    }
2497                                }))
2498                                .into_any_element()
2499                        }
2500                    },
2501                ),
2502            )
2503    }
2504
2505    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2506        cx.theme().colors().border.opacity(0.5)
2507    }
2508
2509    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2510        cx.theme()
2511            .colors()
2512            .element_background
2513            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2514    }
2515
2516    fn render_message_thinking_segment(
2517        &self,
2518        message_id: MessageId,
2519        ix: usize,
2520        markdown: Entity<Markdown>,
2521        scroll_handle: &ScrollHandle,
2522        pending: bool,
2523        window: &Window,
2524        cx: &Context<Self>,
2525    ) -> impl IntoElement {
2526        let is_open = self
2527            .expanded_thinking_segments
2528            .get(&(message_id, ix))
2529            .copied()
2530            .unwrap_or_default();
2531
2532        let editor_bg = cx.theme().colors().panel_background;
2533
2534        div().map(|this| {
2535            if pending {
2536                this.v_flex()
2537                    .mt_neg_2()
2538                    .mb_1p5()
2539                    .child(
2540                        h_flex()
2541                            .group("disclosure-header")
2542                            .justify_between()
2543                            .child(
2544                                h_flex()
2545                                    .gap_1p5()
2546                                    .child(
2547                                        Icon::new(IconName::LightBulb)
2548                                            .size(IconSize::XSmall)
2549                                            .color(Color::Muted),
2550                                    )
2551                                    .child(AnimatedLabel::new("Thinking").size(LabelSize::Small)),
2552                            )
2553                            .child(
2554                                h_flex()
2555                                    .gap_1()
2556                                    .child(
2557                                        div().visible_on_hover("disclosure-header").child(
2558                                            Disclosure::new("thinking-disclosure", is_open)
2559                                                .opened_icon(IconName::ChevronUp)
2560                                                .closed_icon(IconName::ChevronDown)
2561                                                .on_click(cx.listener({
2562                                                    move |this, _event, _window, _cx| {
2563                                                        let is_open = this
2564                                                            .expanded_thinking_segments
2565                                                            .entry((message_id, ix))
2566                                                            .or_insert(false);
2567
2568                                                        *is_open = !*is_open;
2569                                                    }
2570                                                })),
2571                                        ),
2572                                    )
2573                                    .child({
2574                                        Icon::new(IconName::ArrowCircle)
2575                                            .color(Color::Accent)
2576                                            .size(IconSize::Small)
2577                                            .with_animation(
2578                                                "arrow-circle",
2579                                                Animation::new(Duration::from_secs(2)).repeat(),
2580                                                |icon, delta| {
2581                                                    icon.transform(Transformation::rotate(
2582                                                        percentage(delta),
2583                                                    ))
2584                                                },
2585                                            )
2586                                    }),
2587                            ),
2588                    )
2589                    .when(!is_open, |this| {
2590                        let gradient_overlay = div()
2591                            .rounded_b_lg()
2592                            .h_full()
2593                            .absolute()
2594                            .w_full()
2595                            .bottom_0()
2596                            .left_0()
2597                            .bg(linear_gradient(
2598                                180.,
2599                                linear_color_stop(editor_bg, 1.),
2600                                linear_color_stop(editor_bg.opacity(0.2), 0.),
2601                            ));
2602
2603                        this.child(
2604                            div()
2605                                .relative()
2606                                .bg(editor_bg)
2607                                .rounded_b_lg()
2608                                .mt_2()
2609                                .pl_4()
2610                                .child(
2611                                    div()
2612                                        .id(("thinking-content", ix))
2613                                        .max_h_20()
2614                                        .track_scroll(scroll_handle)
2615                                        .text_ui_sm(cx)
2616                                        .overflow_hidden()
2617                                        .child(
2618                                            MarkdownElement::new(
2619                                                markdown.clone(),
2620                                                default_markdown_style(window, cx),
2621                                            )
2622                                            .on_url_click({
2623                                                let workspace = self.workspace.clone();
2624                                                move |text, window, cx| {
2625                                                    open_markdown_link(
2626                                                        text,
2627                                                        workspace.clone(),
2628                                                        window,
2629                                                        cx,
2630                                                    );
2631                                                }
2632                                            }),
2633                                        ),
2634                                )
2635                                .child(gradient_overlay),
2636                        )
2637                    })
2638                    .when(is_open, |this| {
2639                        this.child(
2640                            div()
2641                                .id(("thinking-content", ix))
2642                                .h_full()
2643                                .bg(editor_bg)
2644                                .text_ui_sm(cx)
2645                                .child(
2646                                    MarkdownElement::new(
2647                                        markdown.clone(),
2648                                        default_markdown_style(window, cx),
2649                                    )
2650                                    .on_url_click({
2651                                        let workspace = self.workspace.clone();
2652                                        move |text, window, cx| {
2653                                            open_markdown_link(text, workspace.clone(), window, cx);
2654                                        }
2655                                    }),
2656                                ),
2657                        )
2658                    })
2659            } else {
2660                this.v_flex()
2661                    .mt_neg_2()
2662                    .child(
2663                        h_flex()
2664                            .group("disclosure-header")
2665                            .pr_1()
2666                            .justify_between()
2667                            .opacity(0.8)
2668                            .hover(|style| style.opacity(1.))
2669                            .child(
2670                                h_flex()
2671                                    .gap_1p5()
2672                                    .child(
2673                                        Icon::new(IconName::LightBulb)
2674                                            .size(IconSize::XSmall)
2675                                            .color(Color::Muted),
2676                                    )
2677                                    .child(Label::new("Thought Process").size(LabelSize::Small)),
2678                            )
2679                            .child(
2680                                div().visible_on_hover("disclosure-header").child(
2681                                    Disclosure::new("thinking-disclosure", is_open)
2682                                        .opened_icon(IconName::ChevronUp)
2683                                        .closed_icon(IconName::ChevronDown)
2684                                        .on_click(cx.listener({
2685                                            move |this, _event, _window, _cx| {
2686                                                let is_open = this
2687                                                    .expanded_thinking_segments
2688                                                    .entry((message_id, ix))
2689                                                    .or_insert(false);
2690
2691                                                *is_open = !*is_open;
2692                                            }
2693                                        })),
2694                                ),
2695                            ),
2696                    )
2697                    .child(
2698                        div()
2699                            .id(("thinking-content", ix))
2700                            .relative()
2701                            .mt_1p5()
2702                            .ml_1p5()
2703                            .pl_2p5()
2704                            .border_l_1()
2705                            .border_color(cx.theme().colors().border_variant)
2706                            .text_ui_sm(cx)
2707                            .when(is_open, |this| {
2708                                this.child(
2709                                    MarkdownElement::new(
2710                                        markdown.clone(),
2711                                        default_markdown_style(window, cx),
2712                                    )
2713                                    .on_url_click({
2714                                        let workspace = self.workspace.clone();
2715                                        move |text, window, cx| {
2716                                            open_markdown_link(text, workspace.clone(), window, cx);
2717                                        }
2718                                    }),
2719                                )
2720                            }),
2721                    )
2722            }
2723        })
2724    }
2725
2726    fn render_tool_use(
2727        &self,
2728        tool_use: ToolUse,
2729        window: &mut Window,
2730        workspace: WeakEntity<Workspace>,
2731        cx: &mut Context<Self>,
2732    ) -> impl IntoElement + use<> {
2733        if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2734            return card.render(&tool_use.status, window, workspace, cx);
2735        }
2736
2737        let is_open = self
2738            .expanded_tool_uses
2739            .get(&tool_use.id)
2740            .copied()
2741            .unwrap_or_default();
2742
2743        let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2744
2745        let fs = self
2746            .workspace
2747            .upgrade()
2748            .map(|workspace| workspace.read(cx).app_state().fs.clone());
2749        let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2750        let needs_confirmation_tools = tool_use.needs_confirmation;
2751
2752        let status_icons = div().child(match &tool_use.status {
2753            ToolUseStatus::NeedsConfirmation => {
2754                let icon = Icon::new(IconName::Warning)
2755                    .color(Color::Warning)
2756                    .size(IconSize::Small);
2757                icon.into_any_element()
2758            }
2759            ToolUseStatus::Pending
2760            | ToolUseStatus::InputStillStreaming
2761            | ToolUseStatus::Running => {
2762                let icon = Icon::new(IconName::ArrowCircle)
2763                    .color(Color::Accent)
2764                    .size(IconSize::Small);
2765                icon.with_animation(
2766                    "arrow-circle",
2767                    Animation::new(Duration::from_secs(2)).repeat(),
2768                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2769                )
2770                .into_any_element()
2771            }
2772            ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2773            ToolUseStatus::Error(_) => {
2774                let icon = Icon::new(IconName::Close)
2775                    .color(Color::Error)
2776                    .size(IconSize::Small);
2777                icon.into_any_element()
2778            }
2779        });
2780
2781        let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2782        let results_content_container = || v_flex().p_2().gap_0p5();
2783
2784        let results_content = v_flex()
2785            .gap_1()
2786            .child(
2787                results_content_container()
2788                    .child(
2789                        Label::new("Input")
2790                            .size(LabelSize::XSmall)
2791                            .color(Color::Muted)
2792                            .buffer_font(cx),
2793                    )
2794                    .child(
2795                        div()
2796                            .w_full()
2797                            .text_ui_sm(cx)
2798                            .children(rendered_tool_use.as_ref().map(|rendered| {
2799                                MarkdownElement::new(
2800                                    rendered.input.clone(),
2801                                    tool_use_markdown_style(window, cx),
2802                                )
2803                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2804                                    copy_button: false,
2805                                    copy_button_on_hover: false,
2806                                    border: false,
2807                                })
2808                                .on_url_click({
2809                                    let workspace = self.workspace.clone();
2810                                    move |text, window, cx| {
2811                                        open_markdown_link(text, workspace.clone(), window, cx);
2812                                    }
2813                                })
2814                            })),
2815                    ),
2816            )
2817            .map(|container| match tool_use.status {
2818                ToolUseStatus::Finished(_) => container.child(
2819                    results_content_container()
2820                        .border_t_1()
2821                        .border_color(self.tool_card_border_color(cx))
2822                        .child(
2823                            Label::new("Result")
2824                                .size(LabelSize::XSmall)
2825                                .color(Color::Muted)
2826                                .buffer_font(cx),
2827                        )
2828                        .child(div().w_full().text_ui_sm(cx).children(
2829                            rendered_tool_use.as_ref().map(|rendered| {
2830                                MarkdownElement::new(
2831                                    rendered.output.clone(),
2832                                    tool_use_markdown_style(window, cx),
2833                                )
2834                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2835                                    copy_button: false,
2836                                    copy_button_on_hover: false,
2837                                    border: false,
2838                                })
2839                                .on_url_click({
2840                                    let workspace = self.workspace.clone();
2841                                    move |text, window, cx| {
2842                                        open_markdown_link(text, workspace.clone(), window, cx);
2843                                    }
2844                                })
2845                                .into_any_element()
2846                            }),
2847                        )),
2848                ),
2849                ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2850                    results_content_container()
2851                        .border_t_1()
2852                        .border_color(self.tool_card_border_color(cx))
2853                        .child(
2854                            h_flex()
2855                                .gap_1()
2856                                .child(
2857                                    Icon::new(IconName::ArrowCircle)
2858                                        .size(IconSize::Small)
2859                                        .color(Color::Accent)
2860                                        .with_animation(
2861                                            "arrow-circle",
2862                                            Animation::new(Duration::from_secs(2)).repeat(),
2863                                            |icon, delta| {
2864                                                icon.transform(Transformation::rotate(percentage(
2865                                                    delta,
2866                                                )))
2867                                            },
2868                                        ),
2869                                )
2870                                .child(
2871                                    Label::new("Running…")
2872                                        .size(LabelSize::XSmall)
2873                                        .color(Color::Muted)
2874                                        .buffer_font(cx),
2875                                ),
2876                        ),
2877                ),
2878                ToolUseStatus::Error(_) => container.child(
2879                    results_content_container()
2880                        .border_t_1()
2881                        .border_color(self.tool_card_border_color(cx))
2882                        .child(
2883                            Label::new("Error")
2884                                .size(LabelSize::XSmall)
2885                                .color(Color::Muted)
2886                                .buffer_font(cx),
2887                        )
2888                        .child(
2889                            div()
2890                                .text_ui_sm(cx)
2891                                .children(rendered_tool_use.as_ref().map(|rendered| {
2892                                    MarkdownElement::new(
2893                                        rendered.output.clone(),
2894                                        tool_use_markdown_style(window, cx),
2895                                    )
2896                                    .on_url_click({
2897                                        let workspace = self.workspace.clone();
2898                                        move |text, window, cx| {
2899                                            open_markdown_link(text, workspace.clone(), window, cx);
2900                                        }
2901                                    })
2902                                    .into_any_element()
2903                                })),
2904                        ),
2905                ),
2906                ToolUseStatus::Pending => container,
2907                ToolUseStatus::NeedsConfirmation => container.child(
2908                    results_content_container()
2909                        .border_t_1()
2910                        .border_color(self.tool_card_border_color(cx))
2911                        .child(
2912                            Label::new("Asking Permission")
2913                                .size(LabelSize::Small)
2914                                .color(Color::Muted)
2915                                .buffer_font(cx),
2916                        ),
2917                ),
2918            });
2919
2920        let gradient_overlay = |color: Hsla| {
2921            div()
2922                .h_full()
2923                .absolute()
2924                .w_12()
2925                .bottom_0()
2926                .map(|element| {
2927                    if is_status_finished {
2928                        element.right_6()
2929                    } else {
2930                        element.right(px(44.))
2931                    }
2932                })
2933                .bg(linear_gradient(
2934                    90.,
2935                    linear_color_stop(color, 1.),
2936                    linear_color_stop(color.opacity(0.2), 0.),
2937                ))
2938        };
2939
2940        v_flex().gap_1().mb_2().map(|element| {
2941            if !needs_confirmation_tools {
2942                element.child(
2943                    v_flex()
2944                        .child(
2945                            h_flex()
2946                                .group("disclosure-header")
2947                                .relative()
2948                                .gap_1p5()
2949                                .justify_between()
2950                                .opacity(0.8)
2951                                .hover(|style| style.opacity(1.))
2952                                .when(!is_status_finished, |this| this.pr_2())
2953                                .child(
2954                                    h_flex()
2955                                        .id("tool-label-container")
2956                                        .gap_1p5()
2957                                        .max_w_full()
2958                                        .overflow_x_scroll()
2959                                        .child(
2960                                            Icon::new(tool_use.icon)
2961                                                .size(IconSize::XSmall)
2962                                                .color(Color::Muted),
2963                                        )
2964                                        .child(
2965                                            h_flex().pr_8().text_size(rems(0.8125)).children(
2966                                                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| {
2967                                                    open_markdown_link(text, workspace.clone(), window, cx);
2968                                                }}))
2969                                            ),
2970                                        ),
2971                                )
2972                                .child(
2973                                    h_flex()
2974                                        .gap_1()
2975                                        .child(
2976                                            div().visible_on_hover("disclosure-header").child(
2977                                                Disclosure::new("tool-use-disclosure", is_open)
2978                                                    .opened_icon(IconName::ChevronUp)
2979                                                    .closed_icon(IconName::ChevronDown)
2980                                                    .on_click(cx.listener({
2981                                                        let tool_use_id = tool_use.id.clone();
2982                                                        move |this, _event, _window, _cx| {
2983                                                            let is_open = this
2984                                                                .expanded_tool_uses
2985                                                                .entry(tool_use_id.clone())
2986                                                                .or_insert(false);
2987
2988                                                            *is_open = !*is_open;
2989                                                        }
2990                                                    })),
2991                                            ),
2992                                        )
2993                                        .child(status_icons),
2994                                )
2995                                .child(gradient_overlay(cx.theme().colors().panel_background)),
2996                        )
2997                        .map(|parent| {
2998                            if !is_open {
2999                                return parent;
3000                            }
3001
3002                            parent.child(
3003                                v_flex()
3004                                    .mt_1()
3005                                    .border_1()
3006                                    .border_color(self.tool_card_border_color(cx))
3007                                    .bg(cx.theme().colors().editor_background)
3008                                    .rounded_lg()
3009                                    .child(results_content),
3010                            )
3011                        }),
3012                )
3013            } else {
3014                v_flex()
3015                    .mb_2()
3016                    .rounded_lg()
3017                    .border_1()
3018                    .border_color(self.tool_card_border_color(cx))
3019                    .overflow_hidden()
3020                    .child(
3021                        h_flex()
3022                            .group("disclosure-header")
3023                            .relative()
3024                            .justify_between()
3025                            .py_1()
3026                            .map(|element| {
3027                                if is_status_finished {
3028                                    element.pl_2().pr_0p5()
3029                                } else {
3030                                    element.px_2()
3031                                }
3032                            })
3033                            .bg(self.tool_card_header_bg(cx))
3034                            .map(|element| {
3035                                if is_open {
3036                                    element.border_b_1().rounded_t_md()
3037                                } else if needs_confirmation {
3038                                    element.rounded_t_md()
3039                                } else {
3040                                    element.rounded_md()
3041                                }
3042                            })
3043                            .border_color(self.tool_card_border_color(cx))
3044                            .child(
3045                                h_flex()
3046                                    .id("tool-label-container")
3047                                    .gap_1p5()
3048                                    .max_w_full()
3049                                    .overflow_x_scroll()
3050                                    .child(
3051                                        Icon::new(tool_use.icon)
3052                                            .size(IconSize::XSmall)
3053                                            .color(Color::Muted),
3054                                    )
3055                                    .child(
3056                                        h_flex().pr_8().text_ui_sm(cx).children(
3057                                            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| {
3058                                                open_markdown_link(text, workspace.clone(), window, cx);
3059                                            }}))
3060                                        ),
3061                                    ),
3062                            )
3063                            .child(
3064                                h_flex()
3065                                    .gap_1()
3066                                    .child(
3067                                        div().visible_on_hover("disclosure-header").child(
3068                                            Disclosure::new("tool-use-disclosure", is_open)
3069                                                .opened_icon(IconName::ChevronUp)
3070                                                .closed_icon(IconName::ChevronDown)
3071                                                .on_click(cx.listener({
3072                                                    let tool_use_id = tool_use.id.clone();
3073                                                    move |this, _event, _window, _cx| {
3074                                                        let is_open = this
3075                                                            .expanded_tool_uses
3076                                                            .entry(tool_use_id.clone())
3077                                                            .or_insert(false);
3078
3079                                                        *is_open = !*is_open;
3080                                                    }
3081                                                })),
3082                                        ),
3083                                    )
3084                                    .child(status_icons),
3085                            )
3086                            .child(gradient_overlay(self.tool_card_header_bg(cx))),
3087                    )
3088                    .map(|parent| {
3089                        if !is_open {
3090                            return parent;
3091                        }
3092
3093                        parent.child(
3094                            v_flex()
3095                                .bg(cx.theme().colors().editor_background)
3096                                .map(|element| {
3097                                    if  needs_confirmation {
3098                                        element.rounded_none()
3099                                    } else {
3100                                        element.rounded_b_lg()
3101                                    }
3102                                })
3103                                .child(results_content),
3104                        )
3105                    })
3106                    .when(needs_confirmation, |this| {
3107                        this.child(
3108                            h_flex()
3109                                .py_1()
3110                                .pl_2()
3111                                .pr_1()
3112                                .gap_1()
3113                                .justify_between()
3114                                .flex_wrap()
3115                                .bg(cx.theme().colors().editor_background)
3116                                .border_t_1()
3117                                .border_color(self.tool_card_border_color(cx))
3118                                .rounded_b_lg()
3119                                .child(
3120                                    AnimatedLabel::new("Waiting for Confirmation").size(LabelSize::Small)
3121                                )
3122                                .child(
3123                                    h_flex()
3124                                        .gap_0p5()
3125                                        .child({
3126                                            let tool_id = tool_use.id.clone();
3127                                            Button::new(
3128                                                "always-allow-tool-action",
3129                                                "Always Allow",
3130                                            )
3131                                            .label_size(LabelSize::Small)
3132                                            .icon(IconName::CheckDouble)
3133                                            .icon_position(IconPosition::Start)
3134                                            .icon_size(IconSize::Small)
3135                                            .icon_color(Color::Success)
3136                                            .tooltip(move |window, cx|  {
3137                                                Tooltip::with_meta(
3138                                                    "Never ask for permission",
3139                                                    None,
3140                                                    "Restore the original behavior in your Agent Panel settings",
3141                                                    window,
3142                                                    cx,
3143                                                )
3144                                            })
3145                                            .on_click(cx.listener(
3146                                                move |this, event, window, cx| {
3147                                                    if let Some(fs) = fs.clone() {
3148                                                        update_settings_file::<AgentSettings>(
3149                                                            fs.clone(),
3150                                                            cx,
3151                                                            |settings, _| {
3152                                                                settings.set_always_allow_tool_actions(true);
3153                                                            },
3154                                                        );
3155                                                    }
3156                                                    this.handle_allow_tool(
3157                                                        tool_id.clone(),
3158                                                        event,
3159                                                        window,
3160                                                        cx,
3161                                                    )
3162                                                },
3163                                            ))
3164                                        })
3165                                        .child(ui::Divider::vertical())
3166                                        .child({
3167                                            let tool_id = tool_use.id.clone();
3168                                            Button::new("allow-tool-action", "Allow")
3169                                                .label_size(LabelSize::Small)
3170                                                .icon(IconName::Check)
3171                                                .icon_position(IconPosition::Start)
3172                                                .icon_size(IconSize::Small)
3173                                                .icon_color(Color::Success)
3174                                                .on_click(cx.listener(
3175                                                    move |this, event, window, cx| {
3176                                                        this.handle_allow_tool(
3177                                                            tool_id.clone(),
3178                                                            event,
3179                                                            window,
3180                                                            cx,
3181                                                        )
3182                                                    },
3183                                                ))
3184                                        })
3185                                        .child({
3186                                            let tool_id = tool_use.id.clone();
3187                                            let tool_name: Arc<str> = tool_use.name.into();
3188                                            Button::new("deny-tool", "Deny")
3189                                                .label_size(LabelSize::Small)
3190                                                .icon(IconName::Close)
3191                                                .icon_position(IconPosition::Start)
3192                                                .icon_size(IconSize::Small)
3193                                                .icon_color(Color::Error)
3194                                                .on_click(cx.listener(
3195                                                    move |this, event, window, cx| {
3196                                                        this.handle_deny_tool(
3197                                                            tool_id.clone(),
3198                                                            tool_name.clone(),
3199                                                            event,
3200                                                            window,
3201                                                            cx,
3202                                                        )
3203                                                    },
3204                                                ))
3205                                        }),
3206                                ),
3207                        )
3208                    })
3209            }
3210        }).into_any_element()
3211    }
3212
3213    fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3214        let project_context = self.thread.read(cx).project_context();
3215        let project_context = project_context.borrow();
3216        let Some(project_context) = project_context.as_ref() else {
3217            return div().into_any();
3218        };
3219
3220        let user_rules_text = if project_context.user_rules.is_empty() {
3221            None
3222        } else if project_context.user_rules.len() == 1 {
3223            let user_rules = &project_context.user_rules[0];
3224
3225            match user_rules.title.as_ref() {
3226                Some(title) => Some(format!("Using \"{title}\" user rule")),
3227                None => Some("Using user rule".into()),
3228            }
3229        } else {
3230            Some(format!(
3231                "Using {} user rules",
3232                project_context.user_rules.len()
3233            ))
3234        };
3235
3236        let first_user_rules_id = project_context
3237            .user_rules
3238            .first()
3239            .map(|user_rules| user_rules.uuid.0);
3240
3241        let rules_files = project_context
3242            .worktrees
3243            .iter()
3244            .filter_map(|worktree| worktree.rules_file.as_ref())
3245            .collect::<Vec<_>>();
3246
3247        let rules_file_text = match rules_files.as_slice() {
3248            &[] => None,
3249            &[rules_file] => Some(format!(
3250                "Using project {:?} file",
3251                rules_file.path_in_worktree
3252            )),
3253            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3254        };
3255
3256        if user_rules_text.is_none() && rules_file_text.is_none() {
3257            return div().into_any();
3258        }
3259
3260        v_flex()
3261            .pt_2()
3262            .px_2p5()
3263            .gap_1()
3264            .when_some(user_rules_text, |parent, user_rules_text| {
3265                parent.child(
3266                    h_flex()
3267                        .w_full()
3268                        .child(
3269                            Icon::new(RULES_ICON)
3270                                .size(IconSize::XSmall)
3271                                .color(Color::Disabled),
3272                        )
3273                        .child(
3274                            Label::new(user_rules_text)
3275                                .size(LabelSize::XSmall)
3276                                .color(Color::Muted)
3277                                .truncate()
3278                                .buffer_font(cx)
3279                                .ml_1p5()
3280                                .mr_0p5(),
3281                        )
3282                        .child(
3283                            IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3284                                .shape(ui::IconButtonShape::Square)
3285                                .icon_size(IconSize::XSmall)
3286                                .icon_color(Color::Ignored)
3287                                // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary`  keybinding
3288                                .tooltip(Tooltip::text("View User Rules"))
3289                                .on_click(move |_event, window, cx| {
3290                                    window.dispatch_action(
3291                                        Box::new(OpenRulesLibrary {
3292                                            prompt_to_select: first_user_rules_id,
3293                                        }),
3294                                        cx,
3295                                    )
3296                                }),
3297                        ),
3298                )
3299            })
3300            .when_some(rules_file_text, |parent, rules_file_text| {
3301                parent.child(
3302                    h_flex()
3303                        .w_full()
3304                        .child(
3305                            Icon::new(IconName::File)
3306                                .size(IconSize::XSmall)
3307                                .color(Color::Disabled),
3308                        )
3309                        .child(
3310                            Label::new(rules_file_text)
3311                                .size(LabelSize::XSmall)
3312                                .color(Color::Muted)
3313                                .buffer_font(cx)
3314                                .ml_1p5()
3315                                .mr_0p5(),
3316                        )
3317                        .child(
3318                            IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3319                                .shape(ui::IconButtonShape::Square)
3320                                .icon_size(IconSize::XSmall)
3321                                .icon_color(Color::Ignored)
3322                                .on_click(cx.listener(Self::handle_open_rules))
3323                                .tooltip(Tooltip::text("View Rules")),
3324                        ),
3325                )
3326            })
3327            .into_any()
3328    }
3329
3330    fn handle_allow_tool(
3331        &mut self,
3332        tool_use_id: LanguageModelToolUseId,
3333        _: &ClickEvent,
3334        window: &mut Window,
3335        cx: &mut Context<Self>,
3336    ) {
3337        if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3338            .thread
3339            .read(cx)
3340            .pending_tool(&tool_use_id)
3341            .map(|tool_use| tool_use.status.clone())
3342        {
3343            self.thread.update(cx, |thread, cx| {
3344                if let Some(configured) = thread.get_or_init_configured_model(cx) {
3345                    thread.run_tool(
3346                        c.tool_use_id.clone(),
3347                        c.ui_text.clone(),
3348                        c.input.clone(),
3349                        c.request.clone(),
3350                        c.tool.clone(),
3351                        configured.model,
3352                        Some(window.window_handle()),
3353                        cx,
3354                    );
3355                }
3356            });
3357        }
3358    }
3359
3360    fn handle_deny_tool(
3361        &mut self,
3362        tool_use_id: LanguageModelToolUseId,
3363        tool_name: Arc<str>,
3364        _: &ClickEvent,
3365        window: &mut Window,
3366        cx: &mut Context<Self>,
3367    ) {
3368        let window_handle = window.window_handle();
3369        self.thread.update(cx, |thread, cx| {
3370            thread.deny_tool_use(tool_use_id, tool_name, Some(window_handle), cx);
3371        });
3372    }
3373
3374    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3375        let project_context = self.thread.read(cx).project_context();
3376        let project_context = project_context.borrow();
3377        let Some(project_context) = project_context.as_ref() else {
3378            return;
3379        };
3380
3381        let project_entry_ids = project_context
3382            .worktrees
3383            .iter()
3384            .flat_map(|worktree| worktree.rules_file.as_ref())
3385            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
3386            .collect::<Vec<_>>();
3387
3388        self.workspace
3389            .update(cx, move |workspace, cx| {
3390                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3391                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3392                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3393                let project = workspace.project().read(cx);
3394                let project_paths = project_entry_ids
3395                    .into_iter()
3396                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
3397                    .collect::<Vec<_>>();
3398                for project_path in project_paths {
3399                    workspace
3400                        .open_path(project_path, None, true, window, cx)
3401                        .detach_and_log_err(cx);
3402                }
3403            })
3404            .ok();
3405    }
3406
3407    fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3408        for window in self.notifications.drain(..) {
3409            window
3410                .update(cx, |_, window, _| {
3411                    window.remove_window();
3412                })
3413                .ok();
3414
3415            self.notification_subscriptions.remove(&window);
3416        }
3417    }
3418
3419    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3420        if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3421            return None;
3422        }
3423
3424        Some(
3425            div()
3426                .occlude()
3427                .id("active-thread-scrollbar")
3428                .on_mouse_move(cx.listener(|_, _, _, cx| {
3429                    cx.notify();
3430                    cx.stop_propagation()
3431                }))
3432                .on_hover(|_, _, cx| {
3433                    cx.stop_propagation();
3434                })
3435                .on_any_mouse_down(|_, _, cx| {
3436                    cx.stop_propagation();
3437                })
3438                .on_mouse_up(
3439                    MouseButton::Left,
3440                    cx.listener(|_, _, _, cx| {
3441                        cx.stop_propagation();
3442                    }),
3443                )
3444                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3445                    cx.notify();
3446                }))
3447                .h_full()
3448                .absolute()
3449                .right_1()
3450                .top_1()
3451                .bottom_0()
3452                .w(px(12.))
3453                .cursor_default()
3454                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3455        )
3456    }
3457
3458    fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3459        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3460        self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3461            cx.background_executor()
3462                .timer(SCROLLBAR_SHOW_INTERVAL)
3463                .await;
3464            thread
3465                .update(cx, |thread, cx| {
3466                    if !thread.scrollbar_state.is_dragging() {
3467                        thread.show_scrollbar = false;
3468                        cx.notify();
3469                    }
3470                })
3471                .log_err();
3472        }))
3473    }
3474
3475    pub fn is_codeblock_expanded(&self, message_id: MessageId, ix: usize) -> bool {
3476        self.expanded_code_blocks
3477            .get(&(message_id, ix))
3478            .copied()
3479            .unwrap_or(true)
3480    }
3481
3482    pub fn toggle_codeblock_expanded(&mut self, message_id: MessageId, ix: usize) {
3483        let is_expanded = self
3484            .expanded_code_blocks
3485            .entry((message_id, ix))
3486            .or_insert(true);
3487        *is_expanded = !*is_expanded;
3488    }
3489
3490    pub fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3491        self.list_state.scroll_to(ListOffset::default());
3492        cx.notify();
3493    }
3494
3495    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3496        self.list_state.reset(self.messages.len());
3497        cx.notify();
3498    }
3499}
3500
3501pub enum ActiveThreadEvent {
3502    EditingMessageTokenCountChanged,
3503}
3504
3505impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3506
3507impl Render for ActiveThread {
3508    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3509        v_flex()
3510            .size_full()
3511            .relative()
3512            .bg(cx.theme().colors().panel_background)
3513            .on_mouse_move(cx.listener(|this, _, _, cx| {
3514                this.show_scrollbar = true;
3515                this.hide_scrollbar_later(cx);
3516                cx.notify();
3517            }))
3518            .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3519                this.show_scrollbar = true;
3520                this.hide_scrollbar_later(cx);
3521                cx.notify();
3522            }))
3523            .on_mouse_up(
3524                MouseButton::Left,
3525                cx.listener(|this, _, _, cx| {
3526                    this.hide_scrollbar_later(cx);
3527                }),
3528            )
3529            .child(list(self.list_state.clone()).flex_grow())
3530            .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3531                this.child(scrollbar)
3532            })
3533    }
3534}
3535
3536pub(crate) fn open_active_thread_as_markdown(
3537    thread: Entity<Thread>,
3538    workspace: Entity<Workspace>,
3539    window: &mut Window,
3540    cx: &mut App,
3541) -> Task<anyhow::Result<()>> {
3542    let markdown_language_task = workspace
3543        .read(cx)
3544        .app_state()
3545        .languages
3546        .language_for_name("Markdown");
3547
3548    window.spawn(cx, async move |cx| {
3549        let markdown_language = markdown_language_task.await?;
3550
3551        workspace.update_in(cx, |workspace, window, cx| {
3552            let thread = thread.read(cx);
3553            let markdown = thread.to_markdown(cx)?;
3554            let thread_summary = thread.summary().or_default().to_string();
3555
3556            let project = workspace.project().clone();
3557
3558            if !project.read(cx).is_local() {
3559                anyhow::bail!("failed to open active thread as markdown in remote project");
3560            }
3561
3562            let buffer = project.update(cx, |project, cx| {
3563                project.create_local_buffer(&markdown, Some(markdown_language), cx)
3564            });
3565            let buffer =
3566                cx.new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone()));
3567
3568            workspace.add_item_to_active_pane(
3569                Box::new(cx.new(|cx| {
3570                    let mut editor =
3571                        Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3572                    editor.set_breadcrumb_header(thread_summary);
3573                    editor
3574                })),
3575                None,
3576                true,
3577                window,
3578                cx,
3579            );
3580
3581            anyhow::Ok(())
3582        })??;
3583        anyhow::Ok(())
3584    })
3585}
3586
3587pub(crate) fn open_context(
3588    context: &AgentContextHandle,
3589    workspace: Entity<Workspace>,
3590    window: &mut Window,
3591    cx: &mut App,
3592) {
3593    match context {
3594        AgentContextHandle::File(file_context) => {
3595            if let Some(project_path) = file_context.project_path(cx) {
3596                workspace.update(cx, |workspace, cx| {
3597                    workspace
3598                        .open_path(project_path, None, true, window, cx)
3599                        .detach_and_log_err(cx);
3600                });
3601            }
3602        }
3603
3604        AgentContextHandle::Directory(directory_context) => {
3605            let entry_id = directory_context.entry_id;
3606            workspace.update(cx, |workspace, cx| {
3607                workspace.project().update(cx, |_project, cx| {
3608                    cx.emit(project::Event::RevealInProjectPanel(entry_id));
3609                })
3610            })
3611        }
3612
3613        AgentContextHandle::Symbol(symbol_context) => {
3614            let buffer = symbol_context.buffer.read(cx);
3615            if let Some(project_path) = buffer.project_path(cx) {
3616                let snapshot = buffer.snapshot();
3617                let target_position = symbol_context.range.start.to_point(&snapshot);
3618                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3619                    .detach();
3620            }
3621        }
3622
3623        AgentContextHandle::Selection(selection_context) => {
3624            let buffer = selection_context.buffer.read(cx);
3625            if let Some(project_path) = buffer.project_path(cx) {
3626                let snapshot = buffer.snapshot();
3627                let target_position = selection_context.range.start.to_point(&snapshot);
3628
3629                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3630                    .detach();
3631            }
3632        }
3633
3634        AgentContextHandle::FetchedUrl(fetched_url_context) => {
3635            cx.open_url(&fetched_url_context.url);
3636        }
3637
3638        AgentContextHandle::Thread(thread_context) => workspace.update(cx, |workspace, cx| {
3639            if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3640                panel.update(cx, |panel, cx| {
3641                    panel.open_thread(thread_context.thread.clone(), window, cx);
3642                });
3643            }
3644        }),
3645
3646        AgentContextHandle::TextThread(text_thread_context) => {
3647            workspace.update(cx, |workspace, cx| {
3648                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3649                    panel.update(cx, |panel, cx| {
3650                        panel.open_prompt_editor(text_thread_context.context.clone(), window, cx)
3651                    });
3652                }
3653            })
3654        }
3655
3656        AgentContextHandle::Rules(rules_context) => window.dispatch_action(
3657            Box::new(OpenRulesLibrary {
3658                prompt_to_select: Some(rules_context.prompt_id.0),
3659            }),
3660            cx,
3661        ),
3662
3663        AgentContextHandle::Image(_) => {}
3664    }
3665}
3666
3667pub(crate) fn attach_pasted_images_as_context(
3668    context_store: &Entity<ContextStore>,
3669    cx: &mut App,
3670) -> bool {
3671    let images = cx
3672        .read_from_clipboard()
3673        .map(|item| {
3674            item.into_entries()
3675                .filter_map(|entry| {
3676                    if let ClipboardEntry::Image(image) = entry {
3677                        Some(image)
3678                    } else {
3679                        None
3680                    }
3681                })
3682                .collect::<Vec<_>>()
3683        })
3684        .unwrap_or_default();
3685
3686    if images.is_empty() {
3687        return false;
3688    }
3689    cx.stop_propagation();
3690
3691    context_store.update(cx, |store, cx| {
3692        for image in images {
3693            store.add_image_instance(Arc::new(image), cx);
3694        }
3695    });
3696    true
3697}
3698
3699fn open_editor_at_position(
3700    project_path: project::ProjectPath,
3701    target_position: Point,
3702    workspace: &Entity<Workspace>,
3703    window: &mut Window,
3704    cx: &mut App,
3705) -> Task<()> {
3706    let open_task = workspace.update(cx, |workspace, cx| {
3707        workspace.open_path(project_path, None, true, window, cx)
3708    });
3709    window.spawn(cx, async move |cx| {
3710        if let Some(active_editor) = open_task
3711            .await
3712            .log_err()
3713            .and_then(|item| item.downcast::<Editor>())
3714        {
3715            active_editor
3716                .downgrade()
3717                .update_in(cx, |editor, window, cx| {
3718                    editor.go_to_singleton_buffer_point(target_position, window, cx);
3719                })
3720                .log_err();
3721        }
3722    })
3723}
3724
3725#[cfg(test)]
3726mod tests {
3727    use assistant_tool::{ToolRegistry, ToolWorkingSet};
3728    use editor::{EditorSettings, display_map::CreaseMetadata};
3729    use fs::FakeFs;
3730    use gpui::{AppContext, TestAppContext, VisualTestContext};
3731    use language_model::{
3732        ConfiguredModel, LanguageModel, LanguageModelRegistry,
3733        fake_provider::{FakeLanguageModel, FakeLanguageModelProvider},
3734    };
3735    use project::Project;
3736    use prompt_store::PromptBuilder;
3737    use serde_json::json;
3738    use settings::SettingsStore;
3739    use util::path;
3740    use workspace::CollaboratorId;
3741
3742    use crate::{ContextLoadResult, thread::MessageSegment, thread_store};
3743
3744    use super::*;
3745
3746    #[gpui::test]
3747    async fn test_agent_is_unfollowed_after_cancelling_completion(cx: &mut TestAppContext) {
3748        init_test_settings(cx);
3749
3750        let project = create_test_project(
3751            cx,
3752            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3753        )
3754        .await;
3755
3756        let (cx, _active_thread, workspace, thread, model) =
3757            setup_test_environment(cx, project.clone()).await;
3758
3759        // Insert user message without any context (empty context vector)
3760        thread.update(cx, |thread, cx| {
3761            thread.insert_user_message(
3762                "What is the best way to learn Rust?",
3763                ContextLoadResult::default(),
3764                None,
3765                vec![],
3766                cx,
3767            );
3768        });
3769
3770        // Stream response to user message
3771        thread.update(cx, |thread, cx| {
3772            let request =
3773                thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx);
3774            thread.stream_completion(request, model, cx.active_window(), cx)
3775        });
3776        // Follow the agent
3777        cx.update(|window, cx| {
3778            workspace.update(cx, |workspace, cx| {
3779                workspace.follow(CollaboratorId::Agent, window, cx);
3780            })
3781        });
3782        assert!(cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3783
3784        // Cancel the current completion
3785        thread.update(cx, |thread, cx| {
3786            thread.cancel_last_completion(cx.active_window(), cx)
3787        });
3788
3789        cx.executor().run_until_parked();
3790
3791        // No longer following the agent
3792        assert!(!cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3793    }
3794
3795    #[gpui::test]
3796    async fn test_reinserting_creases_for_edited_message(cx: &mut TestAppContext) {
3797        init_test_settings(cx);
3798
3799        let project = create_test_project(cx, json!({})).await;
3800
3801        let (cx, active_thread, _, thread, model) =
3802            setup_test_environment(cx, project.clone()).await;
3803        cx.update(|_, cx| {
3804            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3805                registry.set_default_model(
3806                    Some(ConfiguredModel {
3807                        provider: Arc::new(FakeLanguageModelProvider),
3808                        model,
3809                    }),
3810                    cx,
3811                );
3812            });
3813        });
3814
3815        let creases = vec![MessageCrease {
3816            range: 14..22,
3817            metadata: CreaseMetadata {
3818                icon_path: "icon".into(),
3819                label: "foo.txt".into(),
3820            },
3821            context: None,
3822        }];
3823
3824        let message = thread.update(cx, |thread, cx| {
3825            let message_id = thread.insert_user_message(
3826                "Tell me about @foo.txt",
3827                ContextLoadResult::default(),
3828                None,
3829                creases,
3830                cx,
3831            );
3832            thread.message(message_id).cloned().unwrap()
3833        });
3834
3835        active_thread.update_in(cx, |active_thread, window, cx| {
3836            active_thread.start_editing_message(
3837                message.id,
3838                message.segments.as_slice(),
3839                message.creases.as_slice(),
3840                window,
3841                cx,
3842            );
3843            let editor = active_thread
3844                .editing_message
3845                .as_ref()
3846                .unwrap()
3847                .1
3848                .editor
3849                .clone();
3850            editor.update(cx, |editor, cx| editor.edit([(0..13, "modified")], cx));
3851            active_thread.confirm_editing_message(&Default::default(), window, cx);
3852        });
3853        cx.run_until_parked();
3854
3855        let message = thread.update(cx, |thread, _| thread.message(message.id).cloned().unwrap());
3856        active_thread.update_in(cx, |active_thread, window, cx| {
3857            active_thread.start_editing_message(
3858                message.id,
3859                message.segments.as_slice(),
3860                message.creases.as_slice(),
3861                window,
3862                cx,
3863            );
3864            let editor = active_thread
3865                .editing_message
3866                .as_ref()
3867                .unwrap()
3868                .1
3869                .editor
3870                .clone();
3871            let text = editor.update(cx, |editor, cx| editor.text(cx));
3872            assert_eq!(text, "modified @foo.txt");
3873        });
3874    }
3875
3876    #[gpui::test]
3877    async fn test_editing_message_cancels_previous_completion(cx: &mut TestAppContext) {
3878        init_test_settings(cx);
3879
3880        let project = create_test_project(cx, json!({})).await;
3881
3882        let (cx, active_thread, _, thread, model) =
3883            setup_test_environment(cx, project.clone()).await;
3884
3885        cx.update(|_, cx| {
3886            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3887                registry.set_default_model(
3888                    Some(ConfiguredModel {
3889                        provider: Arc::new(FakeLanguageModelProvider),
3890                        model: model.clone(),
3891                    }),
3892                    cx,
3893                );
3894            });
3895        });
3896
3897        // Track thread events to verify cancellation
3898        let cancellation_events = Arc::new(std::sync::Mutex::new(Vec::new()));
3899        let new_request_events = Arc::new(std::sync::Mutex::new(Vec::new()));
3900
3901        let _subscription = cx.update(|_, cx| {
3902            let cancellation_events = cancellation_events.clone();
3903            let new_request_events = new_request_events.clone();
3904            cx.subscribe(
3905                &thread,
3906                move |_thread, event: &ThreadEvent, _cx| match event {
3907                    ThreadEvent::CompletionCanceled => {
3908                        cancellation_events.lock().unwrap().push(());
3909                    }
3910                    ThreadEvent::NewRequest => {
3911                        new_request_events.lock().unwrap().push(());
3912                    }
3913                    _ => {}
3914                },
3915            )
3916        });
3917
3918        // Insert a user message and start streaming a response
3919        let message = thread.update(cx, |thread, cx| {
3920            let message_id = thread.insert_user_message(
3921                "Hello, how are you?",
3922                ContextLoadResult::default(),
3923                None,
3924                vec![],
3925                cx,
3926            );
3927            thread.advance_prompt_id();
3928            thread.send_to_model(
3929                model.clone(),
3930                CompletionIntent::UserPrompt,
3931                cx.active_window(),
3932                cx,
3933            );
3934            thread.message(message_id).cloned().unwrap()
3935        });
3936
3937        cx.run_until_parked();
3938
3939        // Verify that a completion is in progress
3940        assert!(cx.read(|cx| thread.read(cx).is_generating()));
3941        assert_eq!(new_request_events.lock().unwrap().len(), 1);
3942
3943        // Edit the message while the completion is still running
3944        active_thread.update_in(cx, |active_thread, window, cx| {
3945            active_thread.start_editing_message(
3946                message.id,
3947                message.segments.as_slice(),
3948                message.creases.as_slice(),
3949                window,
3950                cx,
3951            );
3952            let editor = active_thread
3953                .editing_message
3954                .as_ref()
3955                .unwrap()
3956                .1
3957                .editor
3958                .clone();
3959            editor.update(cx, |editor, cx| {
3960                editor.set_text("What is the weather like?", window, cx);
3961            });
3962            active_thread.confirm_editing_message(&Default::default(), window, cx);
3963        });
3964
3965        cx.run_until_parked();
3966
3967        // Verify that the previous completion was cancelled
3968        assert_eq!(cancellation_events.lock().unwrap().len(), 1);
3969
3970        // Verify that a new request was started after cancellation
3971        assert_eq!(new_request_events.lock().unwrap().len(), 2);
3972
3973        // Verify that the edited message contains the new text
3974        let edited_message =
3975            thread.update(cx, |thread, _| thread.message(message.id).cloned().unwrap());
3976        match &edited_message.segments[0] {
3977            MessageSegment::Text(text) => {
3978                assert_eq!(text, "What is the weather like?");
3979            }
3980            _ => panic!("Expected text segment"),
3981        }
3982    }
3983
3984    fn init_test_settings(cx: &mut TestAppContext) {
3985        cx.update(|cx| {
3986            let settings_store = SettingsStore::test(cx);
3987            cx.set_global(settings_store);
3988            language::init(cx);
3989            Project::init_settings(cx);
3990            AgentSettings::register(cx);
3991            prompt_store::init(cx);
3992            thread_store::init(cx);
3993            workspace::init_settings(cx);
3994            language_model::init_settings(cx);
3995            ThemeSettings::register(cx);
3996            EditorSettings::register(cx);
3997            ToolRegistry::default_global(cx);
3998        });
3999    }
4000
4001    // Helper to create a test project with test files
4002    async fn create_test_project(
4003        cx: &mut TestAppContext,
4004        files: serde_json::Value,
4005    ) -> Entity<Project> {
4006        let fs = FakeFs::new(cx.executor());
4007        fs.insert_tree(path!("/test"), files).await;
4008        Project::test(fs, [path!("/test").as_ref()], cx).await
4009    }
4010
4011    async fn setup_test_environment(
4012        cx: &mut TestAppContext,
4013        project: Entity<Project>,
4014    ) -> (
4015        &mut VisualTestContext,
4016        Entity<ActiveThread>,
4017        Entity<Workspace>,
4018        Entity<Thread>,
4019        Arc<dyn LanguageModel>,
4020    ) {
4021        let (workspace, cx) =
4022            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4023
4024        let thread_store = cx
4025            .update(|_, cx| {
4026                ThreadStore::load(
4027                    project.clone(),
4028                    cx.new(|_| ToolWorkingSet::default()),
4029                    None,
4030                    Arc::new(PromptBuilder::new(None).unwrap()),
4031                    cx,
4032                )
4033            })
4034            .await
4035            .unwrap();
4036
4037        let text_thread_store = cx
4038            .update(|_, cx| {
4039                TextThreadStore::new(
4040                    project.clone(),
4041                    Arc::new(PromptBuilder::new(None).unwrap()),
4042                    Default::default(),
4043                    cx,
4044                )
4045            })
4046            .await
4047            .unwrap();
4048
4049        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
4050        let context_store =
4051            cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
4052
4053        let model = FakeLanguageModel::default();
4054        let model: Arc<dyn LanguageModel> = Arc::new(model);
4055
4056        let language_registry = LanguageRegistry::new(cx.executor());
4057        let language_registry = Arc::new(language_registry);
4058
4059        let active_thread = cx.update(|window, cx| {
4060            cx.new(|cx| {
4061                ActiveThread::new(
4062                    thread.clone(),
4063                    thread_store.clone(),
4064                    text_thread_store,
4065                    context_store.clone(),
4066                    language_registry.clone(),
4067                    workspace.downgrade(),
4068                    window,
4069                    cx,
4070                )
4071            })
4072        });
4073
4074        (cx, active_thread, workspace, thread, model)
4075    }
4076}