agent_panel.rs

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