agent_panel.rs

   1use std::{
   2    ops::Range,
   3    path::{Path, PathBuf},
   4    rc::Rc,
   5    sync::{
   6        Arc,
   7        atomic::{AtomicBool, Ordering},
   8    },
   9    time::Duration,
  10};
  11
  12use acp_thread::{AcpThread, MentionUri, ThreadStatus};
  13use agent::{ContextServerRegistry, SharedThread, ThreadStore};
  14use agent_client_protocol as acp;
  15use agent_servers::AgentServer;
  16use collections::HashSet;
  17use db::kvp::{Dismissable, KEY_VALUE_STORE};
  18use itertools::Itertools;
  19use project::AgentId;
  20use serde::{Deserialize, Serialize};
  21use settings::{LanguageModelProviderSetting, LanguageModelSelection};
  22
  23use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
  24use zed_actions::agent::{
  25    ConflictContent, OpenClaudeAgentOnboardingModal, ReauthenticateAgent,
  26    ResolveConflictedFilesWithAgent, ResolveConflictsWithAgent, ReviewBranchDiff,
  27};
  28
  29use crate::ui::{AcpOnboardingModal, ClaudeCodeOnboardingModal, HoldForDefault};
  30use crate::{
  31    AddContextServer, AgentDiffPane, ConversationView, CopyThreadToClipboard, CycleStartThreadIn,
  32    Follow, InlineAssistant, LoadThreadFromClipboard, NewTextThread, NewThread,
  33    OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,
  34    StartThreadIn, ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,
  35    agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
  36    conversation_view::{AcpThreadViewEvent, ThreadView},
  37    slash_command::SlashCommandCompletionProvider,
  38    text_thread_editor::{AgentPanelDelegate, TextThreadEditor, make_lsp_adapter_delegate},
  39    ui::EndTrialUpsell,
  40};
  41use crate::{
  42    Agent, AgentInitialContent, ExternalSourcePrompt, NewExternalAgentThread,
  43    NewNativeAgentThreadFromSummary,
  44};
  45use crate::{
  46    ExpandMessageEditor, ThreadHistoryView,
  47    text_thread_history::{TextThreadHistory, TextThreadHistoryEvent},
  48};
  49use crate::{ManageProfiles, ThreadHistoryViewEvent};
  50use crate::{ThreadHistory, agent_connection_store::AgentConnectionStore};
  51use agent_settings::AgentSettings;
  52use ai_onboarding::AgentPanelOnboarding;
  53use anyhow::{Context as _, Result, anyhow};
  54use assistant_slash_command::SlashCommandWorkingSet;
  55use assistant_text_thread::{TextThread, TextThreadEvent, TextThreadSummary};
  56use client::UserStore;
  57use cloud_api_types::Plan;
  58use collections::HashMap;
  59use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
  60use extension::ExtensionEvents;
  61use extension_host::ExtensionStore;
  62use fs::Fs;
  63use git::repository::validate_worktree_directory;
  64use gpui::{
  65    Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext, ClipboardItem, Corner,
  66    DismissEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, KeyContext, Pixels,
  67    Subscription, Task, UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
  68};
  69use language::LanguageRegistry;
  70use language_model::{ConfigurationError, LanguageModelRegistry};
  71use project::project_settings::ProjectSettings;
  72use project::{Project, ProjectPath, Worktree};
  73use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
  74use rules_library::{RulesLibrary, open_rules_library};
  75use search::{BufferSearchBar, buffer_search};
  76use settings::{Settings, update_settings_file};
  77use theme::ThemeSettings;
  78use ui::{
  79    Button, Callout, ContextMenu, ContextMenuEntry, DocumentationSide, KeyBinding, PopoverMenu,
  80    PopoverMenuHandle, SpinnerLabel, Tab, Tooltip, prelude::*, utils::WithRemSize,
  81};
  82use util::{ResultExt as _, debug_panic};
  83use workspace::{
  84    CollaboratorId, DraggedSelection, DraggedTab, OpenResult, PathList, SerializedPathList,
  85    ToggleZoom, ToolbarItemView, Workspace, WorkspaceId,
  86    dock::{DockPosition, Panel, PanelEvent},
  87};
  88use zed_actions::{
  89    DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
  90    agent::{OpenAcpOnboardingModal, OpenSettings, ResetAgentZoom, ResetOnboarding},
  91    assistant::{OpenRulesLibrary, Toggle, ToggleFocus},
  92};
  93
  94const AGENT_PANEL_KEY: &str = "agent_panel";
  95const RECENTLY_UPDATED_MENU_LIMIT: usize = 6;
  96const DEFAULT_THREAD_TITLE: &str = "New Thread";
  97
  98fn read_serialized_panel(workspace_id: workspace::WorkspaceId) -> Option<SerializedAgentPanel> {
  99    let scope = KEY_VALUE_STORE.scoped(AGENT_PANEL_KEY);
 100    let key = i64::from(workspace_id).to_string();
 101    scope
 102        .read(&key)
 103        .log_err()
 104        .flatten()
 105        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
 106}
 107
 108async fn save_serialized_panel(
 109    workspace_id: workspace::WorkspaceId,
 110    panel: SerializedAgentPanel,
 111) -> Result<()> {
 112    let scope = KEY_VALUE_STORE.scoped(AGENT_PANEL_KEY);
 113    let key = i64::from(workspace_id).to_string();
 114    scope.write(key, serde_json::to_string(&panel)?).await?;
 115    Ok(())
 116}
 117
 118/// Migration: reads the original single-panel format stored under the
 119/// `"agent_panel"` KVP key before per-workspace keying was introduced.
 120fn read_legacy_serialized_panel() -> Option<SerializedAgentPanel> {
 121    KEY_VALUE_STORE
 122        .read_kvp(AGENT_PANEL_KEY)
 123        .log_err()
 124        .flatten()
 125        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
 126}
 127
 128#[derive(Serialize, Deserialize, Debug)]
 129struct SerializedAgentPanel {
 130    width: Option<Pixels>,
 131    selected_agent: Option<AgentType>,
 132    #[serde(default)]
 133    last_active_thread: Option<SerializedActiveThread>,
 134    #[serde(default)]
 135    start_thread_in: Option<StartThreadIn>,
 136}
 137
 138#[derive(Serialize, Deserialize, Debug)]
 139struct SerializedActiveThread {
 140    session_id: String,
 141    agent_type: AgentType,
 142    title: Option<String>,
 143    work_dirs: Option<SerializedPathList>,
 144}
 145
 146pub fn init(cx: &mut App) {
 147    cx.observe_new(
 148        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
 149            workspace
 150                .register_action(|workspace, action: &NewThread, window, cx| {
 151                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 152                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
 153                        workspace.focus_panel::<AgentPanel>(window, cx);
 154                    }
 155                })
 156                .register_action(
 157                    |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {
 158                        if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 159                            panel.update(cx, |panel, cx| {
 160                                panel.new_native_agent_thread_from_summary(action, window, cx)
 161                            });
 162                            workspace.focus_panel::<AgentPanel>(window, cx);
 163                        }
 164                    },
 165                )
 166                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
 167                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 168                        workspace.focus_panel::<AgentPanel>(window, cx);
 169                        panel.update(cx, |panel, cx| panel.expand_message_editor(window, cx));
 170                    }
 171                })
 172                .register_action(|workspace, _: &OpenHistory, window, cx| {
 173                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 174                        workspace.focus_panel::<AgentPanel>(window, cx);
 175                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
 176                    }
 177                })
 178                .register_action(|workspace, _: &OpenSettings, window, cx| {
 179                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 180                        workspace.focus_panel::<AgentPanel>(window, cx);
 181                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
 182                    }
 183                })
 184                .register_action(|workspace, _: &NewTextThread, window, cx| {
 185                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 186                        workspace.focus_panel::<AgentPanel>(window, cx);
 187                        panel.update(cx, |panel, cx| {
 188                            panel.new_text_thread(window, cx);
 189                        });
 190                    }
 191                })
 192                .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
 193                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 194                        workspace.focus_panel::<AgentPanel>(window, cx);
 195                        panel.update(cx, |panel, cx| {
 196                            panel.external_thread(
 197                                action.agent.clone(),
 198                                None,
 199                                None,
 200                                None,
 201                                None,
 202                                true,
 203                                window,
 204                                cx,
 205                            )
 206                        });
 207                    }
 208                })
 209                .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
 210                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 211                        workspace.focus_panel::<AgentPanel>(window, cx);
 212                        panel.update(cx, |panel, cx| {
 213                            panel.deploy_rules_library(action, window, cx)
 214                        });
 215                    }
 216                })
 217                .register_action(|workspace, _: &Follow, window, cx| {
 218                    workspace.follow(CollaboratorId::Agent, window, cx);
 219                })
 220                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
 221                    let thread = workspace
 222                        .panel::<AgentPanel>(cx)
 223                        .and_then(|panel| panel.read(cx).active_conversation().cloned())
 224                        .and_then(|conversation| {
 225                            conversation
 226                                .read(cx)
 227                                .active_thread()
 228                                .map(|r| r.read(cx).thread.clone())
 229                        });
 230
 231                    if let Some(thread) = thread {
 232                        AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
 233                    }
 234                })
 235                .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
 236                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 237                        workspace.focus_panel::<AgentPanel>(window, cx);
 238                        panel.update(cx, |panel, cx| {
 239                            panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
 240                        });
 241                    }
 242                })
 243                .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
 244                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 245                        workspace.focus_panel::<AgentPanel>(window, cx);
 246                        panel.update(cx, |panel, cx| {
 247                            panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
 248                        });
 249                    }
 250                })
 251                .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
 252                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 253                        workspace.focus_panel::<AgentPanel>(window, cx);
 254                        panel.update(cx, |panel, cx| {
 255                            panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
 256                        });
 257                    }
 258                })
 259                .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {
 260                    AcpOnboardingModal::toggle(workspace, window, cx)
 261                })
 262                .register_action(
 263                    |workspace, _: &OpenClaudeAgentOnboardingModal, window, cx| {
 264                        ClaudeCodeOnboardingModal::toggle(workspace, window, cx)
 265                    },
 266                )
 267                .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
 268                    window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
 269                    window.refresh();
 270                })
 271                .register_action(|workspace, _: &ResetTrialUpsell, _window, cx| {
 272                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 273                        panel.update(cx, |panel, _| {
 274                            panel
 275                                .on_boarding_upsell_dismissed
 276                                .store(false, Ordering::Release);
 277                        });
 278                    }
 279                    OnboardingUpsell::set_dismissed(false, cx);
 280                })
 281                .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
 282                    TrialEndUpsell::set_dismissed(false, cx);
 283                })
 284                .register_action(|workspace, _: &ResetAgentZoom, window, cx| {
 285                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 286                        panel.update(cx, |panel, cx| {
 287                            panel.reset_agent_zoom(window, cx);
 288                        });
 289                    }
 290                })
 291                .register_action(|workspace, _: &CopyThreadToClipboard, window, cx| {
 292                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 293                        panel.update(cx, |panel, cx| {
 294                            panel.copy_thread_to_clipboard(window, cx);
 295                        });
 296                    }
 297                })
 298                .register_action(|workspace, _: &LoadThreadFromClipboard, window, cx| {
 299                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 300                        workspace.focus_panel::<AgentPanel>(window, cx);
 301                        panel.update(cx, |panel, cx| {
 302                            panel.load_thread_from_clipboard(window, cx);
 303                        });
 304                    }
 305                })
 306                .register_action(|workspace, action: &ReviewBranchDiff, window, cx| {
 307                    let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 308                        return;
 309                    };
 310
 311                    let mention_uri = MentionUri::GitDiff {
 312                        base_ref: action.base_ref.to_string(),
 313                    };
 314                    let diff_uri = mention_uri.to_uri().to_string();
 315
 316                    let content_blocks = vec![
 317                        acp::ContentBlock::Text(acp::TextContent::new(
 318                            "Please review this branch diff carefully. Point out any issues, \
 319                             potential bugs, or improvement opportunities you find.\n\n"
 320                                .to_string(),
 321                        )),
 322                        acp::ContentBlock::Resource(acp::EmbeddedResource::new(
 323                            acp::EmbeddedResourceResource::TextResourceContents(
 324                                acp::TextResourceContents::new(
 325                                    action.diff_text.to_string(),
 326                                    diff_uri,
 327                                ),
 328                            ),
 329                        )),
 330                    ];
 331
 332                    workspace.focus_panel::<AgentPanel>(window, cx);
 333
 334                    panel.update(cx, |panel, cx| {
 335                        panel.external_thread(
 336                            None,
 337                            None,
 338                            None,
 339                            None,
 340                            Some(AgentInitialContent::ContentBlock {
 341                                blocks: content_blocks,
 342                                auto_submit: true,
 343                            }),
 344                            true,
 345                            window,
 346                            cx,
 347                        );
 348                    });
 349                })
 350                .register_action(
 351                    |workspace, action: &ResolveConflictsWithAgent, window, cx| {
 352                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 353                            return;
 354                        };
 355
 356                        let content_blocks = build_conflict_resolution_prompt(&action.conflicts);
 357
 358                        workspace.focus_panel::<AgentPanel>(window, cx);
 359
 360                        panel.update(cx, |panel, cx| {
 361                            panel.external_thread(
 362                                None,
 363                                None,
 364                                None,
 365                                None,
 366                                Some(AgentInitialContent::ContentBlock {
 367                                    blocks: content_blocks,
 368                                    auto_submit: true,
 369                                }),
 370                                true,
 371                                window,
 372                                cx,
 373                            );
 374                        });
 375                    },
 376                )
 377                .register_action(
 378                    |workspace, action: &ResolveConflictedFilesWithAgent, window, cx| {
 379                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 380                            return;
 381                        };
 382
 383                        let content_blocks =
 384                            build_conflicted_files_resolution_prompt(&action.conflicted_file_paths);
 385
 386                        workspace.focus_panel::<AgentPanel>(window, cx);
 387
 388                        panel.update(cx, |panel, cx| {
 389                            panel.external_thread(
 390                                None,
 391                                None,
 392                                None,
 393                                None,
 394                                Some(AgentInitialContent::ContentBlock {
 395                                    blocks: content_blocks,
 396                                    auto_submit: true,
 397                                }),
 398                                true,
 399                                window,
 400                                cx,
 401                            );
 402                        });
 403                    },
 404                )
 405                .register_action(|workspace, action: &StartThreadIn, _window, cx| {
 406                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 407                        panel.update(cx, |panel, cx| {
 408                            panel.set_start_thread_in(action, cx);
 409                        });
 410                    }
 411                })
 412                .register_action(|workspace, _: &CycleStartThreadIn, _window, cx| {
 413                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 414                        panel.update(cx, |panel, cx| {
 415                            panel.cycle_start_thread_in(cx);
 416                        });
 417                    }
 418                });
 419        },
 420    )
 421    .detach();
 422}
 423
 424fn conflict_resource_block(conflict: &ConflictContent) -> acp::ContentBlock {
 425    let mention_uri = MentionUri::MergeConflict {
 426        file_path: conflict.file_path.clone(),
 427    };
 428    acp::ContentBlock::Resource(acp::EmbeddedResource::new(
 429        acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents::new(
 430            conflict.conflict_text.clone(),
 431            mention_uri.to_uri().to_string(),
 432        )),
 433    ))
 434}
 435
 436fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::ContentBlock> {
 437    if conflicts.is_empty() {
 438        return Vec::new();
 439    }
 440
 441    let mut blocks = Vec::new();
 442
 443    if conflicts.len() == 1 {
 444        let conflict = &conflicts[0];
 445
 446        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 447            "Please resolve the following merge conflict in ",
 448        )));
 449        let mention = MentionUri::File {
 450            abs_path: PathBuf::from(conflict.file_path.clone()),
 451        };
 452        blocks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
 453            mention.name(),
 454            mention.to_uri(),
 455        )));
 456
 457        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 458            indoc::formatdoc!(
 459                "\nThe conflict is between branch `{ours}` (ours) and `{theirs}` (theirs).
 460
 461                Analyze both versions carefully and resolve the conflict by editing \
 462                the file directly. Choose the resolution that best preserves the intent \
 463                of both changes, or combine them if appropriate.
 464
 465                ",
 466                ours = conflict.ours_branch_name,
 467                theirs = conflict.theirs_branch_name,
 468            ),
 469        )));
 470    } else {
 471        let n = conflicts.len();
 472        let unique_files: HashSet<&str> = conflicts.iter().map(|c| c.file_path.as_str()).collect();
 473        let ours = &conflicts[0].ours_branch_name;
 474        let theirs = &conflicts[0].theirs_branch_name;
 475        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 476            indoc::formatdoc!(
 477                "Please resolve all {n} merge conflicts below.
 478
 479                The conflicts are between branch `{ours}` (ours) and `{theirs}` (theirs).
 480
 481                For each conflict, analyze both versions carefully and resolve them \
 482                by editing the file{suffix} directly. Choose resolutions that best preserve \
 483                the intent of both changes, or combine them if appropriate.
 484
 485                ",
 486                suffix = if unique_files.len() > 1 { "s" } else { "" },
 487            ),
 488        )));
 489    }
 490
 491    for conflict in conflicts {
 492        blocks.push(conflict_resource_block(conflict));
 493    }
 494
 495    blocks
 496}
 497
 498fn build_conflicted_files_resolution_prompt(
 499    conflicted_file_paths: &[String],
 500) -> Vec<acp::ContentBlock> {
 501    if conflicted_file_paths.is_empty() {
 502        return Vec::new();
 503    }
 504
 505    let instruction = indoc::indoc!(
 506        "The following files have unresolved merge conflicts. Please open each \
 507         file, find the conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`), \
 508         and resolve every conflict by editing the files directly.
 509
 510         Choose resolutions that best preserve the intent of both changes, \
 511         or combine them if appropriate.
 512
 513         Files with conflicts:
 514         ",
 515    );
 516
 517    let mut content = vec![acp::ContentBlock::Text(acp::TextContent::new(instruction))];
 518    for path in conflicted_file_paths {
 519        let mention = MentionUri::File {
 520            abs_path: PathBuf::from(path),
 521        };
 522        content.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
 523            mention.name(),
 524            mention.to_uri(),
 525        )));
 526        content.push(acp::ContentBlock::Text(acp::TextContent::new("\n")));
 527    }
 528    content
 529}
 530
 531#[derive(Clone, Debug, PartialEq, Eq)]
 532enum History {
 533    AgentThreads { view: Entity<ThreadHistoryView> },
 534    TextThreads,
 535}
 536
 537enum ActiveView {
 538    Uninitialized,
 539    AgentThread {
 540        conversation_view: Entity<ConversationView>,
 541    },
 542    TextThread {
 543        text_thread_editor: Entity<TextThreadEditor>,
 544        title_editor: Entity<Editor>,
 545        buffer_search_bar: Entity<BufferSearchBar>,
 546        _subscriptions: Vec<gpui::Subscription>,
 547    },
 548    History {
 549        history: History,
 550    },
 551    Configuration,
 552}
 553
 554enum WhichFontSize {
 555    AgentFont,
 556    BufferFont,
 557    None,
 558}
 559
 560// TODO unify this with ExternalAgent
 561#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
 562pub enum AgentType {
 563    #[default]
 564    NativeAgent,
 565    TextThread,
 566    Custom {
 567        #[serde(rename = "name")]
 568        id: AgentId,
 569    },
 570}
 571
 572impl AgentType {
 573    pub fn is_native(&self) -> bool {
 574        matches!(self, Self::NativeAgent)
 575    }
 576
 577    fn label(&self) -> SharedString {
 578        match self {
 579            Self::NativeAgent | Self::TextThread => "Zed Agent".into(),
 580            Self::Custom { id, .. } => id.0.clone(),
 581        }
 582    }
 583
 584    fn icon(&self) -> Option<IconName> {
 585        match self {
 586            Self::NativeAgent | Self::TextThread => None,
 587            Self::Custom { .. } => Some(IconName::Sparkle),
 588        }
 589    }
 590}
 591
 592impl From<Agent> for AgentType {
 593    fn from(value: Agent) -> Self {
 594        match value {
 595            Agent::Custom { id } => Self::Custom { id },
 596            Agent::NativeAgent => Self::NativeAgent,
 597        }
 598    }
 599}
 600
 601impl StartThreadIn {
 602    fn label(&self) -> SharedString {
 603        match self {
 604            Self::LocalProject => "Current Project".into(),
 605            Self::NewWorktree => "New Worktree".into(),
 606        }
 607    }
 608}
 609
 610#[derive(Clone, Debug)]
 611#[allow(dead_code)]
 612pub enum WorktreeCreationStatus {
 613    Creating,
 614    Error(SharedString),
 615}
 616
 617impl ActiveView {
 618    pub fn which_font_size_used(&self) -> WhichFontSize {
 619        match self {
 620            ActiveView::Uninitialized
 621            | ActiveView::AgentThread { .. }
 622            | ActiveView::History { .. } => WhichFontSize::AgentFont,
 623            ActiveView::TextThread { .. } => WhichFontSize::BufferFont,
 624            ActiveView::Configuration => WhichFontSize::None,
 625        }
 626    }
 627
 628    pub fn text_thread(
 629        text_thread_editor: Entity<TextThreadEditor>,
 630        language_registry: Arc<LanguageRegistry>,
 631        window: &mut Window,
 632        cx: &mut App,
 633    ) -> Self {
 634        let title = text_thread_editor.read(cx).title(cx).to_string();
 635
 636        let editor = cx.new(|cx| {
 637            let mut editor = Editor::single_line(window, cx);
 638            editor.set_text(title, window, cx);
 639            editor
 640        });
 641
 642        // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
 643        // cause a custom summary to be set. The presence of this custom summary would cause
 644        // summarization to not happen.
 645        let mut suppress_first_edit = true;
 646
 647        let subscriptions = vec![
 648            window.subscribe(&editor, cx, {
 649                {
 650                    let text_thread_editor = text_thread_editor.clone();
 651                    move |editor, event, window, cx| match event {
 652                        EditorEvent::BufferEdited => {
 653                            if suppress_first_edit {
 654                                suppress_first_edit = false;
 655                                return;
 656                            }
 657                            let new_summary = editor.read(cx).text(cx);
 658
 659                            text_thread_editor.update(cx, |text_thread_editor, cx| {
 660                                text_thread_editor
 661                                    .text_thread()
 662                                    .update(cx, |text_thread, cx| {
 663                                        text_thread.set_custom_summary(new_summary, cx);
 664                                    })
 665                            })
 666                        }
 667                        EditorEvent::Blurred => {
 668                            if editor.read(cx).text(cx).is_empty() {
 669                                let summary = text_thread_editor
 670                                    .read(cx)
 671                                    .text_thread()
 672                                    .read(cx)
 673                                    .summary()
 674                                    .or_default();
 675
 676                                editor.update(cx, |editor, cx| {
 677                                    editor.set_text(summary, window, cx);
 678                                });
 679                            }
 680                        }
 681                        _ => {}
 682                    }
 683                }
 684            }),
 685            window.subscribe(&text_thread_editor.read(cx).text_thread().clone(), cx, {
 686                let editor = editor.clone();
 687                move |text_thread, event, window, cx| match event {
 688                    TextThreadEvent::SummaryGenerated => {
 689                        let summary = text_thread.read(cx).summary().or_default();
 690
 691                        editor.update(cx, |editor, cx| {
 692                            editor.set_text(summary, window, cx);
 693                        })
 694                    }
 695                    TextThreadEvent::PathChanged { .. } => {}
 696                    _ => {}
 697                }
 698            }),
 699        ];
 700
 701        let buffer_search_bar =
 702            cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
 703        buffer_search_bar.update(cx, |buffer_search_bar, cx| {
 704            buffer_search_bar.set_active_pane_item(Some(&text_thread_editor), window, cx)
 705        });
 706
 707        Self::TextThread {
 708            text_thread_editor,
 709            title_editor: editor,
 710            buffer_search_bar,
 711            _subscriptions: subscriptions,
 712        }
 713    }
 714}
 715
 716pub struct AgentPanel {
 717    workspace: WeakEntity<Workspace>,
 718    /// Workspace id is used as a database key
 719    workspace_id: Option<WorkspaceId>,
 720    user_store: Entity<UserStore>,
 721    project: Entity<Project>,
 722    fs: Arc<dyn Fs>,
 723    language_registry: Arc<LanguageRegistry>,
 724    text_thread_history: Entity<TextThreadHistory>,
 725    thread_store: Entity<ThreadStore>,
 726    text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
 727    prompt_store: Option<Entity<PromptStore>>,
 728    connection_store: Entity<AgentConnectionStore>,
 729    context_server_registry: Entity<ContextServerRegistry>,
 730    configuration: Option<Entity<AgentConfiguration>>,
 731    configuration_subscription: Option<Subscription>,
 732    focus_handle: FocusHandle,
 733    active_view: ActiveView,
 734    previous_view: Option<ActiveView>,
 735    background_threads: HashMap<acp::SessionId, Entity<ConversationView>>,
 736    new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
 737    start_thread_in_menu_handle: PopoverMenuHandle<ContextMenu>,
 738    agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
 739    agent_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
 740    agent_navigation_menu: Option<Entity<ContextMenu>>,
 741    _extension_subscription: Option<Subscription>,
 742    width: Option<Pixels>,
 743    height: Option<Pixels>,
 744    zoomed: bool,
 745    pending_serialization: Option<Task<Result<()>>>,
 746    onboarding: Entity<AgentPanelOnboarding>,
 747    selected_agent_type: AgentType,
 748    start_thread_in: StartThreadIn,
 749    worktree_creation_status: Option<WorktreeCreationStatus>,
 750    _thread_view_subscription: Option<Subscription>,
 751    _active_thread_focus_subscription: Option<Subscription>,
 752    _worktree_creation_task: Option<Task<()>>,
 753    show_trust_workspace_message: bool,
 754    last_configuration_error_telemetry: Option<String>,
 755    on_boarding_upsell_dismissed: AtomicBool,
 756    _active_view_observation: Option<Subscription>,
 757}
 758
 759impl AgentPanel {
 760    fn serialize(&mut self, cx: &mut App) {
 761        let Some(workspace_id) = self.workspace_id else {
 762            return;
 763        };
 764
 765        let width = self.width;
 766        let selected_agent_type = self.selected_agent_type.clone();
 767        let start_thread_in = Some(self.start_thread_in);
 768
 769        let last_active_thread = self.active_agent_thread(cx).map(|thread| {
 770            let thread = thread.read(cx);
 771            let title = thread.title();
 772            let work_dirs = thread.work_dirs().cloned();
 773            SerializedActiveThread {
 774                session_id: thread.session_id().0.to_string(),
 775                agent_type: self.selected_agent_type.clone(),
 776                title: if title.as_ref() != DEFAULT_THREAD_TITLE {
 777                    Some(title.to_string())
 778                } else {
 779                    None
 780                },
 781                work_dirs: work_dirs.map(|dirs| dirs.serialize()),
 782            }
 783        });
 784
 785        self.pending_serialization = Some(cx.background_spawn(async move {
 786            save_serialized_panel(
 787                workspace_id,
 788                SerializedAgentPanel {
 789                    width,
 790                    selected_agent: Some(selected_agent_type),
 791                    last_active_thread,
 792                    start_thread_in,
 793                },
 794            )
 795            .await?;
 796            anyhow::Ok(())
 797        }));
 798    }
 799
 800    pub fn load(
 801        workspace: WeakEntity<Workspace>,
 802        prompt_builder: Arc<PromptBuilder>,
 803        mut cx: AsyncWindowContext,
 804    ) -> Task<Result<Entity<Self>>> {
 805        let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
 806        cx.spawn(async move |cx| {
 807            let prompt_store = match prompt_store {
 808                Ok(prompt_store) => prompt_store.await.ok(),
 809                Err(_) => None,
 810            };
 811            let workspace_id = workspace
 812                .read_with(cx, |workspace, _| workspace.database_id())
 813                .ok()
 814                .flatten();
 815
 816            let serialized_panel = cx
 817                .background_spawn(async move {
 818                    workspace_id
 819                        .and_then(read_serialized_panel)
 820                        .or_else(read_legacy_serialized_panel)
 821                })
 822                .await;
 823
 824            let slash_commands = Arc::new(SlashCommandWorkingSet::default());
 825            let text_thread_store = workspace
 826                .update(cx, |workspace, cx| {
 827                    let project = workspace.project().clone();
 828                    assistant_text_thread::TextThreadStore::new(
 829                        project,
 830                        prompt_builder,
 831                        slash_commands,
 832                        cx,
 833                    )
 834                })?
 835                .await?;
 836
 837            let last_active_thread = if let Some(thread_info) = serialized_panel
 838                .as_ref()
 839                .and_then(|p| p.last_active_thread.as_ref())
 840            {
 841                if thread_info.agent_type.is_native() {
 842                    let session_id = acp::SessionId::new(thread_info.session_id.clone());
 843                    let load_result = cx.update(|_window, cx| {
 844                        let thread_store = ThreadStore::global(cx);
 845                        thread_store.update(cx, |store, cx| store.load_thread(session_id, cx))
 846                    });
 847                    let thread_exists = if let Ok(task) = load_result {
 848                        task.await.ok().flatten().is_some()
 849                    } else {
 850                        false
 851                    };
 852                    if thread_exists {
 853                        Some(thread_info)
 854                    } else {
 855                        log::warn!(
 856                            "last active thread {} not found in database, skipping restoration",
 857                            thread_info.session_id
 858                        );
 859                        None
 860                    }
 861                } else {
 862                    Some(thread_info)
 863                }
 864            } else {
 865                None
 866            };
 867
 868            let panel = workspace.update_in(cx, |workspace, window, cx| {
 869                let panel =
 870                    cx.new(|cx| Self::new(workspace, text_thread_store, prompt_store, window, cx));
 871
 872                if let Some(serialized_panel) = &serialized_panel {
 873                    panel.update(cx, |panel, cx| {
 874                        panel.width = serialized_panel.width.map(|w| w.round());
 875                        if let Some(selected_agent) = serialized_panel.selected_agent.clone() {
 876                            panel.selected_agent_type = selected_agent;
 877                        }
 878                        if let Some(start_thread_in) = serialized_panel.start_thread_in {
 879                            let is_worktree_flag_enabled =
 880                                cx.has_flag::<AgentV2FeatureFlag>();
 881                            let is_valid = match &start_thread_in {
 882                                StartThreadIn::LocalProject => true,
 883                                StartThreadIn::NewWorktree => {
 884                                    let project = panel.project.read(cx);
 885                                    is_worktree_flag_enabled && !project.is_via_collab()
 886                                }
 887                            };
 888                            if is_valid {
 889                                panel.start_thread_in = start_thread_in;
 890                            } else {
 891                                log::info!(
 892                                    "deserialized start_thread_in {:?} is no longer valid, falling back to LocalProject",
 893                                    start_thread_in,
 894                                );
 895                            }
 896                        }
 897                        cx.notify();
 898                    });
 899                }
 900
 901                if let Some(thread_info) = last_active_thread {
 902                    let agent_type = thread_info.agent_type.clone();
 903                    panel.update(cx, |panel, cx| {
 904                        panel.selected_agent_type = agent_type;
 905                        if let Some(agent) = panel.selected_agent() {
 906                            panel.load_agent_thread(
 907                                agent,
 908                                thread_info.session_id.clone().into(),
 909                                thread_info.work_dirs.as_ref().map(|dirs| PathList::deserialize(dirs)),
 910                                thread_info.title.as_ref().map(|t| t.clone().into()),
 911                                false,
 912                                window,
 913                                cx,
 914                            );
 915                        }
 916                    });
 917                }
 918                panel
 919            })?;
 920
 921            Ok(panel)
 922        })
 923    }
 924
 925    pub(crate) fn new(
 926        workspace: &Workspace,
 927        text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
 928        prompt_store: Option<Entity<PromptStore>>,
 929        window: &mut Window,
 930        cx: &mut Context<Self>,
 931    ) -> Self {
 932        let fs = workspace.app_state().fs.clone();
 933        let user_store = workspace.app_state().user_store.clone();
 934        let project = workspace.project();
 935        let language_registry = project.read(cx).languages().clone();
 936        let client = workspace.client().clone();
 937        let workspace_id = workspace.database_id();
 938        let workspace = workspace.weak_handle();
 939
 940        let context_server_registry =
 941            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 942
 943        let thread_store = ThreadStore::global(cx);
 944        let text_thread_history =
 945            cx.new(|cx| TextThreadHistory::new(text_thread_store.clone(), window, cx));
 946
 947        cx.subscribe_in(
 948            &text_thread_history,
 949            window,
 950            |this, _, event, window, cx| match event {
 951                TextThreadHistoryEvent::Open(thread) => {
 952                    this.open_saved_text_thread(thread.path.clone(), window, cx)
 953                        .detach_and_log_err(cx);
 954                }
 955            },
 956        )
 957        .detach();
 958
 959        let active_view = ActiveView::Uninitialized;
 960
 961        let weak_panel = cx.entity().downgrade();
 962
 963        window.defer(cx, move |window, cx| {
 964            let panel = weak_panel.clone();
 965            let agent_navigation_menu =
 966                ContextMenu::build_persistent(window, cx, move |mut menu, window, cx| {
 967                    if let Some(panel) = panel.upgrade() {
 968                        if let Some(history) = panel
 969                            .update(cx, |panel, cx| panel.history_for_selected_agent(window, cx))
 970                        {
 971                            let view_all_label = match history {
 972                                History::AgentThreads { .. } => "View All",
 973                                History::TextThreads => "View All Text Threads",
 974                            };
 975                            menu = Self::populate_recently_updated_menu_section(
 976                                menu, panel, history, cx,
 977                            );
 978                            menu = menu.action(view_all_label, Box::new(OpenHistory));
 979                        }
 980                    }
 981
 982                    menu = menu
 983                        .fixed_width(px(320.).into())
 984                        .keep_open_on_confirm(false)
 985                        .key_context("NavigationMenu");
 986
 987                    menu
 988                });
 989            weak_panel
 990                .update(cx, |panel, cx| {
 991                    cx.subscribe_in(
 992                        &agent_navigation_menu,
 993                        window,
 994                        |_, menu, _: &DismissEvent, window, cx| {
 995                            menu.update(cx, |menu, _| {
 996                                menu.clear_selected();
 997                            });
 998                            cx.focus_self(window);
 999                        },
1000                    )
1001                    .detach();
1002                    panel.agent_navigation_menu = Some(agent_navigation_menu);
1003                })
1004                .ok();
1005        });
1006
1007        let weak_panel = cx.entity().downgrade();
1008        let onboarding = cx.new(|cx| {
1009            AgentPanelOnboarding::new(
1010                user_store.clone(),
1011                client,
1012                move |_window, cx| {
1013                    weak_panel
1014                        .update(cx, |panel, _| {
1015                            panel
1016                                .on_boarding_upsell_dismissed
1017                                .store(true, Ordering::Release);
1018                        })
1019                        .ok();
1020                    OnboardingUpsell::set_dismissed(true, cx);
1021                },
1022                cx,
1023            )
1024        });
1025
1026        // Subscribe to extension events to sync agent servers when extensions change
1027        let extension_subscription = if let Some(extension_events) = ExtensionEvents::try_global(cx)
1028        {
1029            Some(
1030                cx.subscribe(&extension_events, |this, _source, event, cx| match event {
1031                    extension::Event::ExtensionInstalled(_)
1032                    | extension::Event::ExtensionUninstalled(_)
1033                    | extension::Event::ExtensionsInstalledChanged => {
1034                        this.sync_agent_servers_from_extensions(cx);
1035                    }
1036                    _ => {}
1037                }),
1038            )
1039        } else {
1040            None
1041        };
1042
1043        let connection_store = cx.new(|cx| {
1044            let mut store = AgentConnectionStore::new(project.clone(), cx);
1045            // Register the native agent right away, so that it is available for
1046            // the inline assistant etc.
1047            store.request_connection(
1048                Agent::NativeAgent,
1049                Agent::NativeAgent.server(fs.clone(), thread_store.clone()),
1050                cx,
1051            );
1052            store
1053        });
1054        let mut panel = Self {
1055            workspace_id,
1056            active_view,
1057            workspace,
1058            user_store,
1059            project: project.clone(),
1060            fs: fs.clone(),
1061            language_registry,
1062            text_thread_store,
1063            prompt_store,
1064            connection_store,
1065            configuration: None,
1066            configuration_subscription: None,
1067            focus_handle: cx.focus_handle(),
1068            context_server_registry,
1069            previous_view: None,
1070            background_threads: HashMap::default(),
1071            new_thread_menu_handle: PopoverMenuHandle::default(),
1072            start_thread_in_menu_handle: PopoverMenuHandle::default(),
1073            agent_panel_menu_handle: PopoverMenuHandle::default(),
1074            agent_navigation_menu_handle: PopoverMenuHandle::default(),
1075            agent_navigation_menu: None,
1076            _extension_subscription: extension_subscription,
1077            width: None,
1078            height: None,
1079            zoomed: false,
1080            pending_serialization: None,
1081            onboarding,
1082            text_thread_history,
1083            thread_store,
1084            selected_agent_type: AgentType::default(),
1085            start_thread_in: StartThreadIn::default(),
1086            worktree_creation_status: None,
1087            _thread_view_subscription: None,
1088            _active_thread_focus_subscription: None,
1089            _worktree_creation_task: None,
1090            show_trust_workspace_message: false,
1091            last_configuration_error_telemetry: None,
1092            on_boarding_upsell_dismissed: AtomicBool::new(OnboardingUpsell::dismissed()),
1093            _active_view_observation: None,
1094        };
1095
1096        // Initial sync of agent servers from extensions
1097        panel.sync_agent_servers_from_extensions(cx);
1098        panel
1099    }
1100
1101    pub fn toggle_focus(
1102        workspace: &mut Workspace,
1103        _: &ToggleFocus,
1104        window: &mut Window,
1105        cx: &mut Context<Workspace>,
1106    ) {
1107        if workspace
1108            .panel::<Self>(cx)
1109            .is_some_and(|panel| panel.read(cx).enabled(cx))
1110        {
1111            workspace.toggle_panel_focus::<Self>(window, cx);
1112        }
1113    }
1114
1115    pub fn toggle(
1116        workspace: &mut Workspace,
1117        _: &Toggle,
1118        window: &mut Window,
1119        cx: &mut Context<Workspace>,
1120    ) {
1121        if workspace
1122            .panel::<Self>(cx)
1123            .is_some_and(|panel| panel.read(cx).enabled(cx))
1124        {
1125            if !workspace.toggle_panel_focus::<Self>(window, cx) {
1126                workspace.close_panel::<Self>(window, cx);
1127            }
1128        }
1129    }
1130
1131    pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
1132        &self.prompt_store
1133    }
1134
1135    pub fn thread_store(&self) -> &Entity<ThreadStore> {
1136        &self.thread_store
1137    }
1138
1139    pub fn connection_store(&self) -> &Entity<AgentConnectionStore> {
1140        &self.connection_store
1141    }
1142
1143    pub fn open_thread(
1144        &mut self,
1145        session_id: acp::SessionId,
1146        work_dirs: Option<PathList>,
1147        title: Option<SharedString>,
1148        window: &mut Window,
1149        cx: &mut Context<Self>,
1150    ) {
1151        self.external_thread(
1152            Some(crate::Agent::NativeAgent),
1153            Some(session_id),
1154            work_dirs,
1155            title,
1156            None,
1157            true,
1158            window,
1159            cx,
1160        );
1161    }
1162
1163    pub(crate) fn context_server_registry(&self) -> &Entity<ContextServerRegistry> {
1164        &self.context_server_registry
1165    }
1166
1167    pub fn is_visible(workspace: &Entity<Workspace>, cx: &App) -> bool {
1168        let workspace_read = workspace.read(cx);
1169
1170        workspace_read
1171            .panel::<AgentPanel>(cx)
1172            .map(|panel| {
1173                let panel_id = Entity::entity_id(&panel);
1174
1175                workspace_read.all_docks().iter().any(|dock| {
1176                    dock.read(cx)
1177                        .visible_panel()
1178                        .is_some_and(|visible_panel| visible_panel.panel_id() == panel_id)
1179                })
1180            })
1181            .unwrap_or(false)
1182    }
1183
1184    pub fn active_conversation(&self) -> Option<&Entity<ConversationView>> {
1185        match &self.active_view {
1186            ActiveView::AgentThread {
1187                conversation_view, ..
1188            } => Some(conversation_view),
1189            ActiveView::Uninitialized
1190            | ActiveView::TextThread { .. }
1191            | ActiveView::History { .. }
1192            | ActiveView::Configuration => None,
1193        }
1194    }
1195
1196    pub fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
1197        self.new_agent_thread(AgentType::NativeAgent, window, cx);
1198    }
1199
1200    fn new_native_agent_thread_from_summary(
1201        &mut self,
1202        action: &NewNativeAgentThreadFromSummary,
1203        window: &mut Window,
1204        cx: &mut Context<Self>,
1205    ) {
1206        let session_id = action.from_session_id.clone();
1207
1208        let Some(history) = self
1209            .connection_store
1210            .read(cx)
1211            .entry(&Agent::NativeAgent)
1212            .and_then(|e| e.read(cx).history().cloned())
1213        else {
1214            debug_panic!("Native agent is not registered");
1215            return;
1216        };
1217
1218        cx.spawn_in(window, async move |this, cx| {
1219            this.update_in(cx, |this, window, cx| {
1220                let thread = history
1221                    .read(cx)
1222                    .session_for_id(&session_id)
1223                    .context("Session not found")?;
1224
1225                this.external_thread(
1226                    Some(Agent::NativeAgent),
1227                    None,
1228                    None,
1229                    None,
1230                    Some(AgentInitialContent::ThreadSummary {
1231                        session_id: thread.session_id,
1232                        title: thread.title,
1233                    }),
1234                    true,
1235                    window,
1236                    cx,
1237                );
1238                anyhow::Ok(())
1239            })
1240        })
1241        .detach_and_log_err(cx);
1242    }
1243
1244    fn new_text_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1245        telemetry::event!("Agent Thread Started", agent = "zed-text");
1246
1247        let context = self
1248            .text_thread_store
1249            .update(cx, |context_store, cx| context_store.create(cx));
1250        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1251            .log_err()
1252            .flatten();
1253
1254        let text_thread_editor = cx.new(|cx| {
1255            let mut editor = TextThreadEditor::for_text_thread(
1256                context,
1257                self.fs.clone(),
1258                self.workspace.clone(),
1259                self.project.clone(),
1260                lsp_adapter_delegate,
1261                window,
1262                cx,
1263            );
1264            editor.insert_default_prompt(window, cx);
1265            editor
1266        });
1267
1268        if self.selected_agent_type != AgentType::TextThread {
1269            self.selected_agent_type = AgentType::TextThread;
1270            self.serialize(cx);
1271        }
1272
1273        self.set_active_view(
1274            ActiveView::text_thread(
1275                text_thread_editor.clone(),
1276                self.language_registry.clone(),
1277                window,
1278                cx,
1279            ),
1280            true,
1281            window,
1282            cx,
1283        );
1284        text_thread_editor.focus_handle(cx).focus(window, cx);
1285    }
1286
1287    fn external_thread(
1288        &mut self,
1289        agent_choice: Option<crate::Agent>,
1290        resume_session_id: Option<acp::SessionId>,
1291        work_dirs: Option<PathList>,
1292        title: Option<SharedString>,
1293        initial_content: Option<AgentInitialContent>,
1294        focus: bool,
1295        window: &mut Window,
1296        cx: &mut Context<Self>,
1297    ) {
1298        let workspace = self.workspace.clone();
1299        let project = self.project.clone();
1300        let fs = self.fs.clone();
1301        let is_via_collab = self.project.read(cx).is_via_collab();
1302
1303        const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
1304
1305        #[derive(Serialize, Deserialize)]
1306        struct LastUsedExternalAgent {
1307            agent: crate::Agent,
1308        }
1309
1310        let thread_store = self.thread_store.clone();
1311
1312        if let Some(agent) = agent_choice {
1313            cx.background_spawn({
1314                let agent = agent.clone();
1315                async move {
1316                    if let Some(serialized) =
1317                        serde_json::to_string(&LastUsedExternalAgent { agent }).log_err()
1318                    {
1319                        KEY_VALUE_STORE
1320                            .write_kvp(LAST_USED_EXTERNAL_AGENT_KEY.to_string(), serialized)
1321                            .await
1322                            .log_err();
1323                    }
1324                }
1325            })
1326            .detach();
1327
1328            let server = agent.server(fs, thread_store);
1329            self.create_agent_thread(
1330                server,
1331                resume_session_id,
1332                work_dirs,
1333                title,
1334                initial_content,
1335                workspace,
1336                project,
1337                agent,
1338                focus,
1339                window,
1340                cx,
1341            );
1342        } else {
1343            cx.spawn_in(window, async move |this, cx| {
1344                let ext_agent = if is_via_collab {
1345                    Agent::NativeAgent
1346                } else {
1347                    cx.background_spawn(async move {
1348                        KEY_VALUE_STORE.read_kvp(LAST_USED_EXTERNAL_AGENT_KEY)
1349                    })
1350                    .await
1351                    .log_err()
1352                    .flatten()
1353                    .and_then(|value| {
1354                        serde_json::from_str::<LastUsedExternalAgent>(&value).log_err()
1355                    })
1356                    .map(|agent| agent.agent)
1357                    .unwrap_or(Agent::NativeAgent)
1358                };
1359
1360                let server = ext_agent.server(fs, thread_store);
1361                this.update_in(cx, |agent_panel, window, cx| {
1362                    agent_panel.create_agent_thread(
1363                        server,
1364                        resume_session_id,
1365                        work_dirs,
1366                        title,
1367                        initial_content,
1368                        workspace,
1369                        project,
1370                        ext_agent,
1371                        focus,
1372                        window,
1373                        cx,
1374                    );
1375                })?;
1376
1377                anyhow::Ok(())
1378            })
1379            .detach_and_log_err(cx);
1380        }
1381    }
1382
1383    fn deploy_rules_library(
1384        &mut self,
1385        action: &OpenRulesLibrary,
1386        _window: &mut Window,
1387        cx: &mut Context<Self>,
1388    ) {
1389        open_rules_library(
1390            self.language_registry.clone(),
1391            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
1392            Rc::new(|| {
1393                Rc::new(SlashCommandCompletionProvider::new(
1394                    Arc::new(SlashCommandWorkingSet::default()),
1395                    None,
1396                    None,
1397                ))
1398            }),
1399            action
1400                .prompt_to_select
1401                .map(|uuid| UserPromptId(uuid).into()),
1402            cx,
1403        )
1404        .detach_and_log_err(cx);
1405    }
1406
1407    fn expand_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1408        let Some(conversation_view) = self.active_conversation() else {
1409            return;
1410        };
1411
1412        let Some(active_thread) = conversation_view.read(cx).active_thread().cloned() else {
1413            return;
1414        };
1415
1416        active_thread.update(cx, |active_thread, cx| {
1417            active_thread.expand_message_editor(&ExpandMessageEditor, window, cx);
1418            active_thread.focus_handle(cx).focus(window, cx);
1419        })
1420    }
1421
1422    fn has_history_for_selected_agent(&self, cx: &App) -> bool {
1423        match &self.selected_agent_type {
1424            AgentType::TextThread | AgentType::NativeAgent => true,
1425            AgentType::Custom { id } => {
1426                let agent = Agent::Custom { id: id.clone() };
1427                self.connection_store
1428                    .read(cx)
1429                    .entry(&agent)
1430                    .map_or(false, |entry| entry.read(cx).history().is_some())
1431            }
1432        }
1433    }
1434
1435    fn history_for_selected_agent(
1436        &self,
1437        window: &mut Window,
1438        cx: &mut Context<Self>,
1439    ) -> Option<History> {
1440        match &self.selected_agent_type {
1441            AgentType::TextThread => Some(History::TextThreads),
1442            AgentType::NativeAgent => {
1443                let history = self
1444                    .connection_store
1445                    .read(cx)
1446                    .entry(&Agent::NativeAgent)?
1447                    .read(cx)
1448                    .history()?
1449                    .clone();
1450
1451                Some(History::AgentThreads {
1452                    view: self.create_thread_history_view(Agent::NativeAgent, history, window, cx),
1453                })
1454            }
1455            AgentType::Custom { id, .. } => {
1456                let agent = Agent::Custom { id: id.clone() };
1457                let history = self
1458                    .connection_store
1459                    .read(cx)
1460                    .entry(&agent)?
1461                    .read(cx)
1462                    .history()?
1463                    .clone();
1464                if history.read(cx).has_session_list() {
1465                    Some(History::AgentThreads {
1466                        view: self.create_thread_history_view(agent, history, window, cx),
1467                    })
1468                } else {
1469                    None
1470                }
1471            }
1472        }
1473    }
1474
1475    fn create_thread_history_view(
1476        &self,
1477        agent: Agent,
1478        history: Entity<ThreadHistory>,
1479        window: &mut Window,
1480        cx: &mut Context<Self>,
1481    ) -> Entity<ThreadHistoryView> {
1482        let view = cx.new(|cx| ThreadHistoryView::new(history.clone(), window, cx));
1483        cx.subscribe_in(
1484            &view,
1485            window,
1486            move |this, _, event, window, cx| match event {
1487                ThreadHistoryViewEvent::Open(thread) => {
1488                    this.load_agent_thread(
1489                        agent.clone(),
1490                        thread.session_id.clone(),
1491                        thread.work_dirs.clone(),
1492                        thread.title.clone(),
1493                        true,
1494                        window,
1495                        cx,
1496                    );
1497                }
1498            },
1499        )
1500        .detach();
1501        view
1502    }
1503
1504    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1505        let Some(history) = self.history_for_selected_agent(window, cx) else {
1506            return;
1507        };
1508
1509        if let ActiveView::History {
1510            history: active_history,
1511        } = &self.active_view
1512        {
1513            if active_history == &history {
1514                if let Some(previous_view) = self.previous_view.take() {
1515                    self.set_active_view(previous_view, true, window, cx);
1516                }
1517                return;
1518            }
1519        }
1520
1521        self.set_active_view(ActiveView::History { history }, true, window, cx);
1522        cx.notify();
1523    }
1524
1525    pub(crate) fn open_saved_text_thread(
1526        &mut self,
1527        path: Arc<Path>,
1528        window: &mut Window,
1529        cx: &mut Context<Self>,
1530    ) -> Task<Result<()>> {
1531        let text_thread_task = self
1532            .text_thread_store
1533            .update(cx, |store, cx| store.open_local(path, cx));
1534        cx.spawn_in(window, async move |this, cx| {
1535            let text_thread = text_thread_task.await?;
1536            this.update_in(cx, |this, window, cx| {
1537                this.open_text_thread(text_thread, window, cx);
1538            })
1539        })
1540    }
1541
1542    pub(crate) fn open_text_thread(
1543        &mut self,
1544        text_thread: Entity<TextThread>,
1545        window: &mut Window,
1546        cx: &mut Context<Self>,
1547    ) {
1548        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
1549            .log_err()
1550            .flatten();
1551        let editor = cx.new(|cx| {
1552            TextThreadEditor::for_text_thread(
1553                text_thread,
1554                self.fs.clone(),
1555                self.workspace.clone(),
1556                self.project.clone(),
1557                lsp_adapter_delegate,
1558                window,
1559                cx,
1560            )
1561        });
1562
1563        if self.selected_agent_type != AgentType::TextThread {
1564            self.selected_agent_type = AgentType::TextThread;
1565            self.serialize(cx);
1566        }
1567
1568        self.set_active_view(
1569            ActiveView::text_thread(editor, self.language_registry.clone(), window, cx),
1570            true,
1571            window,
1572            cx,
1573        );
1574    }
1575
1576    pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1577        match self.active_view {
1578            ActiveView::Configuration | ActiveView::History { .. } => {
1579                if let Some(previous_view) = self.previous_view.take() {
1580                    self.set_active_view(previous_view, true, window, cx);
1581                }
1582                cx.notify();
1583            }
1584            _ => {}
1585        }
1586    }
1587
1588    pub fn toggle_navigation_menu(
1589        &mut self,
1590        _: &ToggleNavigationMenu,
1591        window: &mut Window,
1592        cx: &mut Context<Self>,
1593    ) {
1594        if !self.has_history_for_selected_agent(cx) {
1595            return;
1596        }
1597        self.agent_navigation_menu_handle.toggle(window, cx);
1598    }
1599
1600    pub fn toggle_options_menu(
1601        &mut self,
1602        _: &ToggleOptionsMenu,
1603        window: &mut Window,
1604        cx: &mut Context<Self>,
1605    ) {
1606        self.agent_panel_menu_handle.toggle(window, cx);
1607    }
1608
1609    pub fn toggle_new_thread_menu(
1610        &mut self,
1611        _: &ToggleNewThreadMenu,
1612        window: &mut Window,
1613        cx: &mut Context<Self>,
1614    ) {
1615        self.new_thread_menu_handle.toggle(window, cx);
1616    }
1617
1618    pub fn increase_font_size(
1619        &mut self,
1620        action: &IncreaseBufferFontSize,
1621        _: &mut Window,
1622        cx: &mut Context<Self>,
1623    ) {
1624        self.handle_font_size_action(action.persist, px(1.0), cx);
1625    }
1626
1627    pub fn decrease_font_size(
1628        &mut self,
1629        action: &DecreaseBufferFontSize,
1630        _: &mut Window,
1631        cx: &mut Context<Self>,
1632    ) {
1633        self.handle_font_size_action(action.persist, px(-1.0), cx);
1634    }
1635
1636    fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1637        match self.active_view.which_font_size_used() {
1638            WhichFontSize::AgentFont => {
1639                if persist {
1640                    update_settings_file(self.fs.clone(), cx, move |settings, cx| {
1641                        let agent_ui_font_size =
1642                            ThemeSettings::get_global(cx).agent_ui_font_size(cx) + delta;
1643                        let agent_buffer_font_size =
1644                            ThemeSettings::get_global(cx).agent_buffer_font_size(cx) + delta;
1645
1646                        let _ = settings
1647                            .theme
1648                            .agent_ui_font_size
1649                            .insert(f32::from(theme::clamp_font_size(agent_ui_font_size)).into());
1650                        let _ = settings.theme.agent_buffer_font_size.insert(
1651                            f32::from(theme::clamp_font_size(agent_buffer_font_size)).into(),
1652                        );
1653                    });
1654                } else {
1655                    theme::adjust_agent_ui_font_size(cx, |size| size + delta);
1656                    theme::adjust_agent_buffer_font_size(cx, |size| size + delta);
1657                }
1658            }
1659            WhichFontSize::BufferFont => {
1660                // Prompt editor uses the buffer font size, so allow the action to propagate to the
1661                // default handler that changes that font size.
1662                cx.propagate();
1663            }
1664            WhichFontSize::None => {}
1665        }
1666    }
1667
1668    pub fn reset_font_size(
1669        &mut self,
1670        action: &ResetBufferFontSize,
1671        _: &mut Window,
1672        cx: &mut Context<Self>,
1673    ) {
1674        if action.persist {
1675            update_settings_file(self.fs.clone(), cx, move |settings, _| {
1676                settings.theme.agent_ui_font_size = None;
1677                settings.theme.agent_buffer_font_size = None;
1678            });
1679        } else {
1680            theme::reset_agent_ui_font_size(cx);
1681            theme::reset_agent_buffer_font_size(cx);
1682        }
1683    }
1684
1685    pub fn reset_agent_zoom(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1686        theme::reset_agent_ui_font_size(cx);
1687        theme::reset_agent_buffer_font_size(cx);
1688    }
1689
1690    pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1691        if self.zoomed {
1692            cx.emit(PanelEvent::ZoomOut);
1693        } else {
1694            if !self.focus_handle(cx).contains_focused(window, cx) {
1695                cx.focus_self(window);
1696            }
1697            cx.emit(PanelEvent::ZoomIn);
1698        }
1699    }
1700
1701    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1702        let agent_server_store = self.project.read(cx).agent_server_store().clone();
1703        let context_server_store = self.project.read(cx).context_server_store();
1704        let fs = self.fs.clone();
1705
1706        self.set_active_view(ActiveView::Configuration, true, window, cx);
1707        self.configuration = Some(cx.new(|cx| {
1708            AgentConfiguration::new(
1709                fs,
1710                agent_server_store,
1711                context_server_store,
1712                self.context_server_registry.clone(),
1713                self.language_registry.clone(),
1714                self.workspace.clone(),
1715                window,
1716                cx,
1717            )
1718        }));
1719
1720        if let Some(configuration) = self.configuration.as_ref() {
1721            self.configuration_subscription = Some(cx.subscribe_in(
1722                configuration,
1723                window,
1724                Self::handle_agent_configuration_event,
1725            ));
1726
1727            configuration.focus_handle(cx).focus(window, cx);
1728        }
1729    }
1730
1731    pub(crate) fn open_active_thread_as_markdown(
1732        &mut self,
1733        _: &OpenActiveThreadAsMarkdown,
1734        window: &mut Window,
1735        cx: &mut Context<Self>,
1736    ) {
1737        if let Some(workspace) = self.workspace.upgrade()
1738            && let Some(conversation_view) = self.active_conversation()
1739            && let Some(active_thread) = conversation_view.read(cx).active_thread().cloned()
1740        {
1741            active_thread.update(cx, |thread, cx| {
1742                thread
1743                    .open_thread_as_markdown(workspace, window, cx)
1744                    .detach_and_log_err(cx);
1745            });
1746        }
1747    }
1748
1749    fn copy_thread_to_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1750        let Some(thread) = self.active_native_agent_thread(cx) else {
1751            Self::show_deferred_toast(&self.workspace, "No active native thread to copy", cx);
1752            return;
1753        };
1754
1755        let workspace = self.workspace.clone();
1756        let load_task = thread.read(cx).to_db(cx);
1757
1758        cx.spawn_in(window, async move |_this, cx| {
1759            let db_thread = load_task.await;
1760            let shared_thread = SharedThread::from_db_thread(&db_thread);
1761            let thread_data = shared_thread.to_bytes()?;
1762            let encoded = base64::Engine::encode(&base64::prelude::BASE64_STANDARD, &thread_data);
1763
1764            cx.update(|_window, cx| {
1765                cx.write_to_clipboard(ClipboardItem::new_string(encoded));
1766                if let Some(workspace) = workspace.upgrade() {
1767                    workspace.update(cx, |workspace, cx| {
1768                        struct ThreadCopiedToast;
1769                        workspace.show_toast(
1770                            workspace::Toast::new(
1771                                workspace::notifications::NotificationId::unique::<ThreadCopiedToast>(),
1772                                "Thread copied to clipboard (base64 encoded)",
1773                            )
1774                            .autohide(),
1775                            cx,
1776                        );
1777                    });
1778                }
1779            })?;
1780
1781            anyhow::Ok(())
1782        })
1783        .detach_and_log_err(cx);
1784    }
1785
1786    fn show_deferred_toast(
1787        workspace: &WeakEntity<workspace::Workspace>,
1788        message: &'static str,
1789        cx: &mut App,
1790    ) {
1791        let workspace = workspace.clone();
1792        cx.defer(move |cx| {
1793            if let Some(workspace) = workspace.upgrade() {
1794                workspace.update(cx, |workspace, cx| {
1795                    struct ClipboardToast;
1796                    workspace.show_toast(
1797                        workspace::Toast::new(
1798                            workspace::notifications::NotificationId::unique::<ClipboardToast>(),
1799                            message,
1800                        )
1801                        .autohide(),
1802                        cx,
1803                    );
1804                });
1805            }
1806        });
1807    }
1808
1809    fn load_thread_from_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1810        let Some(clipboard) = cx.read_from_clipboard() else {
1811            Self::show_deferred_toast(&self.workspace, "No clipboard content available", cx);
1812            return;
1813        };
1814
1815        let Some(encoded) = clipboard.text() else {
1816            Self::show_deferred_toast(&self.workspace, "Clipboard does not contain text", cx);
1817            return;
1818        };
1819
1820        let thread_data = match base64::Engine::decode(&base64::prelude::BASE64_STANDARD, &encoded)
1821        {
1822            Ok(data) => data,
1823            Err(_) => {
1824                Self::show_deferred_toast(
1825                    &self.workspace,
1826                    "Failed to decode clipboard content (expected base64)",
1827                    cx,
1828                );
1829                return;
1830            }
1831        };
1832
1833        let shared_thread = match SharedThread::from_bytes(&thread_data) {
1834            Ok(thread) => thread,
1835            Err(_) => {
1836                Self::show_deferred_toast(
1837                    &self.workspace,
1838                    "Failed to parse thread data from clipboard",
1839                    cx,
1840                );
1841                return;
1842            }
1843        };
1844
1845        let db_thread = shared_thread.to_db_thread();
1846        let session_id = acp::SessionId::new(uuid::Uuid::new_v4().to_string());
1847        let thread_store = self.thread_store.clone();
1848        let title = db_thread.title.clone();
1849        let workspace = self.workspace.clone();
1850
1851        cx.spawn_in(window, async move |this, cx| {
1852            thread_store
1853                .update(&mut cx.clone(), |store, cx| {
1854                    store.save_thread(session_id.clone(), db_thread, Default::default(), cx)
1855                })
1856                .await?;
1857
1858            this.update_in(cx, |this, window, cx| {
1859                this.open_thread(session_id, None, Some(title), window, cx);
1860            })?;
1861
1862            this.update_in(cx, |_, _window, cx| {
1863                if let Some(workspace) = workspace.upgrade() {
1864                    workspace.update(cx, |workspace, cx| {
1865                        struct ThreadLoadedToast;
1866                        workspace.show_toast(
1867                            workspace::Toast::new(
1868                                workspace::notifications::NotificationId::unique::<ThreadLoadedToast>(),
1869                                "Thread loaded from clipboard",
1870                            )
1871                            .autohide(),
1872                            cx,
1873                        );
1874                    });
1875                }
1876            })?;
1877
1878            anyhow::Ok(())
1879        })
1880        .detach_and_log_err(cx);
1881    }
1882
1883    fn handle_agent_configuration_event(
1884        &mut self,
1885        _entity: &Entity<AgentConfiguration>,
1886        event: &AssistantConfigurationEvent,
1887        window: &mut Window,
1888        cx: &mut Context<Self>,
1889    ) {
1890        match event {
1891            AssistantConfigurationEvent::NewThread(provider) => {
1892                if LanguageModelRegistry::read_global(cx)
1893                    .default_model()
1894                    .is_none_or(|model| model.provider.id() != provider.id())
1895                    && let Some(model) = provider.default_model(cx)
1896                {
1897                    update_settings_file(self.fs.clone(), cx, move |settings, _| {
1898                        let provider = model.provider_id().0.to_string();
1899                        let enable_thinking = model.supports_thinking();
1900                        let effort = model
1901                            .default_effort_level()
1902                            .map(|effort| effort.value.to_string());
1903                        let model = model.id().0.to_string();
1904                        settings
1905                            .agent
1906                            .get_or_insert_default()
1907                            .set_model(LanguageModelSelection {
1908                                provider: LanguageModelProviderSetting(provider),
1909                                model,
1910                                enable_thinking,
1911                                effort,
1912                            })
1913                    });
1914                }
1915
1916                self.new_thread(&NewThread, window, cx);
1917                if let Some((thread, model)) = self
1918                    .active_native_agent_thread(cx)
1919                    .zip(provider.default_model(cx))
1920                {
1921                    thread.update(cx, |thread, cx| {
1922                        thread.set_model(model, cx);
1923                    });
1924                }
1925            }
1926        }
1927    }
1928
1929    pub fn active_conversation_view(&self) -> Option<&Entity<ConversationView>> {
1930        match &self.active_view {
1931            ActiveView::AgentThread { conversation_view } => Some(conversation_view),
1932            _ => None,
1933        }
1934    }
1935
1936    pub fn active_thread_view(&self, cx: &App) -> Option<Entity<ThreadView>> {
1937        let server_view = self.active_conversation_view()?;
1938        server_view.read(cx).active_thread().cloned()
1939    }
1940
1941    pub fn active_agent_thread(&self, cx: &App) -> Option<Entity<AcpThread>> {
1942        match &self.active_view {
1943            ActiveView::AgentThread {
1944                conversation_view, ..
1945            } => conversation_view
1946                .read(cx)
1947                .active_thread()
1948                .map(|r| r.read(cx).thread.clone()),
1949            _ => None,
1950        }
1951    }
1952
1953    /// Returns the primary thread views for all retained connections: the
1954    pub fn is_background_thread(&self, session_id: &acp::SessionId) -> bool {
1955        self.background_threads.contains_key(session_id)
1956    }
1957
1958    /// active thread plus any background threads that are still running or
1959    /// completed but unseen.
1960    pub fn parent_threads(&self, cx: &App) -> Vec<Entity<ThreadView>> {
1961        let mut views = Vec::new();
1962
1963        if let Some(server_view) = self.active_conversation_view() {
1964            if let Some(thread_view) = server_view.read(cx).parent_thread(cx) {
1965                views.push(thread_view);
1966            }
1967        }
1968
1969        for server_view in self.background_threads.values() {
1970            if let Some(thread_view) = server_view.read(cx).parent_thread(cx) {
1971                views.push(thread_view);
1972            }
1973        }
1974
1975        views
1976    }
1977
1978    fn retain_running_thread(&mut self, old_view: ActiveView, cx: &mut Context<Self>) {
1979        let ActiveView::AgentThread { conversation_view } = old_view else {
1980            return;
1981        };
1982
1983        let Some(thread_view) = conversation_view.read(cx).parent_thread(cx) else {
1984            return;
1985        };
1986
1987        let thread = &thread_view.read(cx).thread;
1988        let (status, session_id) = {
1989            let thread = thread.read(cx);
1990            (thread.status(), thread.session_id().clone())
1991        };
1992
1993        if status != ThreadStatus::Generating {
1994            return;
1995        }
1996
1997        self.background_threads
1998            .insert(session_id, conversation_view);
1999    }
2000
2001    pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
2002        match &self.active_view {
2003            ActiveView::AgentThread {
2004                conversation_view, ..
2005            } => conversation_view.read(cx).as_native_thread(cx),
2006            _ => None,
2007        }
2008    }
2009
2010    pub(crate) fn active_text_thread_editor(&self) -> Option<Entity<TextThreadEditor>> {
2011        match &self.active_view {
2012            ActiveView::TextThread {
2013                text_thread_editor, ..
2014            } => Some(text_thread_editor.clone()),
2015            _ => None,
2016        }
2017    }
2018
2019    fn set_active_view(
2020        &mut self,
2021        new_view: ActiveView,
2022        focus: bool,
2023        window: &mut Window,
2024        cx: &mut Context<Self>,
2025    ) {
2026        let was_in_agent_history = matches!(
2027            self.active_view,
2028            ActiveView::History {
2029                history: History::AgentThreads { .. }
2030            }
2031        );
2032        let current_is_uninitialized = matches!(self.active_view, ActiveView::Uninitialized);
2033        let current_is_history = matches!(self.active_view, ActiveView::History { .. });
2034        let new_is_history = matches!(new_view, ActiveView::History { .. });
2035
2036        let current_is_config = matches!(self.active_view, ActiveView::Configuration);
2037        let new_is_config = matches!(new_view, ActiveView::Configuration);
2038
2039        let current_is_overlay = current_is_history || current_is_config;
2040        let new_is_overlay = new_is_history || new_is_config;
2041
2042        if current_is_uninitialized || (current_is_overlay && !new_is_overlay) {
2043            self.active_view = new_view;
2044        } else if !current_is_overlay && new_is_overlay {
2045            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
2046        } else {
2047            let old_view = std::mem::replace(&mut self.active_view, new_view);
2048            if !new_is_overlay {
2049                if let Some(previous) = self.previous_view.take() {
2050                    self.retain_running_thread(previous, cx);
2051                }
2052            }
2053            self.retain_running_thread(old_view, cx);
2054        }
2055
2056        // Subscribe to the active ThreadView's events (e.g. FirstSendRequested)
2057        // so the panel can intercept the first send for worktree creation.
2058        // Re-subscribe whenever the ConnectionView changes, since the inner
2059        // ThreadView may have been replaced (e.g. navigating between threads).
2060        self._active_view_observation = match &self.active_view {
2061            ActiveView::AgentThread { conversation_view } => {
2062                self._thread_view_subscription =
2063                    Self::subscribe_to_active_thread_view(conversation_view, window, cx);
2064                let focus_handle = conversation_view.focus_handle(cx);
2065                self._active_thread_focus_subscription =
2066                    Some(cx.on_focus_in(&focus_handle, window, |_this, _window, cx| {
2067                        cx.emit(AgentPanelEvent::ThreadFocused);
2068                        cx.notify();
2069                    }));
2070                Some(cx.observe_in(
2071                    conversation_view,
2072                    window,
2073                    |this, server_view, window, cx| {
2074                        this._thread_view_subscription =
2075                            Self::subscribe_to_active_thread_view(&server_view, window, cx);
2076                        cx.emit(AgentPanelEvent::ActiveViewChanged);
2077                        this.serialize(cx);
2078                        cx.notify();
2079                    },
2080                ))
2081            }
2082            _ => {
2083                self._thread_view_subscription = None;
2084                self._active_thread_focus_subscription = None;
2085                None
2086            }
2087        };
2088
2089        if let ActiveView::History { history } = &self.active_view {
2090            if !was_in_agent_history && let History::AgentThreads { view } = history {
2091                view.update(cx, |view, cx| {
2092                    view.history()
2093                        .update(cx, |history, cx| history.refresh_full_history(cx))
2094                });
2095            }
2096        }
2097
2098        if focus {
2099            self.focus_handle(cx).focus(window, cx);
2100        }
2101        cx.emit(AgentPanelEvent::ActiveViewChanged);
2102    }
2103
2104    fn populate_recently_updated_menu_section(
2105        mut menu: ContextMenu,
2106        panel: Entity<Self>,
2107        history: History,
2108        cx: &mut Context<ContextMenu>,
2109    ) -> ContextMenu {
2110        match history {
2111            History::AgentThreads { view } => {
2112                let entries = view
2113                    .read(cx)
2114                    .history()
2115                    .read(cx)
2116                    .sessions()
2117                    .iter()
2118                    .take(RECENTLY_UPDATED_MENU_LIMIT)
2119                    .cloned()
2120                    .collect::<Vec<_>>();
2121
2122                if entries.is_empty() {
2123                    return menu;
2124                }
2125
2126                menu = menu.header("Recently Updated");
2127
2128                for entry in entries {
2129                    let title = entry
2130                        .title
2131                        .as_ref()
2132                        .filter(|title| !title.is_empty())
2133                        .cloned()
2134                        .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE));
2135
2136                    menu = menu.entry(title, None, {
2137                        let panel = panel.downgrade();
2138                        let entry = entry.clone();
2139                        move |window, cx| {
2140                            let entry = entry.clone();
2141                            panel
2142                                .update(cx, move |this, cx| {
2143                                    if let Some(agent) = this.selected_agent() {
2144                                        this.load_agent_thread(
2145                                            agent,
2146                                            entry.session_id.clone(),
2147                                            entry.work_dirs.clone(),
2148                                            entry.title.clone(),
2149                                            true,
2150                                            window,
2151                                            cx,
2152                                        );
2153                                    }
2154                                })
2155                                .ok();
2156                        }
2157                    });
2158                }
2159            }
2160            History::TextThreads => {
2161                let entries = panel
2162                    .read(cx)
2163                    .text_thread_store
2164                    .read(cx)
2165                    .ordered_text_threads()
2166                    .take(RECENTLY_UPDATED_MENU_LIMIT)
2167                    .cloned()
2168                    .collect::<Vec<_>>();
2169
2170                if entries.is_empty() {
2171                    return menu;
2172                }
2173
2174                menu = menu.header("Recent Text Threads");
2175
2176                for entry in entries {
2177                    let title = if entry.title.is_empty() {
2178                        SharedString::new_static(DEFAULT_THREAD_TITLE)
2179                    } else {
2180                        entry.title.clone()
2181                    };
2182
2183                    menu = menu.entry(title, None, {
2184                        let panel = panel.downgrade();
2185                        let entry = entry.clone();
2186                        move |window, cx| {
2187                            let path = entry.path.clone();
2188                            panel
2189                                .update(cx, move |this, cx| {
2190                                    this.open_saved_text_thread(path.clone(), window, cx)
2191                                        .detach_and_log_err(cx);
2192                                })
2193                                .ok();
2194                        }
2195                    });
2196                }
2197            }
2198        }
2199
2200        menu.separator()
2201    }
2202
2203    fn subscribe_to_active_thread_view(
2204        server_view: &Entity<ConversationView>,
2205        window: &mut Window,
2206        cx: &mut Context<Self>,
2207    ) -> Option<Subscription> {
2208        server_view.read(cx).active_thread().cloned().map(|tv| {
2209            cx.subscribe_in(
2210                &tv,
2211                window,
2212                |this, view, event: &AcpThreadViewEvent, window, cx| match event {
2213                    AcpThreadViewEvent::FirstSendRequested { content } => {
2214                        this.handle_first_send_requested(view.clone(), content.clone(), window, cx);
2215                    }
2216                },
2217            )
2218        })
2219    }
2220
2221    pub fn start_thread_in(&self) -> &StartThreadIn {
2222        &self.start_thread_in
2223    }
2224
2225    fn set_start_thread_in(&mut self, action: &StartThreadIn, cx: &mut Context<Self>) {
2226        if matches!(action, StartThreadIn::NewWorktree) && !cx.has_flag::<AgentV2FeatureFlag>() {
2227            return;
2228        }
2229
2230        let new_target = match *action {
2231            StartThreadIn::LocalProject => StartThreadIn::LocalProject,
2232            StartThreadIn::NewWorktree => {
2233                if !self.project_has_git_repository(cx) {
2234                    log::error!(
2235                        "set_start_thread_in: cannot use NewWorktree without a git repository"
2236                    );
2237                    return;
2238                }
2239                if self.project.read(cx).is_via_collab() {
2240                    log::error!("set_start_thread_in: cannot use NewWorktree in a collab project");
2241                    return;
2242                }
2243                StartThreadIn::NewWorktree
2244            }
2245        };
2246        self.start_thread_in = new_target;
2247        self.serialize(cx);
2248        cx.notify();
2249    }
2250
2251    fn cycle_start_thread_in(&mut self, cx: &mut Context<Self>) {
2252        let next = match self.start_thread_in {
2253            StartThreadIn::LocalProject => StartThreadIn::NewWorktree,
2254            StartThreadIn::NewWorktree => StartThreadIn::LocalProject,
2255        };
2256        self.set_start_thread_in(&next, cx);
2257    }
2258
2259    fn reset_start_thread_in_to_default(&mut self, cx: &mut Context<Self>) {
2260        use settings::{NewThreadLocation, Settings};
2261        let default = AgentSettings::get_global(cx).new_thread_location;
2262        let start_thread_in = match default {
2263            NewThreadLocation::LocalProject => StartThreadIn::LocalProject,
2264            NewThreadLocation::NewWorktree => StartThreadIn::NewWorktree,
2265        };
2266        if self.start_thread_in != start_thread_in {
2267            self.start_thread_in = start_thread_in;
2268            self.serialize(cx);
2269            cx.notify();
2270        }
2271    }
2272
2273    pub(crate) fn selected_agent(&self) -> Option<Agent> {
2274        match &self.selected_agent_type {
2275            AgentType::NativeAgent => Some(Agent::NativeAgent),
2276            AgentType::Custom { id } => Some(Agent::Custom { id: id.clone() }),
2277            AgentType::TextThread => None,
2278        }
2279    }
2280
2281    fn sync_agent_servers_from_extensions(&mut self, cx: &mut Context<Self>) {
2282        if let Some(extension_store) = ExtensionStore::try_global(cx) {
2283            let (manifests, extensions_dir) = {
2284                let store = extension_store.read(cx);
2285                let installed = store.installed_extensions();
2286                let manifests: Vec<_> = installed
2287                    .iter()
2288                    .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
2289                    .collect();
2290                let extensions_dir = paths::extensions_dir().join("installed");
2291                (manifests, extensions_dir)
2292            };
2293
2294            self.project.update(cx, |project, cx| {
2295                project.agent_server_store().update(cx, |store, cx| {
2296                    let manifest_refs: Vec<_> = manifests
2297                        .iter()
2298                        .map(|(id, manifest)| (id.as_ref(), manifest.as_ref()))
2299                        .collect();
2300                    store.sync_extension_agents(manifest_refs, extensions_dir, cx);
2301                });
2302            });
2303        }
2304    }
2305
2306    pub fn new_agent_thread_with_external_source_prompt(
2307        &mut self,
2308        external_source_prompt: Option<ExternalSourcePrompt>,
2309        window: &mut Window,
2310        cx: &mut Context<Self>,
2311    ) {
2312        self.external_thread(
2313            None,
2314            None,
2315            None,
2316            None,
2317            external_source_prompt.map(AgentInitialContent::from),
2318            true,
2319            window,
2320            cx,
2321        );
2322    }
2323
2324    pub fn new_agent_thread(
2325        &mut self,
2326        agent: AgentType,
2327        window: &mut Window,
2328        cx: &mut Context<Self>,
2329    ) {
2330        self.reset_start_thread_in_to_default(cx);
2331        self.new_agent_thread_inner(agent, true, window, cx);
2332    }
2333
2334    fn new_agent_thread_inner(
2335        &mut self,
2336        agent: AgentType,
2337        focus: bool,
2338        window: &mut Window,
2339        cx: &mut Context<Self>,
2340    ) {
2341        match agent {
2342            AgentType::TextThread => {
2343                window.dispatch_action(NewTextThread.boxed_clone(), cx);
2344            }
2345            AgentType::NativeAgent => self.external_thread(
2346                Some(crate::Agent::NativeAgent),
2347                None,
2348                None,
2349                None,
2350                None,
2351                focus,
2352                window,
2353                cx,
2354            ),
2355            AgentType::Custom { id } => self.external_thread(
2356                Some(crate::Agent::Custom { id }),
2357                None,
2358                None,
2359                None,
2360                None,
2361                focus,
2362                window,
2363                cx,
2364            ),
2365        }
2366    }
2367
2368    pub fn load_agent_thread(
2369        &mut self,
2370        agent: Agent,
2371        session_id: acp::SessionId,
2372        work_dirs: Option<PathList>,
2373        title: Option<SharedString>,
2374        focus: bool,
2375        window: &mut Window,
2376        cx: &mut Context<Self>,
2377    ) {
2378        if let Some(conversation_view) = self.background_threads.remove(&session_id) {
2379            self.set_active_view(
2380                ActiveView::AgentThread { conversation_view },
2381                focus,
2382                window,
2383                cx,
2384            );
2385            return;
2386        }
2387
2388        if let ActiveView::AgentThread { conversation_view } = &self.active_view {
2389            if conversation_view
2390                .read(cx)
2391                .active_thread()
2392                .map(|t| t.read(cx).id.clone())
2393                == Some(session_id.clone())
2394            {
2395                cx.emit(AgentPanelEvent::ActiveViewChanged);
2396                return;
2397            }
2398        }
2399
2400        if let Some(ActiveView::AgentThread { conversation_view }) = &self.previous_view {
2401            if conversation_view
2402                .read(cx)
2403                .active_thread()
2404                .map(|t| t.read(cx).id.clone())
2405                == Some(session_id.clone())
2406            {
2407                let view = self.previous_view.take().unwrap();
2408                self.set_active_view(view, focus, window, cx);
2409                return;
2410            }
2411        }
2412
2413        self.external_thread(
2414            Some(agent),
2415            Some(session_id),
2416            work_dirs,
2417            title,
2418            None,
2419            focus,
2420            window,
2421            cx,
2422        );
2423    }
2424
2425    pub(crate) fn create_agent_thread(
2426        &mut self,
2427        server: Rc<dyn AgentServer>,
2428        resume_session_id: Option<acp::SessionId>,
2429        work_dirs: Option<PathList>,
2430        title: Option<SharedString>,
2431        initial_content: Option<AgentInitialContent>,
2432        workspace: WeakEntity<Workspace>,
2433        project: Entity<Project>,
2434        ext_agent: Agent,
2435        focus: bool,
2436        window: &mut Window,
2437        cx: &mut Context<Self>,
2438    ) {
2439        let selected_agent = AgentType::from(ext_agent.clone());
2440        if self.selected_agent_type != selected_agent {
2441            self.selected_agent_type = selected_agent;
2442            self.serialize(cx);
2443        }
2444        let thread_store = server
2445            .clone()
2446            .downcast::<agent::NativeAgentServer>()
2447            .is_some()
2448            .then(|| self.thread_store.clone());
2449
2450        let connection_store = self.connection_store.clone();
2451
2452        let conversation_view = cx.new(|cx| {
2453            crate::ConversationView::new(
2454                server,
2455                connection_store,
2456                ext_agent,
2457                resume_session_id,
2458                work_dirs,
2459                title,
2460                initial_content,
2461                workspace.clone(),
2462                project,
2463                thread_store,
2464                self.prompt_store.clone(),
2465                window,
2466                cx,
2467            )
2468        });
2469
2470        cx.observe(&conversation_view, |this, server_view, cx| {
2471            let is_active = this
2472                .active_conversation_view()
2473                .is_some_and(|active| active.entity_id() == server_view.entity_id());
2474            if is_active {
2475                cx.emit(AgentPanelEvent::ActiveViewChanged);
2476                this.serialize(cx);
2477            } else {
2478                cx.emit(AgentPanelEvent::BackgroundThreadChanged);
2479            }
2480            cx.notify();
2481        })
2482        .detach();
2483
2484        self.set_active_view(
2485            ActiveView::AgentThread { conversation_view },
2486            focus,
2487            window,
2488            cx,
2489        );
2490    }
2491
2492    fn active_thread_has_messages(&self, cx: &App) -> bool {
2493        self.active_agent_thread(cx)
2494            .is_some_and(|thread| !thread.read(cx).entries().is_empty())
2495    }
2496
2497    fn handle_first_send_requested(
2498        &mut self,
2499        thread_view: Entity<ThreadView>,
2500        content: Vec<acp::ContentBlock>,
2501        window: &mut Window,
2502        cx: &mut Context<Self>,
2503    ) {
2504        if self.start_thread_in == StartThreadIn::NewWorktree {
2505            self.handle_worktree_creation_requested(content, window, cx);
2506        } else {
2507            cx.defer_in(window, move |_this, window, cx| {
2508                thread_view.update(cx, |thread_view, cx| {
2509                    let editor = thread_view.message_editor.clone();
2510                    thread_view.send_impl(editor, window, cx);
2511                });
2512            });
2513        }
2514    }
2515
2516    // TODO: The mapping from workspace root paths to git repositories needs a
2517    // unified approach across the codebase: this method, `sidebar::is_root_repo`,
2518    // thread persistence (which PathList is saved to the database), and thread
2519    // querying (which PathList is used to read threads back). All of these need
2520    // to agree on how repos are resolved for a given workspace, especially in
2521    // multi-root and nested-repo configurations.
2522    /// Partitions the project's visible worktrees into git-backed repositories
2523    /// and plain (non-git) paths. Git repos will have worktrees created for
2524    /// them; non-git paths are carried over to the new workspace as-is.
2525    ///
2526    /// When multiple worktrees map to the same repository, the most specific
2527    /// match wins (deepest work directory path), with a deterministic
2528    /// tie-break on entity id. Each repository appears at most once.
2529    fn classify_worktrees(
2530        &self,
2531        cx: &App,
2532    ) -> (Vec<Entity<project::git_store::Repository>>, Vec<PathBuf>) {
2533        let project = &self.project;
2534        let repositories = project.read(cx).repositories(cx).clone();
2535        let mut git_repos: Vec<Entity<project::git_store::Repository>> = Vec::new();
2536        let mut non_git_paths: Vec<PathBuf> = Vec::new();
2537        let mut seen_repo_ids = std::collections::HashSet::new();
2538
2539        for worktree in project.read(cx).visible_worktrees(cx) {
2540            let wt_path = worktree.read(cx).abs_path();
2541
2542            let matching_repo = repositories
2543                .iter()
2544                .filter_map(|(id, repo)| {
2545                    let work_dir = repo.read(cx).work_directory_abs_path.clone();
2546                    if wt_path.starts_with(work_dir.as_ref())
2547                        || work_dir.starts_with(wt_path.as_ref())
2548                    {
2549                        Some((*id, repo.clone(), work_dir.as_ref().components().count()))
2550                    } else {
2551                        None
2552                    }
2553                })
2554                .max_by(
2555                    |(left_id, _left_repo, left_depth), (right_id, _right_repo, right_depth)| {
2556                        left_depth
2557                            .cmp(right_depth)
2558                            .then_with(|| left_id.cmp(right_id))
2559                    },
2560                );
2561
2562            if let Some((id, repo, _)) = matching_repo {
2563                if seen_repo_ids.insert(id) {
2564                    git_repos.push(repo);
2565                }
2566            } else {
2567                non_git_paths.push(wt_path.to_path_buf());
2568            }
2569        }
2570
2571        (git_repos, non_git_paths)
2572    }
2573
2574    /// Kicks off an async git-worktree creation for each repository. Returns:
2575    ///
2576    /// - `creation_infos`: a vec of `(repo, new_path, receiver)` tuples—the
2577    ///   receiver resolves once the git worktree command finishes.
2578    /// - `path_remapping`: `(old_work_dir, new_worktree_path)` pairs used
2579    ///   later to remap open editor tabs into the new workspace.
2580    fn start_worktree_creations(
2581        git_repos: &[Entity<project::git_store::Repository>],
2582        branch_name: &str,
2583        worktree_directory_setting: &str,
2584        cx: &mut Context<Self>,
2585    ) -> Result<(
2586        Vec<(
2587            Entity<project::git_store::Repository>,
2588            PathBuf,
2589            futures::channel::oneshot::Receiver<Result<()>>,
2590        )>,
2591        Vec<(PathBuf, PathBuf)>,
2592    )> {
2593        let mut creation_infos = Vec::new();
2594        let mut path_remapping = Vec::new();
2595
2596        for repo in git_repos {
2597            let (work_dir, new_path, receiver) = repo.update(cx, |repo, _cx| {
2598                let original_repo = repo.original_repo_abs_path.clone();
2599                let directory =
2600                    validate_worktree_directory(&original_repo, worktree_directory_setting)?;
2601                let new_path = directory.join(branch_name);
2602                let receiver = repo.create_worktree(branch_name.to_string(), directory, None);
2603                let work_dir = repo.work_directory_abs_path.clone();
2604                anyhow::Ok((work_dir, new_path, receiver))
2605            })?;
2606            path_remapping.push((work_dir.to_path_buf(), new_path.clone()));
2607            creation_infos.push((repo.clone(), new_path, receiver));
2608        }
2609
2610        Ok((creation_infos, path_remapping))
2611    }
2612
2613    /// Waits for every in-flight worktree creation to complete. If any
2614    /// creation fails, all successfully-created worktrees are rolled back
2615    /// (removed) so the project isn't left in a half-migrated state.
2616    async fn await_and_rollback_on_failure(
2617        creation_infos: Vec<(
2618            Entity<project::git_store::Repository>,
2619            PathBuf,
2620            futures::channel::oneshot::Receiver<Result<()>>,
2621        )>,
2622        cx: &mut AsyncWindowContext,
2623    ) -> Result<Vec<PathBuf>> {
2624        let mut created_paths: Vec<PathBuf> = Vec::new();
2625        let mut repos_and_paths: Vec<(Entity<project::git_store::Repository>, PathBuf)> =
2626            Vec::new();
2627        let mut first_error: Option<anyhow::Error> = None;
2628
2629        for (repo, new_path, receiver) in creation_infos {
2630            match receiver.await {
2631                Ok(Ok(())) => {
2632                    created_paths.push(new_path.clone());
2633                    repos_and_paths.push((repo, new_path));
2634                }
2635                Ok(Err(err)) => {
2636                    if first_error.is_none() {
2637                        first_error = Some(err);
2638                    }
2639                }
2640                Err(_canceled) => {
2641                    if first_error.is_none() {
2642                        first_error = Some(anyhow!("Worktree creation was canceled"));
2643                    }
2644                }
2645            }
2646        }
2647
2648        let Some(err) = first_error else {
2649            return Ok(created_paths);
2650        };
2651
2652        // Rollback all successfully created worktrees
2653        let mut rollback_receivers = Vec::new();
2654        for (rollback_repo, rollback_path) in &repos_and_paths {
2655            if let Ok(receiver) = cx.update(|_, cx| {
2656                rollback_repo.update(cx, |repo, _cx| {
2657                    repo.remove_worktree(rollback_path.clone(), true)
2658                })
2659            }) {
2660                rollback_receivers.push((rollback_path.clone(), receiver));
2661            }
2662        }
2663        let mut rollback_failures: Vec<String> = Vec::new();
2664        for (path, receiver) in rollback_receivers {
2665            match receiver.await {
2666                Ok(Ok(())) => {}
2667                Ok(Err(rollback_err)) => {
2668                    log::error!(
2669                        "failed to rollback worktree at {}: {rollback_err}",
2670                        path.display()
2671                    );
2672                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2673                }
2674                Err(rollback_err) => {
2675                    log::error!(
2676                        "failed to rollback worktree at {}: {rollback_err}",
2677                        path.display()
2678                    );
2679                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2680                }
2681            }
2682        }
2683        let mut error_message = format!("Failed to create worktree: {err}");
2684        if !rollback_failures.is_empty() {
2685            error_message.push_str("\n\nFailed to clean up: ");
2686            error_message.push_str(&rollback_failures.join(", "));
2687        }
2688        Err(anyhow!(error_message))
2689    }
2690
2691    fn set_worktree_creation_error(
2692        &mut self,
2693        message: SharedString,
2694        window: &mut Window,
2695        cx: &mut Context<Self>,
2696    ) {
2697        self.worktree_creation_status = Some(WorktreeCreationStatus::Error(message));
2698        if matches!(self.active_view, ActiveView::Uninitialized) {
2699            let selected_agent_type = self.selected_agent_type.clone();
2700            self.new_agent_thread(selected_agent_type, window, cx);
2701        }
2702        cx.notify();
2703    }
2704
2705    fn handle_worktree_creation_requested(
2706        &mut self,
2707        content: Vec<acp::ContentBlock>,
2708        window: &mut Window,
2709        cx: &mut Context<Self>,
2710    ) {
2711        if matches!(
2712            self.worktree_creation_status,
2713            Some(WorktreeCreationStatus::Creating)
2714        ) {
2715            return;
2716        }
2717
2718        self.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
2719        cx.notify();
2720
2721        let (git_repos, non_git_paths) = self.classify_worktrees(cx);
2722
2723        if git_repos.is_empty() {
2724            self.set_worktree_creation_error(
2725                "No git repositories found in the project".into(),
2726                window,
2727                cx,
2728            );
2729            return;
2730        }
2731
2732        // Kick off branch listing as early as possible so it can run
2733        // concurrently with the remaining synchronous setup work.
2734        let branch_receivers: Vec<_> = git_repos
2735            .iter()
2736            .map(|repo| repo.update(cx, |repo, _cx| repo.branches()))
2737            .collect();
2738
2739        let worktree_directory_setting = ProjectSettings::get_global(cx)
2740            .git
2741            .worktree_directory
2742            .clone();
2743
2744        let active_file_path = self.workspace.upgrade().and_then(|workspace| {
2745            let workspace = workspace.read(cx);
2746            let active_item = workspace.active_item(cx)?;
2747            let project_path = active_item.project_path(cx)?;
2748            workspace
2749                .project()
2750                .read(cx)
2751                .absolute_path(&project_path, cx)
2752        });
2753
2754        let workspace = self.workspace.clone();
2755        let window_handle = window
2756            .window_handle()
2757            .downcast::<workspace::MultiWorkspace>();
2758
2759        let selected_agent = self.selected_agent();
2760
2761        let task = cx.spawn_in(window, async move |this, cx| {
2762            // Await the branch listings we kicked off earlier.
2763            let mut existing_branches = Vec::new();
2764            for result in futures::future::join_all(branch_receivers).await {
2765                match result {
2766                    Ok(Ok(branches)) => {
2767                        for branch in branches {
2768                            existing_branches.push(branch.name().to_string());
2769                        }
2770                    }
2771                    Ok(Err(err)) => {
2772                        Err::<(), _>(err).log_err();
2773                    }
2774                    Err(_) => {}
2775                }
2776            }
2777
2778            let existing_branch_refs: Vec<&str> =
2779                existing_branches.iter().map(|s| s.as_str()).collect();
2780            let mut rng = rand::rng();
2781            let branch_name =
2782                match crate::branch_names::generate_branch_name(&existing_branch_refs, &mut rng) {
2783                    Some(name) => name,
2784                    None => {
2785                        this.update_in(cx, |this, window, cx| {
2786                            this.set_worktree_creation_error(
2787                                "Failed to generate a branch name: all typewriter names are taken"
2788                                    .into(),
2789                                window,
2790                                cx,
2791                            );
2792                        })?;
2793                        return anyhow::Ok(());
2794                    }
2795                };
2796
2797            let (creation_infos, path_remapping) = match this.update_in(cx, |_this, _window, cx| {
2798                Self::start_worktree_creations(
2799                    &git_repos,
2800                    &branch_name,
2801                    &worktree_directory_setting,
2802                    cx,
2803                )
2804            }) {
2805                Ok(Ok(result)) => result,
2806                Ok(Err(err)) | Err(err) => {
2807                    this.update_in(cx, |this, window, cx| {
2808                        this.set_worktree_creation_error(
2809                            format!("Failed to validate worktree directory: {err}").into(),
2810                            window,
2811                            cx,
2812                        );
2813                    })
2814                    .log_err();
2815                    return anyhow::Ok(());
2816                }
2817            };
2818
2819            let created_paths = match Self::await_and_rollback_on_failure(creation_infos, cx).await
2820            {
2821                Ok(paths) => paths,
2822                Err(err) => {
2823                    this.update_in(cx, |this, window, cx| {
2824                        this.set_worktree_creation_error(format!("{err}").into(), window, cx);
2825                    })?;
2826                    return anyhow::Ok(());
2827                }
2828            };
2829
2830            let mut all_paths = created_paths;
2831            let has_non_git = !non_git_paths.is_empty();
2832            all_paths.extend(non_git_paths.iter().cloned());
2833
2834            let app_state = match workspace.upgrade() {
2835                Some(workspace) => cx.update(|_, cx| workspace.read(cx).app_state().clone())?,
2836                None => {
2837                    this.update_in(cx, |this, window, cx| {
2838                        this.set_worktree_creation_error(
2839                            "Workspace no longer available".into(),
2840                            window,
2841                            cx,
2842                        );
2843                    })?;
2844                    return anyhow::Ok(());
2845                }
2846            };
2847
2848            let this_for_error = this.clone();
2849            if let Err(err) = Self::setup_new_workspace(
2850                this,
2851                all_paths,
2852                app_state,
2853                window_handle,
2854                active_file_path,
2855                path_remapping,
2856                non_git_paths,
2857                has_non_git,
2858                content,
2859                selected_agent,
2860                cx,
2861            )
2862            .await
2863            {
2864                this_for_error
2865                    .update_in(cx, |this, window, cx| {
2866                        this.set_worktree_creation_error(
2867                            format!("Failed to set up workspace: {err}").into(),
2868                            window,
2869                            cx,
2870                        );
2871                    })
2872                    .log_err();
2873            }
2874            anyhow::Ok(())
2875        });
2876
2877        self._worktree_creation_task = Some(cx.foreground_executor().spawn(async move {
2878            task.await.log_err();
2879        }));
2880    }
2881
2882    async fn setup_new_workspace(
2883        this: WeakEntity<Self>,
2884        all_paths: Vec<PathBuf>,
2885        app_state: Arc<workspace::AppState>,
2886        window_handle: Option<gpui::WindowHandle<workspace::MultiWorkspace>>,
2887        active_file_path: Option<PathBuf>,
2888        path_remapping: Vec<(PathBuf, PathBuf)>,
2889        non_git_paths: Vec<PathBuf>,
2890        has_non_git: bool,
2891        content: Vec<acp::ContentBlock>,
2892        selected_agent: Option<Agent>,
2893        cx: &mut AsyncWindowContext,
2894    ) -> Result<()> {
2895        let OpenResult {
2896            window: new_window_handle,
2897            workspace: new_workspace,
2898            ..
2899        } = cx
2900            .update(|_window, cx| {
2901                Workspace::new_local(all_paths, app_state, window_handle, None, None, false, cx)
2902            })?
2903            .await?;
2904
2905        let panels_task = new_window_handle.update(cx, |_, _, cx| {
2906            new_workspace.update(cx, |workspace, _cx| workspace.take_panels_task())
2907        })?;
2908        if let Some(task) = panels_task {
2909            task.await.log_err();
2910        }
2911
2912        let initial_content = AgentInitialContent::ContentBlock {
2913            blocks: content,
2914            auto_submit: true,
2915        };
2916
2917        new_window_handle.update(cx, |_multi_workspace, window, cx| {
2918            new_workspace.update(cx, |workspace, cx| {
2919                if has_non_git {
2920                    let toast_id = workspace::notifications::NotificationId::unique::<AgentPanel>();
2921                    workspace.show_toast(
2922                        workspace::Toast::new(
2923                            toast_id,
2924                            "Some project folders are not git repositories. \
2925                             They were included as-is without creating a worktree.",
2926                        ),
2927                        cx,
2928                    );
2929                }
2930
2931                // If we had an active buffer, remap its path and reopen it.
2932                let should_zoom_agent_panel = active_file_path.is_none();
2933
2934                let remapped_active_path = active_file_path.and_then(|original_path| {
2935                    let best_match = path_remapping
2936                        .iter()
2937                        .filter_map(|(old_root, new_root)| {
2938                            original_path.strip_prefix(old_root).ok().map(|relative| {
2939                                (old_root.components().count(), new_root.join(relative))
2940                            })
2941                        })
2942                        .max_by_key(|(depth, _)| *depth);
2943
2944                    if let Some((_, remapped_path)) = best_match {
2945                        return Some(remapped_path);
2946                    }
2947
2948                    for non_git in &non_git_paths {
2949                        if original_path.starts_with(non_git) {
2950                            return Some(original_path);
2951                        }
2952                    }
2953                    None
2954                });
2955
2956                if !should_zoom_agent_panel && remapped_active_path.is_none() {
2957                    log::warn!(
2958                        "Active file could not be remapped to the new worktree; it will not be reopened"
2959                    );
2960                }
2961
2962                if let Some(path) = remapped_active_path {
2963                    let open_task = workspace.open_paths(
2964                        vec![path],
2965                        workspace::OpenOptions::default(),
2966                        None,
2967                        window,
2968                        cx,
2969                    );
2970                    cx.spawn(async move |_, _| -> anyhow::Result<()> {
2971                        for item in open_task.await.into_iter().flatten() {
2972                            item?;
2973                        }
2974                        Ok(())
2975                    })
2976                    .detach_and_log_err(cx);
2977                }
2978
2979                workspace.focus_panel::<AgentPanel>(window, cx);
2980
2981                // If no active buffer was open, zoom the agent panel
2982                // (equivalent to cmd-esc fullscreen behavior).
2983                // This must happen after focus_panel, which activates
2984                // and opens the panel in the dock.
2985                if should_zoom_agent_panel {
2986                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2987                        panel.update(cx, |_panel, cx| {
2988                            cx.emit(PanelEvent::ZoomIn);
2989                        });
2990                    }
2991                }
2992                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2993                    panel.update(cx, |panel, cx| {
2994                        panel.external_thread(
2995                            selected_agent,
2996                            None,
2997                            None,
2998                            None,
2999                            Some(initial_content),
3000                            true,
3001                            window,
3002                            cx,
3003                        );
3004                    });
3005                }
3006            });
3007        })?;
3008
3009        new_window_handle.update(cx, |multi_workspace, _window, cx| {
3010            multi_workspace.activate(new_workspace.clone(), cx);
3011        })?;
3012
3013        this.update_in(cx, |this, _window, cx| {
3014            this.worktree_creation_status = None;
3015            cx.notify();
3016        })?;
3017
3018        anyhow::Ok(())
3019    }
3020}
3021
3022impl Focusable for AgentPanel {
3023    fn focus_handle(&self, cx: &App) -> FocusHandle {
3024        match &self.active_view {
3025            ActiveView::Uninitialized => self.focus_handle.clone(),
3026            ActiveView::AgentThread {
3027                conversation_view, ..
3028            } => conversation_view.focus_handle(cx),
3029            ActiveView::History { history: kind } => match kind {
3030                History::AgentThreads { view } => view.read(cx).focus_handle(cx),
3031                History::TextThreads => self.text_thread_history.focus_handle(cx),
3032            },
3033            ActiveView::TextThread {
3034                text_thread_editor, ..
3035            } => text_thread_editor.focus_handle(cx),
3036            ActiveView::Configuration => {
3037                if let Some(configuration) = self.configuration.as_ref() {
3038                    configuration.focus_handle(cx)
3039                } else {
3040                    self.focus_handle.clone()
3041                }
3042            }
3043        }
3044    }
3045}
3046
3047fn agent_panel_dock_position(cx: &App) -> DockPosition {
3048    AgentSettings::get_global(cx).dock.into()
3049}
3050
3051pub enum AgentPanelEvent {
3052    ActiveViewChanged,
3053    ThreadFocused,
3054    BackgroundThreadChanged,
3055}
3056
3057impl EventEmitter<PanelEvent> for AgentPanel {}
3058impl EventEmitter<AgentPanelEvent> for AgentPanel {}
3059
3060impl Panel for AgentPanel {
3061    fn persistent_name() -> &'static str {
3062        "AgentPanel"
3063    }
3064
3065    fn panel_key() -> &'static str {
3066        AGENT_PANEL_KEY
3067    }
3068
3069    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3070        agent_panel_dock_position(cx)
3071    }
3072
3073    fn position_is_valid(&self, position: DockPosition) -> bool {
3074        position != DockPosition::Bottom
3075    }
3076
3077    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3078        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3079            settings
3080                .agent
3081                .get_or_insert_default()
3082                .set_dock(position.into());
3083        });
3084    }
3085
3086    fn size(&self, window: &Window, cx: &App) -> Pixels {
3087        let settings = AgentSettings::get_global(cx);
3088        match self.position(window, cx) {
3089            DockPosition::Left | DockPosition::Right => {
3090                self.width.unwrap_or(settings.default_width)
3091            }
3092            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
3093        }
3094    }
3095
3096    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
3097        match self.position(window, cx) {
3098            DockPosition::Left | DockPosition::Right => self.width = size,
3099            DockPosition::Bottom => self.height = size,
3100        }
3101        self.serialize(cx);
3102        cx.notify();
3103    }
3104
3105    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
3106        if active
3107            && matches!(self.active_view, ActiveView::Uninitialized)
3108            && !matches!(
3109                self.worktree_creation_status,
3110                Some(WorktreeCreationStatus::Creating)
3111            )
3112        {
3113            let selected_agent_type = self.selected_agent_type.clone();
3114            self.new_agent_thread_inner(selected_agent_type, false, window, cx);
3115        }
3116    }
3117
3118    fn remote_id() -> Option<proto::PanelId> {
3119        Some(proto::PanelId::AssistantPanel)
3120    }
3121
3122    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
3123        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
3124    }
3125
3126    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3127        Some("Agent Panel")
3128    }
3129
3130    fn toggle_action(&self) -> Box<dyn Action> {
3131        Box::new(ToggleFocus)
3132    }
3133
3134    fn activation_priority(&self) -> u32 {
3135        3
3136    }
3137
3138    fn enabled(&self, cx: &App) -> bool {
3139        AgentSettings::get_global(cx).enabled(cx)
3140    }
3141
3142    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
3143        self.zoomed
3144    }
3145
3146    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
3147        self.zoomed = zoomed;
3148        cx.notify();
3149    }
3150}
3151
3152impl AgentPanel {
3153    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
3154        const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
3155
3156        let content = match &self.active_view {
3157            ActiveView::AgentThread { conversation_view } => {
3158                let server_view_ref = conversation_view.read(cx);
3159                let is_generating_title = server_view_ref.as_native_thread(cx).is_some()
3160                    && server_view_ref.parent_thread(cx).map_or(false, |tv| {
3161                        tv.read(cx).thread.read(cx).has_provisional_title()
3162                    });
3163
3164                if let Some(title_editor) = server_view_ref
3165                    .parent_thread(cx)
3166                    .map(|r| r.read(cx).title_editor.clone())
3167                {
3168                    if is_generating_title {
3169                        Label::new("New Thread…")
3170                            .color(Color::Muted)
3171                            .truncate()
3172                            .with_animation(
3173                                "generating_title",
3174                                Animation::new(Duration::from_secs(2))
3175                                    .repeat()
3176                                    .with_easing(pulsating_between(0.4, 0.8)),
3177                                |label, delta| label.alpha(delta),
3178                            )
3179                            .into_any_element()
3180                    } else {
3181                        div()
3182                            .w_full()
3183                            .on_action({
3184                                let conversation_view = conversation_view.downgrade();
3185                                move |_: &menu::Confirm, window, cx| {
3186                                    if let Some(conversation_view) = conversation_view.upgrade() {
3187                                        conversation_view.focus_handle(cx).focus(window, cx);
3188                                    }
3189                                }
3190                            })
3191                            .on_action({
3192                                let conversation_view = conversation_view.downgrade();
3193                                move |_: &editor::actions::Cancel, window, cx| {
3194                                    if let Some(conversation_view) = conversation_view.upgrade() {
3195                                        conversation_view.focus_handle(cx).focus(window, cx);
3196                                    }
3197                                }
3198                            })
3199                            .child(title_editor)
3200                            .into_any_element()
3201                    }
3202                } else {
3203                    Label::new(conversation_view.read(cx).title(cx))
3204                        .color(Color::Muted)
3205                        .truncate()
3206                        .into_any_element()
3207                }
3208            }
3209            ActiveView::TextThread {
3210                title_editor,
3211                text_thread_editor,
3212                ..
3213            } => {
3214                let summary = text_thread_editor.read(cx).text_thread().read(cx).summary();
3215
3216                match summary {
3217                    TextThreadSummary::Pending => Label::new(TextThreadSummary::DEFAULT)
3218                        .color(Color::Muted)
3219                        .truncate()
3220                        .into_any_element(),
3221                    TextThreadSummary::Content(summary) => {
3222                        if summary.done {
3223                            div()
3224                                .w_full()
3225                                .child(title_editor.clone())
3226                                .into_any_element()
3227                        } else {
3228                            Label::new(LOADING_SUMMARY_PLACEHOLDER)
3229                                .truncate()
3230                                .color(Color::Muted)
3231                                .with_animation(
3232                                    "generating_title",
3233                                    Animation::new(Duration::from_secs(2))
3234                                        .repeat()
3235                                        .with_easing(pulsating_between(0.4, 0.8)),
3236                                    |label, delta| label.alpha(delta),
3237                                )
3238                                .into_any_element()
3239                        }
3240                    }
3241                    TextThreadSummary::Error => h_flex()
3242                        .w_full()
3243                        .child(title_editor.clone())
3244                        .child(
3245                            IconButton::new("retry-summary-generation", IconName::RotateCcw)
3246                                .icon_size(IconSize::Small)
3247                                .on_click({
3248                                    let text_thread_editor = text_thread_editor.clone();
3249                                    move |_, _window, cx| {
3250                                        text_thread_editor.update(cx, |text_thread_editor, cx| {
3251                                            text_thread_editor.regenerate_summary(cx);
3252                                        });
3253                                    }
3254                                })
3255                                .tooltip(move |_window, cx| {
3256                                    cx.new(|_| {
3257                                        Tooltip::new("Failed to generate title")
3258                                            .meta("Click to try again")
3259                                    })
3260                                    .into()
3261                                }),
3262                        )
3263                        .into_any_element(),
3264                }
3265            }
3266            ActiveView::History { history: kind } => {
3267                let title = match kind {
3268                    History::AgentThreads { .. } => "History",
3269                    History::TextThreads => "Text Thread History",
3270                };
3271                Label::new(title).truncate().into_any_element()
3272            }
3273            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
3274            ActiveView::Uninitialized => Label::new("Agent").truncate().into_any_element(),
3275        };
3276
3277        h_flex()
3278            .key_context("TitleEditor")
3279            .id("TitleEditor")
3280            .flex_grow()
3281            .w_full()
3282            .max_w_full()
3283            .overflow_x_scroll()
3284            .child(content)
3285            .into_any()
3286    }
3287
3288    fn handle_regenerate_thread_title(conversation_view: Entity<ConversationView>, cx: &mut App) {
3289        conversation_view.update(cx, |conversation_view, cx| {
3290            if let Some(thread) = conversation_view.as_native_thread(cx) {
3291                thread.update(cx, |thread, cx| {
3292                    thread.generate_title(cx);
3293                });
3294            }
3295        });
3296    }
3297
3298    fn handle_regenerate_text_thread_title(
3299        text_thread_editor: Entity<TextThreadEditor>,
3300        cx: &mut App,
3301    ) {
3302        text_thread_editor.update(cx, |text_thread_editor, cx| {
3303            text_thread_editor.regenerate_summary(cx);
3304        });
3305    }
3306
3307    fn render_panel_options_menu(
3308        &self,
3309        window: &mut Window,
3310        cx: &mut Context<Self>,
3311    ) -> impl IntoElement {
3312        let focus_handle = self.focus_handle(cx);
3313
3314        let full_screen_label = if self.is_zoomed(window, cx) {
3315            "Disable Full Screen"
3316        } else {
3317            "Enable Full Screen"
3318        };
3319
3320        let text_thread_view = match &self.active_view {
3321            ActiveView::TextThread {
3322                text_thread_editor, ..
3323            } => Some(text_thread_editor.clone()),
3324            _ => None,
3325        };
3326        let text_thread_with_messages = match &self.active_view {
3327            ActiveView::TextThread {
3328                text_thread_editor, ..
3329            } => text_thread_editor
3330                .read(cx)
3331                .text_thread()
3332                .read(cx)
3333                .messages(cx)
3334                .any(|message| message.role == language_model::Role::Assistant),
3335            _ => false,
3336        };
3337
3338        let conversation_view = match &self.active_view {
3339            ActiveView::AgentThread { conversation_view } => Some(conversation_view.clone()),
3340            _ => None,
3341        };
3342        let thread_with_messages = match &self.active_view {
3343            ActiveView::AgentThread { conversation_view } => {
3344                conversation_view.read(cx).has_user_submitted_prompt(cx)
3345            }
3346            _ => false,
3347        };
3348        let has_auth_methods = match &self.active_view {
3349            ActiveView::AgentThread { conversation_view } => {
3350                conversation_view.read(cx).has_auth_methods()
3351            }
3352            _ => false,
3353        };
3354
3355        PopoverMenu::new("agent-options-menu")
3356            .trigger_with_tooltip(
3357                IconButton::new("agent-options-menu", IconName::Ellipsis)
3358                    .icon_size(IconSize::Small),
3359                {
3360                    let focus_handle = focus_handle.clone();
3361                    move |_window, cx| {
3362                        Tooltip::for_action_in(
3363                            "Toggle Agent Menu",
3364                            &ToggleOptionsMenu,
3365                            &focus_handle,
3366                            cx,
3367                        )
3368                    }
3369                },
3370            )
3371            .anchor(Corner::TopRight)
3372            .with_handle(self.agent_panel_menu_handle.clone())
3373            .menu({
3374                move |window, cx| {
3375                    Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
3376                        menu = menu.context(focus_handle.clone());
3377
3378                        if thread_with_messages | text_thread_with_messages {
3379                            menu = menu.header("Current Thread");
3380
3381                            if let Some(text_thread_view) = text_thread_view.as_ref() {
3382                                menu = menu
3383                                    .entry("Regenerate Thread Title", None, {
3384                                        let text_thread_view = text_thread_view.clone();
3385                                        move |_, cx| {
3386                                            Self::handle_regenerate_text_thread_title(
3387                                                text_thread_view.clone(),
3388                                                cx,
3389                                            );
3390                                        }
3391                                    })
3392                                    .separator();
3393                            }
3394
3395                            if let Some(conversation_view) = conversation_view.as_ref() {
3396                                menu = menu
3397                                    .entry("Regenerate Thread Title", None, {
3398                                        let conversation_view = conversation_view.clone();
3399                                        move |_, cx| {
3400                                            Self::handle_regenerate_thread_title(
3401                                                conversation_view.clone(),
3402                                                cx,
3403                                            );
3404                                        }
3405                                    })
3406                                    .separator();
3407                            }
3408                        }
3409
3410                        menu = menu
3411                            .header("MCP Servers")
3412                            .action(
3413                                "View Server Extensions",
3414                                Box::new(zed_actions::Extensions {
3415                                    category_filter: Some(
3416                                        zed_actions::ExtensionCategoryFilter::ContextServers,
3417                                    ),
3418                                    id: None,
3419                                }),
3420                            )
3421                            .action("Add Custom Server…", Box::new(AddContextServer))
3422                            .separator()
3423                            .action("Rules", Box::new(OpenRulesLibrary::default()))
3424                            .action("Profiles", Box::new(ManageProfiles::default()))
3425                            .action("Settings", Box::new(OpenSettings))
3426                            .separator()
3427                            .action(full_screen_label, Box::new(ToggleZoom));
3428
3429                        if has_auth_methods {
3430                            menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
3431                        }
3432
3433                        menu
3434                    }))
3435                }
3436            })
3437    }
3438
3439    fn render_recent_entries_menu(
3440        &self,
3441        icon: IconName,
3442        corner: Corner,
3443        cx: &mut Context<Self>,
3444    ) -> impl IntoElement {
3445        let focus_handle = self.focus_handle(cx);
3446
3447        PopoverMenu::new("agent-nav-menu")
3448            .trigger_with_tooltip(
3449                IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
3450                {
3451                    move |_window, cx| {
3452                        Tooltip::for_action_in(
3453                            "Toggle Recently Updated Threads",
3454                            &ToggleNavigationMenu,
3455                            &focus_handle,
3456                            cx,
3457                        )
3458                    }
3459                },
3460            )
3461            .anchor(corner)
3462            .with_handle(self.agent_navigation_menu_handle.clone())
3463            .menu({
3464                let menu = self.agent_navigation_menu.clone();
3465                move |window, cx| {
3466                    telemetry::event!("View Thread History Clicked");
3467
3468                    if let Some(menu) = menu.as_ref() {
3469                        menu.update(cx, |_, cx| {
3470                            cx.defer_in(window, |menu, window, cx| {
3471                                menu.rebuild(window, cx);
3472                            });
3473                        })
3474                    }
3475                    menu.clone()
3476                }
3477            })
3478    }
3479
3480    fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3481        let focus_handle = self.focus_handle(cx);
3482
3483        IconButton::new("go-back", IconName::ArrowLeft)
3484            .icon_size(IconSize::Small)
3485            .on_click(cx.listener(|this, _, window, cx| {
3486                this.go_back(&workspace::GoBack, window, cx);
3487            }))
3488            .tooltip({
3489                move |_window, cx| {
3490                    Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
3491                }
3492            })
3493    }
3494
3495    fn project_has_git_repository(&self, cx: &App) -> bool {
3496        !self.project.read(cx).repositories(cx).is_empty()
3497    }
3498
3499    fn render_start_thread_in_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3500        use settings::{NewThreadLocation, Settings};
3501
3502        let focus_handle = self.focus_handle(cx);
3503        let has_git_repo = self.project_has_git_repository(cx);
3504        let is_via_collab = self.project.read(cx).is_via_collab();
3505        let fs = self.fs.clone();
3506
3507        let is_creating = matches!(
3508            self.worktree_creation_status,
3509            Some(WorktreeCreationStatus::Creating)
3510        );
3511
3512        let current_target = self.start_thread_in;
3513        let trigger_label = self.start_thread_in.label();
3514
3515        let new_thread_location = AgentSettings::get_global(cx).new_thread_location;
3516        let is_local_default = new_thread_location == NewThreadLocation::LocalProject;
3517        let is_new_worktree_default = new_thread_location == NewThreadLocation::NewWorktree;
3518
3519        let icon = if self.start_thread_in_menu_handle.is_deployed() {
3520            IconName::ChevronUp
3521        } else {
3522            IconName::ChevronDown
3523        };
3524
3525        let trigger_button = Button::new("thread-target-trigger", trigger_label)
3526            .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3527            .disabled(is_creating);
3528
3529        let dock_position = AgentSettings::get_global(cx).dock;
3530        let documentation_side = match dock_position {
3531            settings::DockPosition::Left => DocumentationSide::Right,
3532            settings::DockPosition::Bottom | settings::DockPosition::Right => {
3533                DocumentationSide::Left
3534            }
3535        };
3536
3537        PopoverMenu::new("thread-target-selector")
3538            .trigger_with_tooltip(trigger_button, {
3539                move |_window, cx| {
3540                    Tooltip::for_action_in(
3541                        "Start Thread In…",
3542                        &CycleStartThreadIn,
3543                        &focus_handle,
3544                        cx,
3545                    )
3546                }
3547            })
3548            .menu(move |window, cx| {
3549                let is_local_selected = current_target == StartThreadIn::LocalProject;
3550                let is_new_worktree_selected = current_target == StartThreadIn::NewWorktree;
3551                let fs = fs.clone();
3552
3553                Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
3554                    let new_worktree_disabled = !has_git_repo || is_via_collab;
3555
3556                    menu.header("Start Thread In…")
3557                        .item(
3558                            ContextMenuEntry::new("Current Project")
3559                                .toggleable(IconPosition::End, is_local_selected)
3560                                .documentation_aside(documentation_side, move |_| {
3561                                    HoldForDefault::new(is_local_default)
3562                                        .more_content(false)
3563                                        .into_any_element()
3564                                })
3565                                .handler({
3566                                    let fs = fs.clone();
3567                                    move |window, cx| {
3568                                        if window.modifiers().secondary() {
3569                                            update_settings_file(fs.clone(), cx, |settings, _| {
3570                                                settings
3571                                                    .agent
3572                                                    .get_or_insert_default()
3573                                                    .set_new_thread_location(
3574                                                        NewThreadLocation::LocalProject,
3575                                                    );
3576                                            });
3577                                        }
3578                                        window.dispatch_action(
3579                                            Box::new(StartThreadIn::LocalProject),
3580                                            cx,
3581                                        );
3582                                    }
3583                                }),
3584                        )
3585                        .item({
3586                            let entry = ContextMenuEntry::new("New Worktree")
3587                                .toggleable(IconPosition::End, is_new_worktree_selected)
3588                                .disabled(new_worktree_disabled)
3589                                .handler({
3590                                    let fs = fs.clone();
3591                                    move |window, cx| {
3592                                        if window.modifiers().secondary() {
3593                                            update_settings_file(fs.clone(), cx, |settings, _| {
3594                                                settings
3595                                                    .agent
3596                                                    .get_or_insert_default()
3597                                                    .set_new_thread_location(
3598                                                        NewThreadLocation::NewWorktree,
3599                                                    );
3600                                            });
3601                                        }
3602                                        window.dispatch_action(
3603                                            Box::new(StartThreadIn::NewWorktree),
3604                                            cx,
3605                                        );
3606                                    }
3607                                });
3608
3609                            if new_worktree_disabled {
3610                                entry.documentation_aside(documentation_side, move |_| {
3611                                    let reason = if !has_git_repo {
3612                                        "No git repository found in this project."
3613                                    } else {
3614                                        "Not available for remote/collab projects yet."
3615                                    };
3616                                    Label::new(reason)
3617                                        .color(Color::Muted)
3618                                        .size(LabelSize::Small)
3619                                        .into_any_element()
3620                                })
3621                            } else {
3622                                entry.documentation_aside(documentation_side, move |_| {
3623                                    HoldForDefault::new(is_new_worktree_default)
3624                                        .more_content(false)
3625                                        .into_any_element()
3626                                })
3627                            }
3628                        })
3629                }))
3630            })
3631            .with_handle(self.start_thread_in_menu_handle.clone())
3632            .anchor(Corner::TopLeft)
3633            .offset(gpui::Point {
3634                x: px(1.0),
3635                y: px(1.0),
3636            })
3637    }
3638
3639    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3640        let agent_server_store = self.project.read(cx).agent_server_store().clone();
3641        let focus_handle = self.focus_handle(cx);
3642
3643        let (selected_agent_custom_icon, selected_agent_label) =
3644            if let AgentType::Custom { id, .. } = &self.selected_agent_type {
3645                let store = agent_server_store.read(cx);
3646                let icon = store.agent_icon(&id);
3647
3648                let label = store
3649                    .agent_display_name(&id)
3650                    .unwrap_or_else(|| self.selected_agent_type.label());
3651                (icon, label)
3652            } else {
3653                (None, self.selected_agent_type.label())
3654            };
3655
3656        let active_thread = match &self.active_view {
3657            ActiveView::AgentThread { conversation_view } => {
3658                conversation_view.read(cx).as_native_thread(cx)
3659            }
3660            ActiveView::Uninitialized
3661            | ActiveView::TextThread { .. }
3662            | ActiveView::History { .. }
3663            | ActiveView::Configuration => None,
3664        };
3665
3666        let new_thread_menu_builder: Rc<
3667            dyn Fn(&mut Window, &mut App) -> Option<Entity<ContextMenu>>,
3668        > = {
3669            let selected_agent = self.selected_agent_type.clone();
3670            let is_agent_selected = move |agent_type: AgentType| selected_agent == agent_type;
3671
3672            let workspace = self.workspace.clone();
3673            let is_via_collab = workspace
3674                .update(cx, |workspace, cx| {
3675                    workspace.project().read(cx).is_via_collab()
3676                })
3677                .unwrap_or_default();
3678
3679            let focus_handle = focus_handle.clone();
3680            let agent_server_store = agent_server_store;
3681
3682            Rc::new(move |window, cx| {
3683                telemetry::event!("New Thread Clicked");
3684
3685                let active_thread = active_thread.clone();
3686                Some(ContextMenu::build(window, cx, |menu, _window, cx| {
3687                    menu.context(focus_handle.clone())
3688                        .when_some(active_thread, |this, active_thread| {
3689                            let thread = active_thread.read(cx);
3690
3691                            if !thread.is_empty() {
3692                                let session_id = thread.id().clone();
3693                                this.item(
3694                                    ContextMenuEntry::new("New From Summary")
3695                                        .icon(IconName::ThreadFromSummary)
3696                                        .icon_color(Color::Muted)
3697                                        .handler(move |window, cx| {
3698                                            window.dispatch_action(
3699                                                Box::new(NewNativeAgentThreadFromSummary {
3700                                                    from_session_id: session_id.clone(),
3701                                                }),
3702                                                cx,
3703                                            );
3704                                        }),
3705                                )
3706                            } else {
3707                                this
3708                            }
3709                        })
3710                        .item(
3711                            ContextMenuEntry::new("Zed Agent")
3712                                .when(
3713                                    is_agent_selected(AgentType::NativeAgent)
3714                                        | is_agent_selected(AgentType::TextThread),
3715                                    |this| {
3716                                        this.action(Box::new(NewExternalAgentThread {
3717                                            agent: None,
3718                                        }))
3719                                    },
3720                                )
3721                                .icon(IconName::ZedAgent)
3722                                .icon_color(Color::Muted)
3723                                .handler({
3724                                    let workspace = workspace.clone();
3725                                    move |window, cx| {
3726                                        if let Some(workspace) = workspace.upgrade() {
3727                                            workspace.update(cx, |workspace, cx| {
3728                                                if let Some(panel) =
3729                                                    workspace.panel::<AgentPanel>(cx)
3730                                                {
3731                                                    panel.update(cx, |panel, cx| {
3732                                                        panel.new_agent_thread(
3733                                                            AgentType::NativeAgent,
3734                                                            window,
3735                                                            cx,
3736                                                        );
3737                                                    });
3738                                                }
3739                                            });
3740                                        }
3741                                    }
3742                                }),
3743                        )
3744                        .item(
3745                            ContextMenuEntry::new("Text Thread")
3746                                .action(NewTextThread.boxed_clone())
3747                                .icon(IconName::TextThread)
3748                                .icon_color(Color::Muted)
3749                                .handler({
3750                                    let workspace = workspace.clone();
3751                                    move |window, cx| {
3752                                        if let Some(workspace) = workspace.upgrade() {
3753                                            workspace.update(cx, |workspace, cx| {
3754                                                if let Some(panel) =
3755                                                    workspace.panel::<AgentPanel>(cx)
3756                                                {
3757                                                    panel.update(cx, |panel, cx| {
3758                                                        panel.new_agent_thread(
3759                                                            AgentType::TextThread,
3760                                                            window,
3761                                                            cx,
3762                                                        );
3763                                                    });
3764                                                }
3765                                            });
3766                                        }
3767                                    }
3768                                }),
3769                        )
3770                        .separator()
3771                        .header("External Agents")
3772                        .map(|mut menu| {
3773                            let agent_server_store = agent_server_store.read(cx);
3774                            let registry_store = project::AgentRegistryStore::try_global(cx);
3775                            let registry_store_ref = registry_store.as_ref().map(|s| s.read(cx));
3776
3777                            struct AgentMenuItem {
3778                                id: AgentId,
3779                                display_name: SharedString,
3780                            }
3781
3782                            let agent_items = agent_server_store
3783                                .external_agents()
3784                                .map(|agent_id| {
3785                                    let display_name = agent_server_store
3786                                        .agent_display_name(agent_id)
3787                                        .or_else(|| {
3788                                            registry_store_ref
3789                                                .as_ref()
3790                                                .and_then(|store| store.agent(agent_id))
3791                                                .map(|a| a.name().clone())
3792                                        })
3793                                        .unwrap_or_else(|| agent_id.0.clone());
3794                                    AgentMenuItem {
3795                                        id: agent_id.clone(),
3796                                        display_name,
3797                                    }
3798                                })
3799                                .sorted_unstable_by_key(|e| e.display_name.to_lowercase())
3800                                .collect::<Vec<_>>();
3801
3802                            for item in &agent_items {
3803                                let mut entry = ContextMenuEntry::new(item.display_name.clone());
3804
3805                                let icon_path =
3806                                    agent_server_store.agent_icon(&item.id).or_else(|| {
3807                                        registry_store_ref
3808                                            .as_ref()
3809                                            .and_then(|store| store.agent(&item.id))
3810                                            .and_then(|a| a.icon_path().cloned())
3811                                    });
3812
3813                                if let Some(icon_path) = icon_path {
3814                                    entry = entry.custom_icon_svg(icon_path);
3815                                } else {
3816                                    entry = entry.icon(IconName::Sparkle);
3817                                }
3818
3819                                entry = entry
3820                                    .when(
3821                                        is_agent_selected(AgentType::Custom {
3822                                            id: item.id.clone(),
3823                                        }),
3824                                        |this| {
3825                                            this.action(Box::new(NewExternalAgentThread {
3826                                                agent: None,
3827                                            }))
3828                                        },
3829                                    )
3830                                    .icon_color(Color::Muted)
3831                                    .disabled(is_via_collab)
3832                                    .handler({
3833                                        let workspace = workspace.clone();
3834                                        let agent_id = item.id.clone();
3835                                        move |window, cx| {
3836                                            if let Some(workspace) = workspace.upgrade() {
3837                                                workspace.update(cx, |workspace, cx| {
3838                                                    if let Some(panel) =
3839                                                        workspace.panel::<AgentPanel>(cx)
3840                                                    {
3841                                                        panel.update(cx, |panel, cx| {
3842                                                            panel.new_agent_thread(
3843                                                                AgentType::Custom {
3844                                                                    id: agent_id.clone(),
3845                                                                },
3846                                                                window,
3847                                                                cx,
3848                                                            );
3849                                                        });
3850                                                    }
3851                                                });
3852                                            }
3853                                        }
3854                                    });
3855
3856                                menu = menu.item(entry);
3857                            }
3858
3859                            menu
3860                        })
3861                        .separator()
3862                        .item(
3863                            ContextMenuEntry::new("Add More Agents")
3864                                .icon(IconName::Plus)
3865                                .icon_color(Color::Muted)
3866                                .handler({
3867                                    move |window, cx| {
3868                                        window
3869                                            .dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
3870                                    }
3871                                }),
3872                        )
3873                }))
3874            })
3875        };
3876
3877        let is_thread_loading = self
3878            .active_conversation()
3879            .map(|thread| thread.read(cx).is_loading())
3880            .unwrap_or(false);
3881
3882        let has_custom_icon = selected_agent_custom_icon.is_some();
3883        let selected_agent_custom_icon_for_button = selected_agent_custom_icon.clone();
3884        let selected_agent_builtin_icon = self.selected_agent_type.icon();
3885        let selected_agent_label_for_tooltip = selected_agent_label.clone();
3886
3887        let selected_agent = div()
3888            .id("selected_agent_icon")
3889            .when_some(selected_agent_custom_icon, |this, icon_path| {
3890                this.px_1()
3891                    .child(Icon::from_external_svg(icon_path).color(Color::Muted))
3892            })
3893            .when(!has_custom_icon, |this| {
3894                this.when_some(self.selected_agent_type.icon(), |this, icon| {
3895                    this.px_1().child(Icon::new(icon).color(Color::Muted))
3896                })
3897            })
3898            .tooltip(move |_, cx| {
3899                Tooltip::with_meta(
3900                    selected_agent_label_for_tooltip.clone(),
3901                    None,
3902                    "Selected Agent",
3903                    cx,
3904                )
3905            });
3906
3907        let selected_agent = if is_thread_loading {
3908            selected_agent
3909                .with_animation(
3910                    "pulsating-icon",
3911                    Animation::new(Duration::from_secs(1))
3912                        .repeat()
3913                        .with_easing(pulsating_between(0.2, 0.6)),
3914                    |icon, delta| icon.opacity(delta),
3915                )
3916                .into_any_element()
3917        } else {
3918            selected_agent.into_any_element()
3919        };
3920
3921        let show_history_menu = self.has_history_for_selected_agent(cx);
3922        let has_v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
3923        let is_empty_state = !self.active_thread_has_messages(cx);
3924
3925        let is_in_history_or_config = matches!(
3926            &self.active_view,
3927            ActiveView::History { .. } | ActiveView::Configuration
3928        );
3929
3930        let is_text_thread = matches!(&self.active_view, ActiveView::TextThread { .. });
3931
3932        let use_v2_empty_toolbar =
3933            has_v2_flag && is_empty_state && !is_in_history_or_config && !is_text_thread;
3934
3935        let base_container = h_flex()
3936            .id("agent-panel-toolbar")
3937            .h(Tab::container_height(cx))
3938            .max_w_full()
3939            .flex_none()
3940            .justify_between()
3941            .gap_2()
3942            .bg(cx.theme().colors().tab_bar_background)
3943            .border_b_1()
3944            .border_color(cx.theme().colors().border);
3945
3946        if use_v2_empty_toolbar {
3947            let (chevron_icon, icon_color, label_color) =
3948                if self.new_thread_menu_handle.is_deployed() {
3949                    (IconName::ChevronUp, Color::Accent, Color::Accent)
3950                } else {
3951                    (IconName::ChevronDown, Color::Muted, Color::Default)
3952                };
3953
3954            let agent_icon = if let Some(icon_path) = selected_agent_custom_icon_for_button {
3955                Icon::from_external_svg(icon_path)
3956                    .size(IconSize::Small)
3957                    .color(icon_color)
3958            } else {
3959                let icon_name = selected_agent_builtin_icon.unwrap_or(IconName::ZedAgent);
3960                Icon::new(icon_name).size(IconSize::Small).color(icon_color)
3961            };
3962
3963            let agent_selector_button = Button::new("agent-selector-trigger", selected_agent_label)
3964                .start_icon(agent_icon)
3965                .color(label_color)
3966                .end_icon(
3967                    Icon::new(chevron_icon)
3968                        .color(icon_color)
3969                        .size(IconSize::XSmall),
3970                );
3971
3972            let agent_selector_menu = PopoverMenu::new("new_thread_menu")
3973                .trigger_with_tooltip(agent_selector_button, {
3974                    move |_window, cx| {
3975                        Tooltip::for_action_in(
3976                            "New Thread\u{2026}",
3977                            &ToggleNewThreadMenu,
3978                            &focus_handle,
3979                            cx,
3980                        )
3981                    }
3982                })
3983                .menu({
3984                    let builder = new_thread_menu_builder.clone();
3985                    move |window, cx| builder(window, cx)
3986                })
3987                .with_handle(self.new_thread_menu_handle.clone())
3988                .anchor(Corner::TopLeft)
3989                .offset(gpui::Point {
3990                    x: px(1.0),
3991                    y: px(1.0),
3992                });
3993
3994            base_container
3995                .child(
3996                    h_flex()
3997                        .size_full()
3998                        .gap(DynamicSpacing::Base04.rems(cx))
3999                        .pl(DynamicSpacing::Base04.rems(cx))
4000                        .child(agent_selector_menu)
4001                        .child(self.render_start_thread_in_selector(cx)),
4002                )
4003                .child(
4004                    h_flex()
4005                        .h_full()
4006                        .flex_none()
4007                        .gap_1()
4008                        .pl_1()
4009                        .pr_1()
4010                        .when(show_history_menu && !has_v2_flag, |this| {
4011                            this.child(self.render_recent_entries_menu(
4012                                IconName::MenuAltTemp,
4013                                Corner::TopRight,
4014                                cx,
4015                            ))
4016                        })
4017                        .child(self.render_panel_options_menu(window, cx)),
4018                )
4019                .into_any_element()
4020        } else {
4021            let new_thread_menu = PopoverMenu::new("new_thread_menu")
4022                .trigger_with_tooltip(
4023                    IconButton::new("new_thread_menu_btn", IconName::Plus)
4024                        .icon_size(IconSize::Small),
4025                    {
4026                        move |_window, cx| {
4027                            Tooltip::for_action_in(
4028                                "New Thread\u{2026}",
4029                                &ToggleNewThreadMenu,
4030                                &focus_handle,
4031                                cx,
4032                            )
4033                        }
4034                    },
4035                )
4036                .anchor(Corner::TopRight)
4037                .with_handle(self.new_thread_menu_handle.clone())
4038                .menu(move |window, cx| new_thread_menu_builder(window, cx));
4039
4040            base_container
4041                .child(
4042                    h_flex()
4043                        .size_full()
4044                        .gap(DynamicSpacing::Base04.rems(cx))
4045                        .pl(DynamicSpacing::Base04.rems(cx))
4046                        .child(match &self.active_view {
4047                            ActiveView::History { .. } | ActiveView::Configuration => {
4048                                self.render_toolbar_back_button(cx).into_any_element()
4049                            }
4050                            _ => selected_agent.into_any_element(),
4051                        })
4052                        .child(self.render_title_view(window, cx)),
4053                )
4054                .child(
4055                    h_flex()
4056                        .h_full()
4057                        .flex_none()
4058                        .gap_1()
4059                        .pl_1()
4060                        .pr_1()
4061                        .child(new_thread_menu)
4062                        .when(show_history_menu && !has_v2_flag, |this| {
4063                            this.child(self.render_recent_entries_menu(
4064                                IconName::MenuAltTemp,
4065                                Corner::TopRight,
4066                                cx,
4067                            ))
4068                        })
4069                        .child(self.render_panel_options_menu(window, cx)),
4070                )
4071                .into_any_element()
4072        }
4073    }
4074
4075    fn render_worktree_creation_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4076        let status = self.worktree_creation_status.as_ref()?;
4077        match status {
4078            WorktreeCreationStatus::Creating => Some(
4079                h_flex()
4080                    .w_full()
4081                    .px(DynamicSpacing::Base06.rems(cx))
4082                    .py(DynamicSpacing::Base02.rems(cx))
4083                    .gap_2()
4084                    .bg(cx.theme().colors().surface_background)
4085                    .border_b_1()
4086                    .border_color(cx.theme().colors().border)
4087                    .child(SpinnerLabel::new().size(LabelSize::Small))
4088                    .child(
4089                        Label::new("Creating worktree…")
4090                            .color(Color::Muted)
4091                            .size(LabelSize::Small),
4092                    )
4093                    .into_any_element(),
4094            ),
4095            WorktreeCreationStatus::Error(message) => Some(
4096                h_flex()
4097                    .w_full()
4098                    .px(DynamicSpacing::Base06.rems(cx))
4099                    .py(DynamicSpacing::Base02.rems(cx))
4100                    .gap_2()
4101                    .bg(cx.theme().colors().surface_background)
4102                    .border_b_1()
4103                    .border_color(cx.theme().colors().border)
4104                    .child(
4105                        Icon::new(IconName::Warning)
4106                            .size(IconSize::Small)
4107                            .color(Color::Warning),
4108                    )
4109                    .child(
4110                        Label::new(message.clone())
4111                            .color(Color::Warning)
4112                            .size(LabelSize::Small)
4113                            .truncate(),
4114                    )
4115                    .into_any_element(),
4116            ),
4117        }
4118    }
4119
4120    fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
4121        if TrialEndUpsell::dismissed() {
4122            return false;
4123        }
4124
4125        match &self.active_view {
4126            ActiveView::TextThread { .. } => {
4127                if LanguageModelRegistry::global(cx)
4128                    .read(cx)
4129                    .default_model()
4130                    .is_some_and(|model| {
4131                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4132                    })
4133                {
4134                    return false;
4135                }
4136            }
4137            ActiveView::Uninitialized
4138            | ActiveView::AgentThread { .. }
4139            | ActiveView::History { .. }
4140            | ActiveView::Configuration => return false,
4141        }
4142
4143        let plan = self.user_store.read(cx).plan();
4144        let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
4145
4146        plan.is_some_and(|plan| plan == Plan::ZedFree) && has_previous_trial
4147    }
4148
4149    fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
4150        if self.on_boarding_upsell_dismissed.load(Ordering::Acquire) {
4151            return false;
4152        }
4153
4154        let user_store = self.user_store.read(cx);
4155
4156        if user_store.plan().is_some_and(|plan| plan == Plan::ZedPro)
4157            && user_store
4158                .subscription_period()
4159                .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
4160                .is_some_and(|date| date < chrono::Utc::now())
4161        {
4162            OnboardingUpsell::set_dismissed(true, cx);
4163            self.on_boarding_upsell_dismissed
4164                .store(true, Ordering::Release);
4165            return false;
4166        }
4167
4168        let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
4169            .visible_providers()
4170            .iter()
4171            .any(|provider| {
4172                provider.is_authenticated(cx)
4173                    && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4174            });
4175
4176        match &self.active_view {
4177            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
4178                false
4179            }
4180            ActiveView::AgentThread {
4181                conversation_view, ..
4182            } if conversation_view.read(cx).as_native_thread(cx).is_none() => false,
4183            ActiveView::AgentThread { conversation_view } => {
4184                let history_is_empty = conversation_view
4185                    .read(cx)
4186                    .history()
4187                    .is_none_or(|h| h.read(cx).is_empty());
4188                history_is_empty || !has_configured_non_zed_providers
4189            }
4190            ActiveView::TextThread { .. } => {
4191                let history_is_empty = self.text_thread_history.read(cx).is_empty();
4192                history_is_empty || !has_configured_non_zed_providers
4193            }
4194        }
4195    }
4196
4197    fn render_onboarding(
4198        &self,
4199        _window: &mut Window,
4200        cx: &mut Context<Self>,
4201    ) -> Option<impl IntoElement> {
4202        if !self.should_render_onboarding(cx) {
4203            return None;
4204        }
4205
4206        let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
4207
4208        Some(
4209            div()
4210                .when(text_thread_view, |this| {
4211                    this.bg(cx.theme().colors().editor_background)
4212                })
4213                .child(self.onboarding.clone()),
4214        )
4215    }
4216
4217    fn render_trial_end_upsell(
4218        &self,
4219        _window: &mut Window,
4220        cx: &mut Context<Self>,
4221    ) -> Option<impl IntoElement> {
4222        if !self.should_render_trial_end_upsell(cx) {
4223            return None;
4224        }
4225
4226        Some(
4227            v_flex()
4228                .absolute()
4229                .inset_0()
4230                .size_full()
4231                .bg(cx.theme().colors().panel_background)
4232                .opacity(0.85)
4233                .block_mouse_except_scroll()
4234                .child(EndTrialUpsell::new(Arc::new({
4235                    let this = cx.entity();
4236                    move |_, cx| {
4237                        this.update(cx, |_this, cx| {
4238                            TrialEndUpsell::set_dismissed(true, cx);
4239                            cx.notify();
4240                        });
4241                    }
4242                }))),
4243        )
4244    }
4245
4246    fn emit_configuration_error_telemetry_if_needed(
4247        &mut self,
4248        configuration_error: Option<&ConfigurationError>,
4249    ) {
4250        let error_kind = configuration_error.map(|err| match err {
4251            ConfigurationError::NoProvider => "no_provider",
4252            ConfigurationError::ModelNotFound => "model_not_found",
4253            ConfigurationError::ProviderNotAuthenticated(_) => "provider_not_authenticated",
4254        });
4255
4256        let error_kind_string = error_kind.map(String::from);
4257
4258        if self.last_configuration_error_telemetry == error_kind_string {
4259            return;
4260        }
4261
4262        self.last_configuration_error_telemetry = error_kind_string;
4263
4264        if let Some(kind) = error_kind {
4265            let message = configuration_error
4266                .map(|err| err.to_string())
4267                .unwrap_or_default();
4268
4269            telemetry::event!("Agent Panel Error Shown", kind = kind, message = message,);
4270        }
4271    }
4272
4273    fn render_configuration_error(
4274        &self,
4275        border_bottom: bool,
4276        configuration_error: &ConfigurationError,
4277        focus_handle: &FocusHandle,
4278        cx: &mut App,
4279    ) -> impl IntoElement {
4280        let zed_provider_configured = AgentSettings::get_global(cx)
4281            .default_model
4282            .as_ref()
4283            .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
4284
4285        let callout = if zed_provider_configured {
4286            Callout::new()
4287                .icon(IconName::Warning)
4288                .severity(Severity::Warning)
4289                .when(border_bottom, |this| {
4290                    this.border_position(ui::BorderPosition::Bottom)
4291                })
4292                .title("Sign in to continue using Zed as your LLM provider.")
4293                .actions_slot(
4294                    Button::new("sign_in", "Sign In")
4295                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4296                        .label_size(LabelSize::Small)
4297                        .on_click({
4298                            let workspace = self.workspace.clone();
4299                            move |_, _, cx| {
4300                                let Ok(client) =
4301                                    workspace.update(cx, |workspace, _| workspace.client().clone())
4302                                else {
4303                                    return;
4304                                };
4305
4306                                cx.spawn(async move |cx| {
4307                                    client.sign_in_with_optional_connect(true, cx).await
4308                                })
4309                                .detach_and_log_err(cx);
4310                            }
4311                        }),
4312                )
4313        } else {
4314            Callout::new()
4315                .icon(IconName::Warning)
4316                .severity(Severity::Warning)
4317                .when(border_bottom, |this| {
4318                    this.border_position(ui::BorderPosition::Bottom)
4319                })
4320                .title(configuration_error.to_string())
4321                .actions_slot(
4322                    Button::new("settings", "Configure")
4323                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4324                        .label_size(LabelSize::Small)
4325                        .key_binding(
4326                            KeyBinding::for_action_in(&OpenSettings, focus_handle, cx)
4327                                .map(|kb| kb.size(rems_from_px(12.))),
4328                        )
4329                        .on_click(|_event, window, cx| {
4330                            window.dispatch_action(OpenSettings.boxed_clone(), cx)
4331                        }),
4332                )
4333        };
4334
4335        match configuration_error {
4336            ConfigurationError::ModelNotFound
4337            | ConfigurationError::ProviderNotAuthenticated(_)
4338            | ConfigurationError::NoProvider => callout.into_any_element(),
4339        }
4340    }
4341
4342    fn render_text_thread(
4343        &self,
4344        text_thread_editor: &Entity<TextThreadEditor>,
4345        buffer_search_bar: &Entity<BufferSearchBar>,
4346        window: &mut Window,
4347        cx: &mut Context<Self>,
4348    ) -> Div {
4349        let mut registrar = buffer_search::DivRegistrar::new(
4350            |this, _, _cx| match &this.active_view {
4351                ActiveView::TextThread {
4352                    buffer_search_bar, ..
4353                } => Some(buffer_search_bar.clone()),
4354                _ => None,
4355            },
4356            cx,
4357        );
4358        BufferSearchBar::register(&mut registrar);
4359        registrar
4360            .into_div()
4361            .size_full()
4362            .relative()
4363            .map(|parent| {
4364                buffer_search_bar.update(cx, |buffer_search_bar, cx| {
4365                    if buffer_search_bar.is_dismissed() {
4366                        return parent;
4367                    }
4368                    parent.child(
4369                        div()
4370                            .p(DynamicSpacing::Base08.rems(cx))
4371                            .border_b_1()
4372                            .border_color(cx.theme().colors().border_variant)
4373                            .bg(cx.theme().colors().editor_background)
4374                            .child(buffer_search_bar.render(window, cx)),
4375                    )
4376                })
4377            })
4378            .child(text_thread_editor.clone())
4379            .child(self.render_drag_target(cx))
4380    }
4381
4382    fn render_drag_target(&self, cx: &Context<Self>) -> Div {
4383        let is_local = self.project.read(cx).is_local();
4384        div()
4385            .invisible()
4386            .absolute()
4387            .top_0()
4388            .right_0()
4389            .bottom_0()
4390            .left_0()
4391            .bg(cx.theme().colors().drop_target_background)
4392            .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
4393            .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
4394            .when(is_local, |this| {
4395                this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
4396            })
4397            .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
4398                let item = tab.pane.read(cx).item_for_index(tab.ix);
4399                let project_paths = item
4400                    .and_then(|item| item.project_path(cx))
4401                    .into_iter()
4402                    .collect::<Vec<_>>();
4403                this.handle_drop(project_paths, vec![], window, cx);
4404            }))
4405            .on_drop(
4406                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
4407                    let project_paths = selection
4408                        .items()
4409                        .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
4410                        .collect::<Vec<_>>();
4411                    this.handle_drop(project_paths, vec![], window, cx);
4412                }),
4413            )
4414            .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
4415                let tasks = paths
4416                    .paths()
4417                    .iter()
4418                    .map(|path| {
4419                        Workspace::project_path_for_path(this.project.clone(), path, false, cx)
4420                    })
4421                    .collect::<Vec<_>>();
4422                cx.spawn_in(window, async move |this, cx| {
4423                    let mut paths = vec![];
4424                    let mut added_worktrees = vec![];
4425                    let opened_paths = futures::future::join_all(tasks).await;
4426                    for entry in opened_paths {
4427                        if let Some((worktree, project_path)) = entry.log_err() {
4428                            added_worktrees.push(worktree);
4429                            paths.push(project_path);
4430                        }
4431                    }
4432                    this.update_in(cx, |this, window, cx| {
4433                        this.handle_drop(paths, added_worktrees, window, cx);
4434                    })
4435                    .ok();
4436                })
4437                .detach();
4438            }))
4439    }
4440
4441    fn handle_drop(
4442        &mut self,
4443        paths: Vec<ProjectPath>,
4444        added_worktrees: Vec<Entity<Worktree>>,
4445        window: &mut Window,
4446        cx: &mut Context<Self>,
4447    ) {
4448        match &self.active_view {
4449            ActiveView::AgentThread { conversation_view } => {
4450                conversation_view.update(cx, |conversation_view, cx| {
4451                    conversation_view.insert_dragged_files(paths, added_worktrees, window, cx);
4452                });
4453            }
4454            ActiveView::TextThread {
4455                text_thread_editor, ..
4456            } => {
4457                text_thread_editor.update(cx, |text_thread_editor, cx| {
4458                    TextThreadEditor::insert_dragged_files(
4459                        text_thread_editor,
4460                        paths,
4461                        added_worktrees,
4462                        window,
4463                        cx,
4464                    );
4465                });
4466            }
4467            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4468        }
4469    }
4470
4471    fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
4472        if !self.show_trust_workspace_message {
4473            return None;
4474        }
4475
4476        let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
4477
4478        Some(
4479            Callout::new()
4480                .icon(IconName::Warning)
4481                .severity(Severity::Warning)
4482                .border_position(ui::BorderPosition::Bottom)
4483                .title("You're in Restricted Mode")
4484                .description(description)
4485                .actions_slot(
4486                    Button::new("open-trust-modal", "Configure Project Trust")
4487                        .label_size(LabelSize::Small)
4488                        .style(ButtonStyle::Outlined)
4489                        .on_click({
4490                            cx.listener(move |this, _, window, cx| {
4491                                this.workspace
4492                                    .update(cx, |workspace, cx| {
4493                                        workspace
4494                                            .show_worktree_trust_security_modal(true, window, cx)
4495                                    })
4496                                    .log_err();
4497                            })
4498                        }),
4499                ),
4500        )
4501    }
4502
4503    fn key_context(&self) -> KeyContext {
4504        let mut key_context = KeyContext::new_with_defaults();
4505        key_context.add("AgentPanel");
4506        match &self.active_view {
4507            ActiveView::AgentThread { .. } => key_context.add("acp_thread"),
4508            ActiveView::TextThread { .. } => key_context.add("text_thread"),
4509            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4510        }
4511        key_context
4512    }
4513}
4514
4515impl Render for AgentPanel {
4516    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4517        // WARNING: Changes to this element hierarchy can have
4518        // non-obvious implications to the layout of children.
4519        //
4520        // If you need to change it, please confirm:
4521        // - The message editor expands (cmd-option-esc) correctly
4522        // - When expanded, the buttons at the bottom of the panel are displayed correctly
4523        // - Font size works as expected and can be changed with cmd-+/cmd-
4524        // - Scrolling in all views works as expected
4525        // - Files can be dropped into the panel
4526        let content = v_flex()
4527            .relative()
4528            .size_full()
4529            .justify_between()
4530            .key_context(self.key_context())
4531            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
4532                this.new_thread(action, window, cx);
4533            }))
4534            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
4535                this.open_history(window, cx);
4536            }))
4537            .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
4538                this.open_configuration(window, cx);
4539            }))
4540            .on_action(cx.listener(Self::open_active_thread_as_markdown))
4541            .on_action(cx.listener(Self::deploy_rules_library))
4542            .on_action(cx.listener(Self::go_back))
4543            .on_action(cx.listener(Self::toggle_navigation_menu))
4544            .on_action(cx.listener(Self::toggle_options_menu))
4545            .on_action(cx.listener(Self::increase_font_size))
4546            .on_action(cx.listener(Self::decrease_font_size))
4547            .on_action(cx.listener(Self::reset_font_size))
4548            .on_action(cx.listener(Self::toggle_zoom))
4549            .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
4550                if let Some(conversation_view) = this.active_conversation() {
4551                    conversation_view.update(cx, |conversation_view, cx| {
4552                        conversation_view.reauthenticate(window, cx)
4553                    })
4554                }
4555            }))
4556            .child(self.render_toolbar(window, cx))
4557            .children(self.render_worktree_creation_status(cx))
4558            .children(self.render_workspace_trust_message(cx))
4559            .children(self.render_onboarding(window, cx))
4560            .map(|parent| {
4561                // Emit configuration error telemetry before entering the match to avoid borrow conflicts
4562                if matches!(&self.active_view, ActiveView::TextThread { .. }) {
4563                    let model_registry = LanguageModelRegistry::read_global(cx);
4564                    let configuration_error =
4565                        model_registry.configuration_error(model_registry.default_model(), cx);
4566                    self.emit_configuration_error_telemetry_if_needed(configuration_error.as_ref());
4567                }
4568
4569                match &self.active_view {
4570                    ActiveView::Uninitialized => parent,
4571                    ActiveView::AgentThread {
4572                        conversation_view, ..
4573                    } => parent
4574                        .child(conversation_view.clone())
4575                        .child(self.render_drag_target(cx)),
4576                    ActiveView::History { history: kind } => match kind {
4577                        History::AgentThreads { view } => parent.child(view.clone()),
4578                        History::TextThreads => parent.child(self.text_thread_history.clone()),
4579                    },
4580                    ActiveView::TextThread {
4581                        text_thread_editor,
4582                        buffer_search_bar,
4583                        ..
4584                    } => {
4585                        let model_registry = LanguageModelRegistry::read_global(cx);
4586                        let configuration_error =
4587                            model_registry.configuration_error(model_registry.default_model(), cx);
4588
4589                        parent
4590                            .map(|this| {
4591                                if !self.should_render_onboarding(cx)
4592                                    && let Some(err) = configuration_error.as_ref()
4593                                {
4594                                    this.child(self.render_configuration_error(
4595                                        true,
4596                                        err,
4597                                        &self.focus_handle(cx),
4598                                        cx,
4599                                    ))
4600                                } else {
4601                                    this
4602                                }
4603                            })
4604                            .child(self.render_text_thread(
4605                                text_thread_editor,
4606                                buffer_search_bar,
4607                                window,
4608                                cx,
4609                            ))
4610                    }
4611                    ActiveView::Configuration => parent.children(self.configuration.clone()),
4612                }
4613            })
4614            .children(self.render_trial_end_upsell(window, cx));
4615
4616        match self.active_view.which_font_size_used() {
4617            WhichFontSize::AgentFont => {
4618                WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
4619                    .size_full()
4620                    .child(content)
4621                    .into_any()
4622            }
4623            _ => content.into_any(),
4624        }
4625    }
4626}
4627
4628struct PromptLibraryInlineAssist {
4629    workspace: WeakEntity<Workspace>,
4630}
4631
4632impl PromptLibraryInlineAssist {
4633    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
4634        Self { workspace }
4635    }
4636}
4637
4638impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
4639    fn assist(
4640        &self,
4641        prompt_editor: &Entity<Editor>,
4642        initial_prompt: Option<String>,
4643        window: &mut Window,
4644        cx: &mut Context<RulesLibrary>,
4645    ) {
4646        InlineAssistant::update_global(cx, |assistant, cx| {
4647            let Some(workspace) = self.workspace.upgrade() else {
4648                return;
4649            };
4650            let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4651                return;
4652            };
4653            let Some(history) = panel
4654                .read(cx)
4655                .connection_store()
4656                .read(cx)
4657                .entry(&crate::Agent::NativeAgent)
4658                .and_then(|s| s.read(cx).history())
4659            else {
4660                log::error!("No connection entry found for native agent");
4661                return;
4662            };
4663            let project = workspace.read(cx).project().downgrade();
4664            let panel = panel.read(cx);
4665            let thread_store = panel.thread_store().clone();
4666            assistant.assist(
4667                prompt_editor,
4668                self.workspace.clone(),
4669                project,
4670                thread_store,
4671                None,
4672                history.downgrade(),
4673                initial_prompt,
4674                window,
4675                cx,
4676            );
4677        })
4678    }
4679
4680    fn focus_agent_panel(
4681        &self,
4682        workspace: &mut Workspace,
4683        window: &mut Window,
4684        cx: &mut Context<Workspace>,
4685    ) -> bool {
4686        workspace.focus_panel::<AgentPanel>(window, cx).is_some()
4687    }
4688}
4689
4690pub struct ConcreteAssistantPanelDelegate;
4691
4692impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
4693    fn active_text_thread_editor(
4694        &self,
4695        workspace: &mut Workspace,
4696        _window: &mut Window,
4697        cx: &mut Context<Workspace>,
4698    ) -> Option<Entity<TextThreadEditor>> {
4699        let panel = workspace.panel::<AgentPanel>(cx)?;
4700        panel.read(cx).active_text_thread_editor()
4701    }
4702
4703    fn open_local_text_thread(
4704        &self,
4705        workspace: &mut Workspace,
4706        path: Arc<Path>,
4707        window: &mut Window,
4708        cx: &mut Context<Workspace>,
4709    ) -> Task<Result<()>> {
4710        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4711            return Task::ready(Err(anyhow!("Agent panel not found")));
4712        };
4713
4714        panel.update(cx, |panel, cx| {
4715            panel.open_saved_text_thread(path, window, cx)
4716        })
4717    }
4718
4719    fn open_remote_text_thread(
4720        &self,
4721        _workspace: &mut Workspace,
4722        _text_thread_id: assistant_text_thread::TextThreadId,
4723        _window: &mut Window,
4724        _cx: &mut Context<Workspace>,
4725    ) -> Task<Result<Entity<TextThreadEditor>>> {
4726        Task::ready(Err(anyhow!("opening remote context not implemented")))
4727    }
4728
4729    fn quote_selection(
4730        &self,
4731        workspace: &mut Workspace,
4732        selection_ranges: Vec<Range<Anchor>>,
4733        buffer: Entity<MultiBuffer>,
4734        window: &mut Window,
4735        cx: &mut Context<Workspace>,
4736    ) {
4737        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4738            return;
4739        };
4740
4741        if !panel.focus_handle(cx).contains_focused(window, cx) {
4742            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4743        }
4744
4745        panel.update(cx, |_, cx| {
4746            // Wait to create a new context until the workspace is no longer
4747            // being updated.
4748            cx.defer_in(window, move |panel, window, cx| {
4749                if let Some(conversation_view) = panel.active_conversation() {
4750                    conversation_view.update(cx, |conversation_view, cx| {
4751                        conversation_view.insert_selections(window, cx);
4752                    });
4753                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4754                    let snapshot = buffer.read(cx).snapshot(cx);
4755                    let selection_ranges = selection_ranges
4756                        .into_iter()
4757                        .map(|range| range.to_point(&snapshot))
4758                        .collect::<Vec<_>>();
4759
4760                    text_thread_editor.update(cx, |text_thread_editor, cx| {
4761                        text_thread_editor.quote_ranges(selection_ranges, snapshot, window, cx)
4762                    });
4763                }
4764            });
4765        });
4766    }
4767
4768    fn quote_terminal_text(
4769        &self,
4770        workspace: &mut Workspace,
4771        text: String,
4772        window: &mut Window,
4773        cx: &mut Context<Workspace>,
4774    ) {
4775        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4776            return;
4777        };
4778
4779        if !panel.focus_handle(cx).contains_focused(window, cx) {
4780            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4781        }
4782
4783        panel.update(cx, |_, cx| {
4784            // Wait to create a new context until the workspace is no longer
4785            // being updated.
4786            cx.defer_in(window, move |panel, window, cx| {
4787                if let Some(conversation_view) = panel.active_conversation() {
4788                    conversation_view.update(cx, |conversation_view, cx| {
4789                        conversation_view.insert_terminal_text(text, window, cx);
4790                    });
4791                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4792                    text_thread_editor.update(cx, |text_thread_editor, cx| {
4793                        text_thread_editor.quote_terminal_text(text, window, cx)
4794                    });
4795                }
4796            });
4797        });
4798    }
4799}
4800
4801struct OnboardingUpsell;
4802
4803impl Dismissable for OnboardingUpsell {
4804    const KEY: &'static str = "dismissed-trial-upsell";
4805}
4806
4807struct TrialEndUpsell;
4808
4809impl Dismissable for TrialEndUpsell {
4810    const KEY: &'static str = "dismissed-trial-end-upsell";
4811}
4812
4813/// Test-only helper methods
4814#[cfg(any(test, feature = "test-support"))]
4815impl AgentPanel {
4816    pub fn test_new(
4817        workspace: &Workspace,
4818        text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
4819        window: &mut Window,
4820        cx: &mut Context<Self>,
4821    ) -> Self {
4822        Self::new(workspace, text_thread_store, None, window, cx)
4823    }
4824
4825    /// Opens an external thread using an arbitrary AgentServer.
4826    ///
4827    /// This is a test-only helper that allows visual tests and integration tests
4828    /// to inject a stub server without modifying production code paths.
4829    /// Not compiled into production builds.
4830    pub fn open_external_thread_with_server(
4831        &mut self,
4832        server: Rc<dyn AgentServer>,
4833        window: &mut Window,
4834        cx: &mut Context<Self>,
4835    ) {
4836        let workspace = self.workspace.clone();
4837        let project = self.project.clone();
4838
4839        let ext_agent = Agent::Custom {
4840            id: server.agent_id(),
4841        };
4842
4843        self.create_agent_thread(
4844            server, None, None, None, None, workspace, project, ext_agent, true, window, cx,
4845        );
4846    }
4847
4848    /// Returns the currently active thread view, if any.
4849    ///
4850    /// This is a test-only accessor that exposes the private `active_thread_view()`
4851    /// method for test assertions. Not compiled into production builds.
4852    pub fn active_thread_view_for_tests(&self) -> Option<&Entity<ConversationView>> {
4853        self.active_conversation()
4854    }
4855
4856    /// Sets the start_thread_in value directly, bypassing validation.
4857    ///
4858    /// This is a test-only helper for visual tests that need to show specific
4859    /// start_thread_in states without requiring a real git repository.
4860    pub fn set_start_thread_in_for_tests(&mut self, target: StartThreadIn, cx: &mut Context<Self>) {
4861        self.start_thread_in = target;
4862        cx.notify();
4863    }
4864
4865    /// Returns the current worktree creation status.
4866    ///
4867    /// This is a test-only helper for visual tests.
4868    pub fn worktree_creation_status_for_tests(&self) -> Option<&WorktreeCreationStatus> {
4869        self.worktree_creation_status.as_ref()
4870    }
4871
4872    /// Sets the worktree creation status directly.
4873    ///
4874    /// This is a test-only helper for visual tests that need to show the
4875    /// "Creating worktree…" spinner or error banners.
4876    pub fn set_worktree_creation_status_for_tests(
4877        &mut self,
4878        status: Option<WorktreeCreationStatus>,
4879        cx: &mut Context<Self>,
4880    ) {
4881        self.worktree_creation_status = status;
4882        cx.notify();
4883    }
4884
4885    /// Opens the history view.
4886    ///
4887    /// This is a test-only helper that exposes the private `open_history()`
4888    /// method for visual tests.
4889    pub fn open_history_for_tests(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4890        self.open_history(window, cx);
4891    }
4892
4893    /// Opens the start_thread_in selector popover menu.
4894    ///
4895    /// This is a test-only helper for visual tests.
4896    pub fn open_start_thread_in_menu_for_tests(
4897        &mut self,
4898        window: &mut Window,
4899        cx: &mut Context<Self>,
4900    ) {
4901        self.start_thread_in_menu_handle.show(window, cx);
4902    }
4903
4904    /// Dismisses the start_thread_in dropdown menu.
4905    ///
4906    /// This is a test-only helper for visual tests.
4907    pub fn close_start_thread_in_menu_for_tests(&mut self, cx: &mut Context<Self>) {
4908        self.start_thread_in_menu_handle.hide(cx);
4909    }
4910}
4911
4912#[cfg(test)]
4913mod tests {
4914    use super::*;
4915    use crate::conversation_view::tests::{StubAgentServer, init_test};
4916    use crate::test_support::{active_session_id, open_thread_with_connection, send_message};
4917    use acp_thread::{StubAgentConnection, ThreadStatus};
4918    use assistant_text_thread::TextThreadStore;
4919    use feature_flags::FeatureFlagAppExt;
4920    use fs::FakeFs;
4921    use gpui::{TestAppContext, VisualTestContext};
4922    use project::Project;
4923    use project::agent_server_store::CODEX_ID;
4924    use serde_json::json;
4925    use workspace::MultiWorkspace;
4926
4927    #[gpui::test]
4928    async fn test_active_thread_serialize_and_load_round_trip(cx: &mut TestAppContext) {
4929        init_test(cx);
4930        cx.update(|cx| {
4931            cx.update_flags(true, vec!["agent-v2".to_string()]);
4932            agent::ThreadStore::init_global(cx);
4933            language_model::LanguageModelRegistry::test(cx);
4934        });
4935
4936        // --- Create a MultiWorkspace window with two workspaces ---
4937        let fs = FakeFs::new(cx.executor());
4938        let project_a = Project::test(fs.clone(), [], cx).await;
4939        let project_b = Project::test(fs, [], cx).await;
4940
4941        let multi_workspace =
4942            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
4943
4944        let workspace_a = multi_workspace
4945            .read_with(cx, |multi_workspace, _cx| {
4946                multi_workspace.workspace().clone()
4947            })
4948            .unwrap();
4949
4950        let workspace_b = multi_workspace
4951            .update(cx, |multi_workspace, window, cx| {
4952                multi_workspace.test_add_workspace(project_b.clone(), window, cx)
4953            })
4954            .unwrap();
4955
4956        workspace_a.update(cx, |workspace, _cx| {
4957            workspace.set_random_database_id();
4958        });
4959        workspace_b.update(cx, |workspace, _cx| {
4960            workspace.set_random_database_id();
4961        });
4962
4963        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
4964
4965        // --- Set up workspace A: width=300, with an active thread ---
4966        let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
4967            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_a.clone(), cx));
4968            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
4969        });
4970
4971        panel_a.update(cx, |panel, _cx| {
4972            panel.width = Some(px(300.0));
4973        });
4974
4975        panel_a.update_in(cx, |panel, window, cx| {
4976            panel.open_external_thread_with_server(
4977                Rc::new(StubAgentServer::default_response()),
4978                window,
4979                cx,
4980            );
4981        });
4982
4983        cx.run_until_parked();
4984
4985        panel_a.read_with(cx, |panel, cx| {
4986            assert!(
4987                panel.active_agent_thread(cx).is_some(),
4988                "workspace A should have an active thread after connection"
4989            );
4990        });
4991
4992        let agent_type_a = panel_a.read_with(cx, |panel, _cx| panel.selected_agent_type.clone());
4993
4994        // --- Set up workspace B: ClaudeCode, width=400, no active thread ---
4995        let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
4996            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_b.clone(), cx));
4997            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
4998        });
4999
5000        panel_b.update(cx, |panel, _cx| {
5001            panel.width = Some(px(400.0));
5002            panel.selected_agent_type = AgentType::Custom {
5003                id: "claude-acp".into(),
5004            };
5005        });
5006
5007        // --- Serialize both panels ---
5008        panel_a.update(cx, |panel, cx| panel.serialize(cx));
5009        panel_b.update(cx, |panel, cx| panel.serialize(cx));
5010        cx.run_until_parked();
5011
5012        // --- Load fresh panels for each workspace and verify independent state ---
5013        let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5014
5015        let async_cx = cx.update(|window, cx| window.to_async(cx));
5016        let loaded_a = AgentPanel::load(workspace_a.downgrade(), prompt_builder.clone(), async_cx)
5017            .await
5018            .expect("panel A load should succeed");
5019        cx.run_until_parked();
5020
5021        let async_cx = cx.update(|window, cx| window.to_async(cx));
5022        let loaded_b = AgentPanel::load(workspace_b.downgrade(), prompt_builder.clone(), async_cx)
5023            .await
5024            .expect("panel B load should succeed");
5025        cx.run_until_parked();
5026
5027        // Workspace A should restore its thread, width, and agent type
5028        loaded_a.read_with(cx, |panel, _cx| {
5029            assert_eq!(
5030                panel.width,
5031                Some(px(300.0)),
5032                "workspace A width should be restored"
5033            );
5034            assert_eq!(
5035                panel.selected_agent_type, agent_type_a,
5036                "workspace A agent type should be restored"
5037            );
5038            assert!(
5039                panel.active_conversation().is_some(),
5040                "workspace A should have its active thread restored"
5041            );
5042        });
5043
5044        // Workspace B should restore its own width and agent type, with no thread
5045        loaded_b.read_with(cx, |panel, _cx| {
5046            assert_eq!(
5047                panel.width,
5048                Some(px(400.0)),
5049                "workspace B width should be restored"
5050            );
5051            assert_eq!(
5052                panel.selected_agent_type,
5053                AgentType::Custom {
5054                    id: "claude-acp".into()
5055                },
5056                "workspace B agent type should be restored"
5057            );
5058            assert!(
5059                panel.active_conversation().is_none(),
5060                "workspace B should have no active thread"
5061            );
5062        });
5063    }
5064
5065    // Simple regression test
5066    #[gpui::test]
5067    async fn test_new_text_thread_action_handler(cx: &mut TestAppContext) {
5068        init_test(cx);
5069
5070        let fs = FakeFs::new(cx.executor());
5071
5072        cx.update(|cx| {
5073            cx.update_flags(true, vec!["agent-v2".to_string()]);
5074            agent::ThreadStore::init_global(cx);
5075            language_model::LanguageModelRegistry::test(cx);
5076            let slash_command_registry =
5077                assistant_slash_command::SlashCommandRegistry::default_global(cx);
5078            slash_command_registry
5079                .register_command(assistant_slash_commands::DefaultSlashCommand, false);
5080            <dyn fs::Fs>::set_global(fs.clone(), cx);
5081        });
5082
5083        let project = Project::test(fs.clone(), [], cx).await;
5084
5085        let multi_workspace =
5086            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5087
5088        let workspace_a = multi_workspace
5089            .read_with(cx, |multi_workspace, _cx| {
5090                multi_workspace.workspace().clone()
5091            })
5092            .unwrap();
5093
5094        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5095
5096        workspace_a.update_in(cx, |workspace, window, cx| {
5097            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5098            let panel =
5099                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5100            workspace.add_panel(panel, window, cx);
5101        });
5102
5103        cx.run_until_parked();
5104
5105        workspace_a.update_in(cx, |_, window, cx| {
5106            window.dispatch_action(NewTextThread.boxed_clone(), cx);
5107        });
5108
5109        cx.run_until_parked();
5110    }
5111
5112    /// Extracts the text from a Text content block, panicking if it's not Text.
5113    fn expect_text_block(block: &acp::ContentBlock) -> &str {
5114        match block {
5115            acp::ContentBlock::Text(t) => t.text.as_str(),
5116            other => panic!("expected Text block, got {:?}", other),
5117        }
5118    }
5119
5120    /// Extracts the (text_content, uri) from a Resource content block, panicking
5121    /// if it's not a TextResourceContents resource.
5122    fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
5123        match block {
5124            acp::ContentBlock::Resource(r) => match &r.resource {
5125                acp::EmbeddedResourceResource::TextResourceContents(t) => {
5126                    (t.text.as_str(), t.uri.as_str())
5127                }
5128                other => panic!("expected TextResourceContents, got {:?}", other),
5129            },
5130            other => panic!("expected Resource block, got {:?}", other),
5131        }
5132    }
5133
5134    #[test]
5135    fn test_build_conflict_resolution_prompt_single_conflict() {
5136        let conflicts = vec![ConflictContent {
5137            file_path: "src/main.rs".to_string(),
5138            conflict_text: "<<<<<<< HEAD\nlet x = 1;\n=======\nlet x = 2;\n>>>>>>> feature"
5139                .to_string(),
5140            ours_branch_name: "HEAD".to_string(),
5141            theirs_branch_name: "feature".to_string(),
5142        }];
5143
5144        let blocks = build_conflict_resolution_prompt(&conflicts);
5145        // 2 Text blocks + 1 ResourceLink + 1 Resource for the conflict
5146        assert_eq!(
5147            blocks.len(),
5148            4,
5149            "expected 2 text + 1 resource link + 1 resource block"
5150        );
5151
5152        let intro_text = expect_text_block(&blocks[0]);
5153        assert!(
5154            intro_text.contains("Please resolve the following merge conflict in"),
5155            "prompt should include single-conflict intro text"
5156        );
5157
5158        match &blocks[1] {
5159            acp::ContentBlock::ResourceLink(link) => {
5160                assert!(
5161                    link.uri.contains("file://"),
5162                    "resource link URI should use file scheme"
5163                );
5164                assert!(
5165                    link.uri.contains("main.rs"),
5166                    "resource link URI should reference file path"
5167                );
5168            }
5169            other => panic!("expected ResourceLink block, got {:?}", other),
5170        }
5171
5172        let body_text = expect_text_block(&blocks[2]);
5173        assert!(
5174            body_text.contains("`HEAD` (ours)"),
5175            "prompt should mention ours branch"
5176        );
5177        assert!(
5178            body_text.contains("`feature` (theirs)"),
5179            "prompt should mention theirs branch"
5180        );
5181        assert!(
5182            body_text.contains("editing the file directly"),
5183            "prompt should instruct the agent to edit the file"
5184        );
5185
5186        let (resource_text, resource_uri) = expect_resource_block(&blocks[3]);
5187        assert!(
5188            resource_text.contains("<<<<<<< HEAD"),
5189            "resource should contain the conflict text"
5190        );
5191        assert!(
5192            resource_uri.contains("merge-conflict"),
5193            "resource URI should use the merge-conflict scheme"
5194        );
5195        assert!(
5196            resource_uri.contains("main.rs"),
5197            "resource URI should reference the file path"
5198        );
5199    }
5200
5201    #[test]
5202    fn test_build_conflict_resolution_prompt_multiple_conflicts_same_file() {
5203        let conflicts = vec![
5204            ConflictContent {
5205                file_path: "src/lib.rs".to_string(),
5206                conflict_text: "<<<<<<< main\nfn a() {}\n=======\nfn a_v2() {}\n>>>>>>> dev"
5207                    .to_string(),
5208                ours_branch_name: "main".to_string(),
5209                theirs_branch_name: "dev".to_string(),
5210            },
5211            ConflictContent {
5212                file_path: "src/lib.rs".to_string(),
5213                conflict_text: "<<<<<<< main\nfn b() {}\n=======\nfn b_v2() {}\n>>>>>>> dev"
5214                    .to_string(),
5215                ours_branch_name: "main".to_string(),
5216                theirs_branch_name: "dev".to_string(),
5217            },
5218        ];
5219
5220        let blocks = build_conflict_resolution_prompt(&conflicts);
5221        // 1 Text instruction + 2 Resource blocks
5222        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5223
5224        let text = expect_text_block(&blocks[0]);
5225        assert!(
5226            text.contains("all 2 merge conflicts"),
5227            "prompt should mention the total count"
5228        );
5229        assert!(
5230            text.contains("`main` (ours)"),
5231            "prompt should mention ours branch"
5232        );
5233        assert!(
5234            text.contains("`dev` (theirs)"),
5235            "prompt should mention theirs branch"
5236        );
5237        // Single file, so "file" not "files"
5238        assert!(
5239            text.contains("file directly"),
5240            "single file should use singular 'file'"
5241        );
5242
5243        let (resource_a, _) = expect_resource_block(&blocks[1]);
5244        let (resource_b, _) = expect_resource_block(&blocks[2]);
5245        assert!(
5246            resource_a.contains("fn a()"),
5247            "first resource should contain first conflict"
5248        );
5249        assert!(
5250            resource_b.contains("fn b()"),
5251            "second resource should contain second conflict"
5252        );
5253    }
5254
5255    #[test]
5256    fn test_build_conflict_resolution_prompt_multiple_conflicts_different_files() {
5257        let conflicts = vec![
5258            ConflictContent {
5259                file_path: "src/a.rs".to_string(),
5260                conflict_text: "<<<<<<< main\nA\n=======\nB\n>>>>>>> dev".to_string(),
5261                ours_branch_name: "main".to_string(),
5262                theirs_branch_name: "dev".to_string(),
5263            },
5264            ConflictContent {
5265                file_path: "src/b.rs".to_string(),
5266                conflict_text: "<<<<<<< main\nC\n=======\nD\n>>>>>>> dev".to_string(),
5267                ours_branch_name: "main".to_string(),
5268                theirs_branch_name: "dev".to_string(),
5269            },
5270        ];
5271
5272        let blocks = build_conflict_resolution_prompt(&conflicts);
5273        // 1 Text instruction + 2 Resource blocks
5274        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5275
5276        let text = expect_text_block(&blocks[0]);
5277        assert!(
5278            text.contains("files directly"),
5279            "multiple files should use plural 'files'"
5280        );
5281
5282        let (_, uri_a) = expect_resource_block(&blocks[1]);
5283        let (_, uri_b) = expect_resource_block(&blocks[2]);
5284        assert!(
5285            uri_a.contains("a.rs"),
5286            "first resource URI should reference a.rs"
5287        );
5288        assert!(
5289            uri_b.contains("b.rs"),
5290            "second resource URI should reference b.rs"
5291        );
5292    }
5293
5294    #[test]
5295    fn test_build_conflicted_files_resolution_prompt_file_paths_only() {
5296        let file_paths = vec![
5297            "src/main.rs".to_string(),
5298            "src/lib.rs".to_string(),
5299            "tests/integration.rs".to_string(),
5300        ];
5301
5302        let blocks = build_conflicted_files_resolution_prompt(&file_paths);
5303        // 1 instruction Text block + (ResourceLink + newline Text) per file
5304        assert_eq!(
5305            blocks.len(),
5306            1 + (file_paths.len() * 2),
5307            "expected instruction text plus resource links and separators"
5308        );
5309
5310        let text = expect_text_block(&blocks[0]);
5311        assert!(
5312            text.contains("unresolved merge conflicts"),
5313            "prompt should describe the task"
5314        );
5315        assert!(
5316            text.contains("conflict markers"),
5317            "prompt should mention conflict markers"
5318        );
5319
5320        for (index, path) in file_paths.iter().enumerate() {
5321            let link_index = 1 + (index * 2);
5322            let newline_index = link_index + 1;
5323
5324            match &blocks[link_index] {
5325                acp::ContentBlock::ResourceLink(link) => {
5326                    assert!(
5327                        link.uri.contains("file://"),
5328                        "resource link URI should use file scheme"
5329                    );
5330                    assert!(
5331                        link.uri.contains(path),
5332                        "resource link URI should reference file path: {path}"
5333                    );
5334                }
5335                other => panic!(
5336                    "expected ResourceLink block at index {}, got {:?}",
5337                    link_index, other
5338                ),
5339            }
5340
5341            let separator = expect_text_block(&blocks[newline_index]);
5342            assert_eq!(
5343                separator, "\n",
5344                "expected newline separator after each file"
5345            );
5346        }
5347    }
5348
5349    #[test]
5350    fn test_build_conflict_resolution_prompt_empty_conflicts() {
5351        let blocks = build_conflict_resolution_prompt(&[]);
5352        assert!(
5353            blocks.is_empty(),
5354            "empty conflicts should produce no blocks, got {} blocks",
5355            blocks.len()
5356        );
5357    }
5358
5359    #[test]
5360    fn test_build_conflicted_files_resolution_prompt_empty_paths() {
5361        let blocks = build_conflicted_files_resolution_prompt(&[]);
5362        assert!(
5363            blocks.is_empty(),
5364            "empty paths should produce no blocks, got {} blocks",
5365            blocks.len()
5366        );
5367    }
5368
5369    #[test]
5370    fn test_conflict_resource_block_structure() {
5371        let conflict = ConflictContent {
5372            file_path: "src/utils.rs".to_string(),
5373            conflict_text: "<<<<<<< HEAD\nold code\n=======\nnew code\n>>>>>>> branch".to_string(),
5374            ours_branch_name: "HEAD".to_string(),
5375            theirs_branch_name: "branch".to_string(),
5376        };
5377
5378        let block = conflict_resource_block(&conflict);
5379        let (text, uri) = expect_resource_block(&block);
5380
5381        assert_eq!(
5382            text, conflict.conflict_text,
5383            "resource text should be the raw conflict"
5384        );
5385        assert!(
5386            uri.starts_with("zed:///agent/merge-conflict"),
5387            "URI should use the zed merge-conflict scheme, got: {uri}"
5388        );
5389        assert!(uri.contains("utils.rs"), "URI should encode the file path");
5390    }
5391
5392    async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {
5393        init_test(cx);
5394        cx.update(|cx| {
5395            cx.update_flags(true, vec!["agent-v2".to_string()]);
5396            agent::ThreadStore::init_global(cx);
5397            language_model::LanguageModelRegistry::test(cx);
5398        });
5399
5400        let fs = FakeFs::new(cx.executor());
5401        let project = Project::test(fs.clone(), [], cx).await;
5402
5403        let multi_workspace =
5404            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5405
5406        let workspace = multi_workspace
5407            .read_with(cx, |mw, _cx| mw.workspace().clone())
5408            .unwrap();
5409
5410        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
5411
5412        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
5413            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5414            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5415        });
5416
5417        (panel, cx)
5418    }
5419
5420    #[gpui::test]
5421    async fn test_running_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5422        let (panel, mut cx) = setup_panel(cx).await;
5423
5424        let connection_a = StubAgentConnection::new();
5425        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5426        send_message(&panel, &mut cx);
5427
5428        let session_id_a = active_session_id(&panel, &cx);
5429
5430        // Send a chunk to keep thread A generating (don't end the turn).
5431        cx.update(|_, cx| {
5432            connection_a.send_update(
5433                session_id_a.clone(),
5434                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5435                cx,
5436            );
5437        });
5438        cx.run_until_parked();
5439
5440        // Verify thread A is generating.
5441        panel.read_with(&cx, |panel, cx| {
5442            let thread = panel.active_agent_thread(cx).unwrap();
5443            assert_eq!(thread.read(cx).status(), ThreadStatus::Generating);
5444            assert!(panel.background_threads.is_empty());
5445        });
5446
5447        // Open a new thread B — thread A should be retained in background.
5448        let connection_b = StubAgentConnection::new();
5449        open_thread_with_connection(&panel, connection_b, &mut cx);
5450
5451        panel.read_with(&cx, |panel, _cx| {
5452            assert_eq!(
5453                panel.background_threads.len(),
5454                1,
5455                "Running thread A should be retained in background_views"
5456            );
5457            assert!(
5458                panel.background_threads.contains_key(&session_id_a),
5459                "Background view should be keyed by thread A's session ID"
5460            );
5461        });
5462    }
5463
5464    #[gpui::test]
5465    async fn test_idle_thread_dropped_when_navigating_away(cx: &mut TestAppContext) {
5466        let (panel, mut cx) = setup_panel(cx).await;
5467
5468        let connection_a = StubAgentConnection::new();
5469        connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5470            acp::ContentChunk::new("Response".into()),
5471        )]);
5472        open_thread_with_connection(&panel, connection_a, &mut cx);
5473        send_message(&panel, &mut cx);
5474
5475        let weak_view_a = panel.read_with(&cx, |panel, _cx| {
5476            panel.active_conversation().unwrap().downgrade()
5477        });
5478
5479        // Thread A should be idle (auto-completed via set_next_prompt_updates).
5480        panel.read_with(&cx, |panel, cx| {
5481            let thread = panel.active_agent_thread(cx).unwrap();
5482            assert_eq!(thread.read(cx).status(), ThreadStatus::Idle);
5483        });
5484
5485        // Open a new thread B — thread A should NOT be retained.
5486        let connection_b = StubAgentConnection::new();
5487        open_thread_with_connection(&panel, connection_b, &mut cx);
5488
5489        panel.read_with(&cx, |panel, _cx| {
5490            assert!(
5491                panel.background_threads.is_empty(),
5492                "Idle thread A should not be retained in background_views"
5493            );
5494        });
5495
5496        // Verify the old ConnectionView entity was dropped (no strong references remain).
5497        assert!(
5498            weak_view_a.upgrade().is_none(),
5499            "Idle ConnectionView should have been dropped"
5500        );
5501    }
5502
5503    #[gpui::test]
5504    async fn test_background_thread_promoted_via_load(cx: &mut TestAppContext) {
5505        let (panel, mut cx) = setup_panel(cx).await;
5506
5507        let connection_a = StubAgentConnection::new();
5508        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5509        send_message(&panel, &mut cx);
5510
5511        let session_id_a = active_session_id(&panel, &cx);
5512
5513        // Keep thread A generating.
5514        cx.update(|_, cx| {
5515            connection_a.send_update(
5516                session_id_a.clone(),
5517                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5518                cx,
5519            );
5520        });
5521        cx.run_until_parked();
5522
5523        // Open thread B — thread A goes to background.
5524        let connection_b = StubAgentConnection::new();
5525        open_thread_with_connection(&panel, connection_b, &mut cx);
5526
5527        let session_id_b = active_session_id(&panel, &cx);
5528
5529        panel.read_with(&cx, |panel, _cx| {
5530            assert_eq!(panel.background_threads.len(), 1);
5531            assert!(panel.background_threads.contains_key(&session_id_a));
5532        });
5533
5534        // Load thread A back via load_agent_thread — should promote from background.
5535        panel.update_in(&mut cx, |panel, window, cx| {
5536            panel.load_agent_thread(
5537                panel.selected_agent().expect("selected agent must be set"),
5538                session_id_a.clone(),
5539                None,
5540                None,
5541                true,
5542                window,
5543                cx,
5544            );
5545        });
5546
5547        // Thread A should now be the active view, promoted from background.
5548        let active_session = active_session_id(&panel, &cx);
5549        assert_eq!(
5550            active_session, session_id_a,
5551            "Thread A should be the active thread after promotion"
5552        );
5553
5554        panel.read_with(&cx, |panel, _cx| {
5555            assert!(
5556                !panel.background_threads.contains_key(&session_id_a),
5557                "Promoted thread A should no longer be in background_views"
5558            );
5559            assert!(
5560                !panel.background_threads.contains_key(&session_id_b),
5561                "Thread B (idle) should not have been retained in background_views"
5562            );
5563        });
5564    }
5565
5566    #[gpui::test]
5567    async fn test_thread_target_local_project(cx: &mut TestAppContext) {
5568        init_test(cx);
5569        cx.update(|cx| {
5570            cx.update_flags(true, vec!["agent-v2".to_string()]);
5571            agent::ThreadStore::init_global(cx);
5572            language_model::LanguageModelRegistry::test(cx);
5573        });
5574
5575        let fs = FakeFs::new(cx.executor());
5576        fs.insert_tree(
5577            "/project",
5578            json!({
5579                ".git": {},
5580                "src": {
5581                    "main.rs": "fn main() {}"
5582                }
5583            }),
5584        )
5585        .await;
5586        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5587
5588        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5589
5590        let multi_workspace =
5591            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5592
5593        let workspace = multi_workspace
5594            .read_with(cx, |multi_workspace, _cx| {
5595                multi_workspace.workspace().clone()
5596            })
5597            .unwrap();
5598
5599        workspace.update(cx, |workspace, _cx| {
5600            workspace.set_random_database_id();
5601        });
5602
5603        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5604
5605        // Wait for the project to discover the git repository.
5606        cx.run_until_parked();
5607
5608        let panel = workspace.update_in(cx, |workspace, window, cx| {
5609            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5610            let panel =
5611                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5612            workspace.add_panel(panel.clone(), window, cx);
5613            panel
5614        });
5615
5616        cx.run_until_parked();
5617
5618        // Default thread target should be LocalProject.
5619        panel.read_with(cx, |panel, _cx| {
5620            assert_eq!(
5621                *panel.start_thread_in(),
5622                StartThreadIn::LocalProject,
5623                "default thread target should be LocalProject"
5624            );
5625        });
5626
5627        // Start a new thread with the default LocalProject target.
5628        // Use StubAgentServer so the thread connects immediately in tests.
5629        panel.update_in(cx, |panel, window, cx| {
5630            panel.open_external_thread_with_server(
5631                Rc::new(StubAgentServer::default_response()),
5632                window,
5633                cx,
5634            );
5635        });
5636
5637        cx.run_until_parked();
5638
5639        // MultiWorkspace should still have exactly one workspace (no worktree created).
5640        multi_workspace
5641            .read_with(cx, |multi_workspace, _cx| {
5642                assert_eq!(
5643                    multi_workspace.workspaces().len(),
5644                    1,
5645                    "LocalProject should not create a new workspace"
5646                );
5647            })
5648            .unwrap();
5649
5650        // The thread should be active in the panel.
5651        panel.read_with(cx, |panel, cx| {
5652            assert!(
5653                panel.active_agent_thread(cx).is_some(),
5654                "a thread should be running in the current workspace"
5655            );
5656        });
5657
5658        // The thread target should still be LocalProject (unchanged).
5659        panel.read_with(cx, |panel, _cx| {
5660            assert_eq!(
5661                *panel.start_thread_in(),
5662                StartThreadIn::LocalProject,
5663                "thread target should remain LocalProject"
5664            );
5665        });
5666
5667        // No worktree creation status should be set.
5668        panel.read_with(cx, |panel, _cx| {
5669            assert!(
5670                panel.worktree_creation_status.is_none(),
5671                "no worktree creation should have occurred"
5672            );
5673        });
5674    }
5675
5676    #[gpui::test]
5677    async fn test_thread_target_serialization_round_trip(cx: &mut TestAppContext) {
5678        init_test(cx);
5679        cx.update(|cx| {
5680            cx.update_flags(true, vec!["agent-v2".to_string()]);
5681            agent::ThreadStore::init_global(cx);
5682            language_model::LanguageModelRegistry::test(cx);
5683        });
5684
5685        let fs = FakeFs::new(cx.executor());
5686        fs.insert_tree(
5687            "/project",
5688            json!({
5689                ".git": {},
5690                "src": {
5691                    "main.rs": "fn main() {}"
5692                }
5693            }),
5694        )
5695        .await;
5696        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5697
5698        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5699
5700        let multi_workspace =
5701            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5702
5703        let workspace = multi_workspace
5704            .read_with(cx, |multi_workspace, _cx| {
5705                multi_workspace.workspace().clone()
5706            })
5707            .unwrap();
5708
5709        workspace.update(cx, |workspace, _cx| {
5710            workspace.set_random_database_id();
5711        });
5712
5713        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5714
5715        // Wait for the project to discover the git repository.
5716        cx.run_until_parked();
5717
5718        let panel = workspace.update_in(cx, |workspace, window, cx| {
5719            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5720            let panel =
5721                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5722            workspace.add_panel(panel.clone(), window, cx);
5723            panel
5724        });
5725
5726        cx.run_until_parked();
5727
5728        // Default should be LocalProject.
5729        panel.read_with(cx, |panel, _cx| {
5730            assert_eq!(*panel.start_thread_in(), StartThreadIn::LocalProject);
5731        });
5732
5733        // Change thread target to NewWorktree.
5734        panel.update(cx, |panel, cx| {
5735            panel.set_start_thread_in(&StartThreadIn::NewWorktree, cx);
5736        });
5737
5738        panel.read_with(cx, |panel, _cx| {
5739            assert_eq!(
5740                *panel.start_thread_in(),
5741                StartThreadIn::NewWorktree,
5742                "thread target should be NewWorktree after set_thread_target"
5743            );
5744        });
5745
5746        // Let serialization complete.
5747        cx.run_until_parked();
5748
5749        // Load a fresh panel from the serialized data.
5750        let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5751        let async_cx = cx.update(|window, cx| window.to_async(cx));
5752        let loaded_panel =
5753            AgentPanel::load(workspace.downgrade(), prompt_builder.clone(), async_cx)
5754                .await
5755                .expect("panel load should succeed");
5756        cx.run_until_parked();
5757
5758        loaded_panel.read_with(cx, |panel, _cx| {
5759            assert_eq!(
5760                *panel.start_thread_in(),
5761                StartThreadIn::NewWorktree,
5762                "thread target should survive serialization round-trip"
5763            );
5764        });
5765    }
5766
5767    #[gpui::test]
5768    async fn test_set_active_blocked_during_worktree_creation(cx: &mut TestAppContext) {
5769        init_test(cx);
5770
5771        let fs = FakeFs::new(cx.executor());
5772        cx.update(|cx| {
5773            cx.update_flags(true, vec!["agent-v2".to_string()]);
5774            agent::ThreadStore::init_global(cx);
5775            language_model::LanguageModelRegistry::test(cx);
5776            <dyn fs::Fs>::set_global(fs.clone(), cx);
5777        });
5778
5779        fs.insert_tree(
5780            "/project",
5781            json!({
5782                ".git": {},
5783                "src": {
5784                    "main.rs": "fn main() {}"
5785                }
5786            }),
5787        )
5788        .await;
5789
5790        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5791
5792        let multi_workspace =
5793            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5794
5795        let workspace = multi_workspace
5796            .read_with(cx, |multi_workspace, _cx| {
5797                multi_workspace.workspace().clone()
5798            })
5799            .unwrap();
5800
5801        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5802
5803        let panel = workspace.update_in(cx, |workspace, window, cx| {
5804            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5805            let panel =
5806                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5807            workspace.add_panel(panel.clone(), window, cx);
5808            panel
5809        });
5810
5811        cx.run_until_parked();
5812
5813        // Simulate worktree creation in progress and reset to Uninitialized
5814        panel.update_in(cx, |panel, window, cx| {
5815            panel.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
5816            panel.active_view = ActiveView::Uninitialized;
5817            Panel::set_active(panel, true, window, cx);
5818            assert!(
5819                matches!(panel.active_view, ActiveView::Uninitialized),
5820                "set_active should not create a thread while worktree is being created"
5821            );
5822        });
5823
5824        // Clear the creation status and use open_external_thread_with_server
5825        // (which bypasses new_agent_thread) to verify the panel can transition
5826        // out of Uninitialized. We can't call set_active directly because
5827        // new_agent_thread requires full agent server infrastructure.
5828        panel.update_in(cx, |panel, window, cx| {
5829            panel.worktree_creation_status = None;
5830            panel.active_view = ActiveView::Uninitialized;
5831            panel.open_external_thread_with_server(
5832                Rc::new(StubAgentServer::default_response()),
5833                window,
5834                cx,
5835            );
5836        });
5837
5838        cx.run_until_parked();
5839
5840        panel.read_with(cx, |panel, _cx| {
5841            assert!(
5842                !matches!(panel.active_view, ActiveView::Uninitialized),
5843                "panel should transition out of Uninitialized once worktree creation is cleared"
5844            );
5845        });
5846    }
5847
5848    #[test]
5849    fn test_deserialize_agent_type_variants() {
5850        assert_eq!(
5851            serde_json::from_str::<AgentType>(r#""NativeAgent""#).unwrap(),
5852            AgentType::NativeAgent,
5853        );
5854        assert_eq!(
5855            serde_json::from_str::<AgentType>(r#""TextThread""#).unwrap(),
5856            AgentType::TextThread,
5857        );
5858        assert_eq!(
5859            serde_json::from_str::<AgentType>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
5860            AgentType::Custom {
5861                id: "my-agent".into(),
5862            },
5863        );
5864    }
5865
5866    #[gpui::test]
5867    async fn test_worktree_creation_preserves_selected_agent(cx: &mut TestAppContext) {
5868        init_test(cx);
5869
5870        let app_state = cx.update(|cx| {
5871            cx.update_flags(true, vec!["agent-v2".to_string()]);
5872            agent::ThreadStore::init_global(cx);
5873            language_model::LanguageModelRegistry::test(cx);
5874
5875            let app_state = workspace::AppState::test(cx);
5876            workspace::init(app_state.clone(), cx);
5877            app_state
5878        });
5879
5880        let fs = app_state.fs.as_fake();
5881        fs.insert_tree(
5882            "/project",
5883            json!({
5884                ".git": {},
5885                "src": {
5886                    "main.rs": "fn main() {}"
5887                }
5888            }),
5889        )
5890        .await;
5891        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5892
5893        let project = Project::test(app_state.fs.clone(), [Path::new("/project")], cx).await;
5894
5895        let multi_workspace =
5896            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5897
5898        let workspace = multi_workspace
5899            .read_with(cx, |multi_workspace, _cx| {
5900                multi_workspace.workspace().clone()
5901            })
5902            .unwrap();
5903
5904        workspace.update(cx, |workspace, _cx| {
5905            workspace.set_random_database_id();
5906        });
5907
5908        // Register a callback so new workspaces also get an AgentPanel.
5909        cx.update(|cx| {
5910            cx.observe_new(
5911                |workspace: &mut Workspace,
5912                 window: Option<&mut Window>,
5913                 cx: &mut Context<Workspace>| {
5914                    if let Some(window) = window {
5915                        let project = workspace.project().clone();
5916                        let text_thread_store =
5917                            cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5918                        let panel = cx.new(|cx| {
5919                            AgentPanel::new(workspace, text_thread_store, None, window, cx)
5920                        });
5921                        workspace.add_panel(panel, window, cx);
5922                    }
5923                },
5924            )
5925            .detach();
5926        });
5927
5928        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5929
5930        // Wait for the project to discover the git repository.
5931        cx.run_until_parked();
5932
5933        let panel = workspace.update_in(cx, |workspace, window, cx| {
5934            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5935            let panel =
5936                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5937            workspace.add_panel(panel.clone(), window, cx);
5938            panel
5939        });
5940
5941        cx.run_until_parked();
5942
5943        // Open a thread (needed so there's an active thread view).
5944        panel.update_in(cx, |panel, window, cx| {
5945            panel.open_external_thread_with_server(
5946                Rc::new(StubAgentServer::default_response()),
5947                window,
5948                cx,
5949            );
5950        });
5951
5952        cx.run_until_parked();
5953
5954        // Set the selected agent to Codex (a custom agent) and start_thread_in
5955        // to NewWorktree. We do this AFTER opening the thread because
5956        // open_external_thread_with_server overrides selected_agent_type.
5957        panel.update(cx, |panel, cx| {
5958            panel.selected_agent_type = AgentType::Custom {
5959                id: CODEX_ID.into(),
5960            };
5961            panel.set_start_thread_in(&StartThreadIn::NewWorktree, cx);
5962        });
5963
5964        // Verify the panel has the Codex agent selected.
5965        panel.read_with(cx, |panel, _cx| {
5966            assert_eq!(
5967                panel.selected_agent_type,
5968                AgentType::Custom {
5969                    id: CODEX_ID.into()
5970                },
5971            );
5972        });
5973
5974        // Directly call handle_worktree_creation_requested, which is what
5975        // handle_first_send_requested does when start_thread_in == NewWorktree.
5976        let content = vec![acp::ContentBlock::Text(acp::TextContent::new(
5977            "Hello from test",
5978        ))];
5979        panel.update_in(cx, |panel, window, cx| {
5980            panel.handle_worktree_creation_requested(content, window, cx);
5981        });
5982
5983        // Let the async worktree creation + workspace setup complete.
5984        cx.run_until_parked();
5985
5986        // Find the new workspace's AgentPanel and verify it used the Codex agent.
5987        let found_codex = multi_workspace
5988            .read_with(cx, |multi_workspace, cx| {
5989                // There should be more than one workspace now (the original + the new worktree).
5990                assert!(
5991                    multi_workspace.workspaces().len() > 1,
5992                    "expected a new workspace to have been created, found {}",
5993                    multi_workspace.workspaces().len(),
5994                );
5995
5996                // Check the newest workspace's panel for the correct agent.
5997                let new_workspace = multi_workspace
5998                    .workspaces()
5999                    .iter()
6000                    .find(|ws| ws.entity_id() != workspace.entity_id())
6001                    .expect("should find the new workspace");
6002                let new_panel = new_workspace
6003                    .read(cx)
6004                    .panel::<AgentPanel>(cx)
6005                    .expect("new workspace should have an AgentPanel");
6006
6007                new_panel.read(cx).selected_agent_type.clone()
6008            })
6009            .unwrap();
6010
6011        assert_eq!(
6012            found_codex,
6013            AgentType::Custom {
6014                id: CODEX_ID.into()
6015            },
6016            "the new worktree workspace should use the same agent (Codex) that was selected in the original panel",
6017        );
6018    }
6019}