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