active_thread.rs

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