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