active_thread.rs

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