active_thread.rs

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