active_thread.rs

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