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