active_thread.rs

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