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