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