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