agent_panel.rs

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