terminal_panel.rs

   1use std::{cmp, ops::ControlFlow, path::PathBuf, process::ExitStatus, sync::Arc, time::Duration};
   2
   3use crate::{
   4    TerminalView, default_working_directory,
   5    persistence::{
   6        SerializedItems, SerializedTerminalPanel, deserialize_terminal_panel, serialize_pane_group,
   7    },
   8};
   9use breadcrumbs::Breadcrumbs;
  10use collections::HashMap;
  11use db::kvp::KEY_VALUE_STORE;
  12use futures::{channel::oneshot, future::join_all};
  13use gpui::{
  14    Action, AnyView, App, AsyncApp, AsyncWindowContext, Context, Corner, Entity, EventEmitter,
  15    ExternalPaths, FocusHandle, Focusable, IntoElement, ParentElement, Pixels, Render, Styled,
  16    Task, WeakEntity, Window, actions,
  17};
  18use itertools::Itertools;
  19use project::{Fs, Project, ProjectEntryId};
  20use search::{BufferSearchBar, buffer_search::DivRegistrar};
  21use settings::{Settings, TerminalDockPosition};
  22use task::{RevealStrategy, RevealTarget, Shell, ShellBuilder, SpawnInTerminal, TaskId};
  23use terminal::{Terminal, terminal_settings::TerminalSettings};
  24use ui::{
  25    ButtonLike, Clickable, ContextMenu, FluentBuilder, PopoverMenu, SplitButton, Toggleable,
  26    Tooltip, prelude::*,
  27};
  28use util::{ResultExt, TryFutureExt};
  29use workspace::{
  30    ActivateNextPane, ActivatePane, ActivatePaneDown, ActivatePaneLeft, ActivatePaneRight,
  31    ActivatePaneUp, ActivatePreviousPane, DraggedSelection, DraggedTab, ItemId, MoveItemToPane,
  32    MoveItemToPaneInDirection, MovePaneDown, MovePaneLeft, MovePaneRight, MovePaneUp, Pane,
  33    PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitMode, SplitRight, SplitUp, SwapPaneDown,
  34    SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom, Workspace,
  35    dock::{DockPosition, Panel, PanelEvent, PanelHandle},
  36    item::SerializableItem,
  37    move_active_item, move_item, pane,
  38};
  39
  40use anyhow::{Result, anyhow};
  41use zed_actions::assistant::InlineAssist;
  42
  43const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
  44
  45actions!(
  46    terminal_panel,
  47    [
  48        /// Toggles the terminal panel.
  49        Toggle,
  50        /// Toggles focus on the terminal panel.
  51        ToggleFocus
  52    ]
  53);
  54
  55pub fn init(cx: &mut App) {
  56    cx.observe_new(
  57        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
  58            workspace.register_action(TerminalPanel::new_terminal);
  59            workspace.register_action(TerminalPanel::open_terminal);
  60            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
  61                if is_enabled_in_workspace(workspace, cx) {
  62                    workspace.toggle_panel_focus::<TerminalPanel>(window, cx);
  63                }
  64            });
  65            workspace.register_action(|workspace, _: &Toggle, window, cx| {
  66                if is_enabled_in_workspace(workspace, cx) {
  67                    if !workspace.toggle_panel_focus::<TerminalPanel>(window, cx) {
  68                        workspace.close_panel::<TerminalPanel>(window, cx);
  69                    }
  70                }
  71            });
  72        },
  73    )
  74    .detach();
  75}
  76
  77pub struct TerminalPanel {
  78    pub(crate) active_pane: Entity<Pane>,
  79    pub(crate) center: PaneGroup,
  80    fs: Arc<dyn Fs>,
  81    workspace: WeakEntity<Workspace>,
  82    pub(crate) width: Option<Pixels>,
  83    pub(crate) height: Option<Pixels>,
  84    pending_serialization: Task<Option<()>>,
  85    pending_terminals_to_add: usize,
  86    deferred_tasks: HashMap<TaskId, Task<()>>,
  87    assistant_enabled: bool,
  88    assistant_tab_bar_button: Option<AnyView>,
  89    active: bool,
  90}
  91
  92impl TerminalPanel {
  93    pub fn new(workspace: &Workspace, window: &mut Window, cx: &mut Context<Self>) -> Self {
  94        let project = workspace.project();
  95        let pane = new_terminal_pane(workspace.weak_handle(), project.clone(), false, window, cx);
  96        let center = PaneGroup::new(pane.clone());
  97        let terminal_panel = Self {
  98            center,
  99            active_pane: pane,
 100            fs: workspace.app_state().fs.clone(),
 101            workspace: workspace.weak_handle(),
 102            pending_serialization: Task::ready(None),
 103            width: None,
 104            height: None,
 105            pending_terminals_to_add: 0,
 106            deferred_tasks: HashMap::default(),
 107            assistant_enabled: false,
 108            assistant_tab_bar_button: None,
 109            active: false,
 110        };
 111        terminal_panel.apply_tab_bar_buttons(&terminal_panel.active_pane, cx);
 112        terminal_panel
 113    }
 114
 115    pub fn set_assistant_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 116        self.assistant_enabled = enabled;
 117        if enabled {
 118            let focus_handle = self
 119                .active_pane
 120                .read(cx)
 121                .active_item()
 122                .map(|item| item.item_focus_handle(cx))
 123                .unwrap_or(self.focus_handle(cx));
 124            self.assistant_tab_bar_button = Some(
 125                cx.new(move |_| InlineAssistTabBarButton { focus_handle })
 126                    .into(),
 127            );
 128        } else {
 129            self.assistant_tab_bar_button = None;
 130        }
 131        for pane in self.center.panes() {
 132            self.apply_tab_bar_buttons(pane, cx);
 133        }
 134    }
 135
 136    fn apply_tab_bar_buttons(&self, terminal_pane: &Entity<Pane>, cx: &mut Context<Self>) {
 137        let assistant_tab_bar_button = self.assistant_tab_bar_button.clone();
 138        terminal_pane.update(cx, |pane, cx| {
 139            pane.set_render_tab_bar_buttons(cx, move |pane, window, cx| {
 140                let split_context = pane
 141                    .active_item()
 142                    .and_then(|item| item.downcast::<TerminalView>())
 143                    .map(|terminal_view| terminal_view.read(cx).focus_handle.clone());
 144                let has_focused_rename_editor = pane
 145                    .active_item()
 146                    .and_then(|item| item.downcast::<TerminalView>())
 147                    .is_some_and(|view| view.read(cx).rename_editor_is_focused(window, cx));
 148                if !pane.has_focus(window, cx)
 149                    && !pane.context_menu_focused(window, cx)
 150                    && !has_focused_rename_editor
 151                {
 152                    return (None, None);
 153                }
 154                let focus_handle = pane.focus_handle(cx);
 155                let right_children = h_flex()
 156                    .gap(DynamicSpacing::Base02.rems(cx))
 157                    .child(
 158                        PopoverMenu::new("terminal-tab-bar-popover-menu")
 159                            .trigger_with_tooltip(
 160                                IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
 161                                Tooltip::text("New…"),
 162                            )
 163                            .anchor(Corner::TopRight)
 164                            .with_handle(pane.new_item_context_menu_handle.clone())
 165                            .menu(move |window, cx| {
 166                                let focus_handle = focus_handle.clone();
 167                                let menu = ContextMenu::build(window, cx, |menu, _, _| {
 168                                    menu.context(focus_handle.clone())
 169                                        .action(
 170                                            "New Terminal",
 171                                            workspace::NewTerminal::default().boxed_clone(),
 172                                        )
 173                                        // We want the focus to go back to terminal panel once task modal is dismissed,
 174                                        // hence we focus that first. Otherwise, we'd end up without a focused element, as
 175                                        // context menu will be gone the moment we spawn the modal.
 176                                        .action(
 177                                            "Spawn Task",
 178                                            zed_actions::Spawn::modal().boxed_clone(),
 179                                        )
 180                                });
 181
 182                                Some(menu)
 183                            }),
 184                    )
 185                    .children(assistant_tab_bar_button.clone())
 186                    .child(
 187                        PopoverMenu::new("terminal-pane-tab-bar-split")
 188                            .trigger_with_tooltip(
 189                                IconButton::new("terminal-pane-split", IconName::Split)
 190                                    .icon_size(IconSize::Small),
 191                                Tooltip::text("Split Pane"),
 192                            )
 193                            .anchor(Corner::TopRight)
 194                            .with_handle(pane.split_item_context_menu_handle.clone())
 195                            .menu({
 196                                move |window, cx| {
 197                                    ContextMenu::build(window, cx, |menu, _, _| {
 198                                        menu.when_some(
 199                                            split_context.clone(),
 200                                            |menu, split_context| menu.context(split_context),
 201                                        )
 202                                        .action("Split Right", SplitRight::default().boxed_clone())
 203                                        .action("Split Left", SplitLeft::default().boxed_clone())
 204                                        .action("Split Up", SplitUp::default().boxed_clone())
 205                                        .action("Split Down", SplitDown::default().boxed_clone())
 206                                    })
 207                                    .into()
 208                                }
 209                            }),
 210                    )
 211                    .child({
 212                        let zoomed = pane.is_zoomed();
 213                        IconButton::new("toggle_zoom", IconName::Maximize)
 214                            .icon_size(IconSize::Small)
 215                            .toggle_state(zoomed)
 216                            .selected_icon(IconName::Minimize)
 217                            .on_click(cx.listener(|pane, _, window, cx| {
 218                                pane.toggle_zoom(&workspace::ToggleZoom, window, cx);
 219                            }))
 220                            .tooltip(move |_window, cx| {
 221                                Tooltip::for_action(
 222                                    if zoomed { "Zoom Out" } else { "Zoom In" },
 223                                    &ToggleZoom,
 224                                    cx,
 225                                )
 226                            })
 227                    })
 228                    .into_any_element()
 229                    .into();
 230                (None, right_children)
 231            });
 232        });
 233    }
 234
 235    fn serialization_key(workspace: &Workspace) -> Option<String> {
 236        workspace
 237            .database_id()
 238            .map(|id| i64::from(id).to_string())
 239            .or(workspace.session_id())
 240            .map(|id| format!("{:?}-{:?}", TERMINAL_PANEL_KEY, id))
 241    }
 242
 243    pub async fn load(
 244        workspace: WeakEntity<Workspace>,
 245        mut cx: AsyncWindowContext,
 246    ) -> Result<Entity<Self>> {
 247        let mut terminal_panel = None;
 248
 249        if let Some((database_id, serialization_key)) = workspace
 250            .read_with(&cx, |workspace, _| {
 251                workspace
 252                    .database_id()
 253                    .zip(TerminalPanel::serialization_key(workspace))
 254            })
 255            .ok()
 256            .flatten()
 257            && let Some(serialized_panel) = cx
 258                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 259                .await
 260                .log_err()
 261                .flatten()
 262                .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
 263                .transpose()
 264                .log_err()
 265                .flatten()
 266            && let Ok(serialized) = workspace
 267                .update_in(&mut cx, |workspace, window, cx| {
 268                    deserialize_terminal_panel(
 269                        workspace.weak_handle(),
 270                        workspace.project().clone(),
 271                        database_id,
 272                        serialized_panel,
 273                        window,
 274                        cx,
 275                    )
 276                })?
 277                .await
 278        {
 279            terminal_panel = Some(serialized);
 280        }
 281
 282        let terminal_panel = if let Some(panel) = terminal_panel {
 283            panel
 284        } else {
 285            workspace.update_in(&mut cx, |workspace, window, cx| {
 286                cx.new(|cx| TerminalPanel::new(workspace, window, cx))
 287            })?
 288        };
 289
 290        if let Some(workspace) = workspace.upgrade() {
 291            workspace.update(&mut cx, |workspace, _| {
 292                workspace.set_terminal_provider(TerminalProvider(terminal_panel.clone()))
 293            });
 294        }
 295
 296        // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
 297        if let Some(workspace) = workspace.upgrade() {
 298            let cleanup_task = workspace.update_in(&mut cx, |workspace, window, cx| {
 299                let alive_item_ids = terminal_panel
 300                    .read(cx)
 301                    .center
 302                    .panes()
 303                    .into_iter()
 304                    .flat_map(|pane| pane.read(cx).items())
 305                    .map(|item| item.item_id().as_u64() as ItemId)
 306                    .collect();
 307                workspace.database_id().map(|workspace_id| {
 308                    TerminalView::cleanup(workspace_id, alive_item_ids, window, cx)
 309                })
 310            })?;
 311            if let Some(task) = cleanup_task {
 312                task.await.log_err();
 313            }
 314        }
 315
 316        if let Some(workspace) = workspace.upgrade() {
 317            let should_focus = workspace
 318                .update_in(&mut cx, |workspace, window, cx| {
 319                    workspace.active_item(cx).is_none()
 320                        && workspace
 321                            .is_dock_at_position_open(terminal_panel.position(window, cx), cx)
 322                })
 323                .unwrap_or(false);
 324
 325            if should_focus {
 326                terminal_panel
 327                    .update_in(&mut cx, |panel, window, cx| {
 328                        panel.active_pane.update(cx, |pane, cx| {
 329                            pane.focus_active_item(window, cx);
 330                        });
 331                    })
 332                    .ok();
 333            }
 334        }
 335        Ok(terminal_panel)
 336    }
 337
 338    fn handle_pane_event(
 339        &mut self,
 340        pane: &Entity<Pane>,
 341        event: &pane::Event,
 342        window: &mut Window,
 343        cx: &mut Context<Self>,
 344    ) {
 345        match event {
 346            pane::Event::ActivateItem { .. } => self.serialize(cx),
 347            pane::Event::RemovedItem { .. } => self.serialize(cx),
 348            pane::Event::Remove { focus_on_pane } => {
 349                let pane_count_before_removal = self.center.panes().len();
 350                let _removal_result = self.center.remove(pane, cx);
 351                if pane_count_before_removal == 1 {
 352                    self.center.first_pane().update(cx, |pane, cx| {
 353                        pane.set_zoomed(false, cx);
 354                    });
 355                    cx.emit(PanelEvent::Close);
 356                } else if let Some(focus_on_pane) =
 357                    focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
 358                {
 359                    focus_on_pane.focus_handle(cx).focus(window, cx);
 360                }
 361            }
 362            pane::Event::ZoomIn => {
 363                for pane in self.center.panes() {
 364                    pane.update(cx, |pane, cx| {
 365                        pane.set_zoomed(true, cx);
 366                    })
 367                }
 368                cx.emit(PanelEvent::ZoomIn);
 369                cx.notify();
 370            }
 371            pane::Event::ZoomOut => {
 372                for pane in self.center.panes() {
 373                    pane.update(cx, |pane, cx| {
 374                        pane.set_zoomed(false, cx);
 375                    })
 376                }
 377                cx.emit(PanelEvent::ZoomOut);
 378                cx.notify();
 379            }
 380            pane::Event::AddItem { item } => {
 381                if let Some(workspace) = self.workspace.upgrade() {
 382                    workspace.update(cx, |workspace, cx| {
 383                        item.added_to_pane(workspace, pane.clone(), window, cx)
 384                    })
 385                }
 386                self.serialize(cx);
 387            }
 388            &pane::Event::Split { direction, mode } => {
 389                match mode {
 390                    SplitMode::ClonePane | SplitMode::EmptyPane => {
 391                        let clone = matches!(mode, SplitMode::ClonePane);
 392                        let new_pane = self.new_pane_with_active_terminal(clone, window, cx);
 393                        let pane = pane.clone();
 394                        cx.spawn_in(window, async move |panel, cx| {
 395                            let Some(new_pane) = new_pane.await else {
 396                                return;
 397                            };
 398                            panel
 399                                .update_in(cx, |panel, window, cx| {
 400                                    panel
 401                                        .center
 402                                        .split(&pane, &new_pane, direction, cx)
 403                                        .log_err();
 404                                    window.focus(&new_pane.focus_handle(cx), cx);
 405                                })
 406                                .ok();
 407                        })
 408                        .detach();
 409                    }
 410                    SplitMode::MovePane => {
 411                        let Some(item) =
 412                            pane.update(cx, |pane, cx| pane.take_active_item(window, cx))
 413                        else {
 414                            return;
 415                        };
 416                        let Ok(project) = self
 417                            .workspace
 418                            .update(cx, |workspace, _| workspace.project().clone())
 419                        else {
 420                            return;
 421                        };
 422                        let new_pane =
 423                            new_terminal_pane(self.workspace.clone(), project, false, window, cx);
 424                        new_pane.update(cx, |pane, cx| {
 425                            pane.add_item(item, true, true, None, window, cx);
 426                        });
 427                        self.center.split(&pane, &new_pane, direction, cx).log_err();
 428                        window.focus(&new_pane.focus_handle(cx), cx);
 429                    }
 430                };
 431            }
 432            pane::Event::Focus => {
 433                self.active_pane = pane.clone();
 434            }
 435            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {
 436                self.serialize(cx);
 437            }
 438
 439            _ => {}
 440        }
 441    }
 442
 443    fn new_pane_with_active_terminal(
 444        &mut self,
 445        clone: bool,
 446        window: &mut Window,
 447        cx: &mut Context<Self>,
 448    ) -> Task<Option<Entity<Pane>>> {
 449        let Some(workspace) = self.workspace.upgrade() else {
 450            return Task::ready(None);
 451        };
 452        let workspace = workspace.read(cx);
 453        let database_id = workspace.database_id();
 454        let weak_workspace = self.workspace.clone();
 455        let project = workspace.project().clone();
 456        let active_pane = &self.active_pane;
 457        let terminal_view = if clone {
 458            active_pane
 459                .read(cx)
 460                .active_item()
 461                .and_then(|item| item.downcast::<TerminalView>())
 462        } else {
 463            None
 464        };
 465        let working_directory = if clone {
 466            terminal_view
 467                .as_ref()
 468                .and_then(|terminal_view| {
 469                    terminal_view
 470                        .read(cx)
 471                        .terminal()
 472                        .read(cx)
 473                        .working_directory()
 474                })
 475                .or_else(|| default_working_directory(workspace, cx))
 476        } else {
 477            default_working_directory(workspace, cx)
 478        };
 479
 480        let is_zoomed = if clone {
 481            active_pane.read(cx).is_zoomed()
 482        } else {
 483            false
 484        };
 485        cx.spawn_in(window, async move |panel, cx| {
 486            let terminal = project
 487                .update(cx, |project, cx| match terminal_view {
 488                    Some(view) => project.clone_terminal(
 489                        &view.read(cx).terminal.clone(),
 490                        cx,
 491                        working_directory,
 492                    ),
 493                    None => project.create_terminal_shell(working_directory, cx),
 494                })
 495                .await
 496                .log_err()?;
 497
 498            panel
 499                .update_in(cx, move |terminal_panel, window, cx| {
 500                    let terminal_view = Box::new(cx.new(|cx| {
 501                        TerminalView::new(
 502                            terminal.clone(),
 503                            weak_workspace.clone(),
 504                            database_id,
 505                            project.downgrade(),
 506                            window,
 507                            cx,
 508                        )
 509                    }));
 510                    let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
 511                    terminal_panel.apply_tab_bar_buttons(&pane, cx);
 512                    pane.update(cx, |pane, cx| {
 513                        pane.add_item(terminal_view, true, true, None, window, cx);
 514                    });
 515                    Some(pane)
 516                })
 517                .ok()
 518                .flatten()
 519        })
 520    }
 521
 522    pub fn open_terminal(
 523        workspace: &mut Workspace,
 524        action: &workspace::OpenTerminal,
 525        window: &mut Window,
 526        cx: &mut Context<Workspace>,
 527    ) {
 528        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 529            return;
 530        };
 531
 532        terminal_panel
 533            .update(cx, |panel, cx| {
 534                if action.local {
 535                    panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
 536                } else {
 537                    panel.add_terminal_shell(
 538                        Some(action.working_directory.clone()),
 539                        RevealStrategy::Always,
 540                        window,
 541                        cx,
 542                    )
 543                }
 544            })
 545            .detach_and_log_err(cx);
 546    }
 547
 548    pub fn spawn_task(
 549        &mut self,
 550        task: &SpawnInTerminal,
 551        window: &mut Window,
 552        cx: &mut Context<Self>,
 553    ) -> Task<Result<WeakEntity<Terminal>>> {
 554        let Some(workspace) = self.workspace.upgrade() else {
 555            return Task::ready(Err(anyhow!("failed to read workspace")));
 556        };
 557
 558        let project = workspace.read(cx).project().read(cx);
 559
 560        if project.is_via_collab() {
 561            return Task::ready(Err(anyhow!("cannot spawn tasks as a guest")));
 562        }
 563
 564        let remote_client = project.remote_client();
 565        let is_windows = project.path_style(cx).is_windows();
 566        let remote_shell = remote_client
 567            .as_ref()
 568            .and_then(|remote_client| remote_client.read(cx).shell());
 569
 570        let shell = if let Some(remote_shell) = remote_shell
 571            && task.shell == Shell::System
 572        {
 573            Shell::Program(remote_shell)
 574        } else {
 575            task.shell.clone()
 576        };
 577
 578        let task = prepare_task_for_spawn(task, &shell, is_windows);
 579
 580        if task.allow_concurrent_runs && task.use_new_terminal {
 581            return self.spawn_in_new_terminal(task, window, cx);
 582        }
 583
 584        let mut terminals_for_task = self.terminals_for_task(&task.full_label, cx);
 585        let Some(existing) = terminals_for_task.pop() else {
 586            return self.spawn_in_new_terminal(task, window, cx);
 587        };
 588
 589        let (existing_item_index, task_pane, existing_terminal) = existing;
 590        if task.allow_concurrent_runs {
 591            return self.replace_terminal(
 592                task,
 593                task_pane,
 594                existing_item_index,
 595                existing_terminal,
 596                window,
 597                cx,
 598            );
 599        }
 600
 601        let (tx, rx) = oneshot::channel();
 602
 603        self.deferred_tasks.insert(
 604            task.id.clone(),
 605            cx.spawn_in(window, async move |terminal_panel, cx| {
 606                wait_for_terminals_tasks(terminals_for_task, cx).await;
 607                let task = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
 608                    if task.use_new_terminal {
 609                        terminal_panel.spawn_in_new_terminal(task, window, cx)
 610                    } else {
 611                        terminal_panel.replace_terminal(
 612                            task,
 613                            task_pane,
 614                            existing_item_index,
 615                            existing_terminal,
 616                            window,
 617                            cx,
 618                        )
 619                    }
 620                });
 621                if let Ok(task) = task {
 622                    tx.send(task.await).ok();
 623                }
 624            }),
 625        );
 626
 627        cx.spawn(async move |_, _| rx.await?)
 628    }
 629
 630    fn spawn_in_new_terminal(
 631        &mut self,
 632        spawn_task: SpawnInTerminal,
 633        window: &mut Window,
 634        cx: &mut Context<Self>,
 635    ) -> Task<Result<WeakEntity<Terminal>>> {
 636        let reveal = spawn_task.reveal;
 637        let reveal_target = spawn_task.reveal_target;
 638        match reveal_target {
 639            RevealTarget::Center => self
 640                .workspace
 641                .update(cx, |workspace, cx| {
 642                    Self::add_center_terminal(workspace, window, cx, |project, cx| {
 643                        project.create_terminal_task(spawn_task, cx)
 644                    })
 645                })
 646                .unwrap_or_else(|e| Task::ready(Err(e))),
 647            RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
 648        }
 649    }
 650
 651    /// Create a new Terminal in the current working directory or the user's home directory
 652    fn new_terminal(
 653        workspace: &mut Workspace,
 654        action: &workspace::NewTerminal,
 655        window: &mut Window,
 656        cx: &mut Context<Workspace>,
 657    ) {
 658        let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
 659            return;
 660        };
 661
 662        terminal_panel
 663            .update(cx, |this, cx| {
 664                if action.local {
 665                    this.add_local_terminal_shell(RevealStrategy::Always, window, cx)
 666                } else {
 667                    this.add_terminal_shell(
 668                        default_working_directory(workspace, cx),
 669                        RevealStrategy::Always,
 670                        window,
 671                        cx,
 672                    )
 673                }
 674            })
 675            .detach_and_log_err(cx);
 676    }
 677
 678    fn terminals_for_task(
 679        &self,
 680        label: &str,
 681        cx: &mut App,
 682    ) -> Vec<(usize, Entity<Pane>, Entity<TerminalView>)> {
 683        let Some(workspace) = self.workspace.upgrade() else {
 684            return Vec::new();
 685        };
 686
 687        let pane_terminal_views = |pane: Entity<Pane>| {
 688            pane.read(cx)
 689                .items()
 690                .enumerate()
 691                .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
 692                .filter_map(|(index, terminal_view)| {
 693                    let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
 694                    if &task_state.spawned_task.full_label == label {
 695                        Some((index, terminal_view))
 696                    } else {
 697                        None
 698                    }
 699                })
 700                .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
 701        };
 702
 703        self.center
 704            .panes()
 705            .into_iter()
 706            .cloned()
 707            .flat_map(pane_terminal_views)
 708            .chain(
 709                workspace
 710                    .read(cx)
 711                    .panes()
 712                    .iter()
 713                    .cloned()
 714                    .flat_map(pane_terminal_views),
 715            )
 716            .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
 717            .collect()
 718    }
 719
 720    fn activate_terminal_view(
 721        &self,
 722        pane: &Entity<Pane>,
 723        item_index: usize,
 724        focus: bool,
 725        window: &mut Window,
 726        cx: &mut App,
 727    ) {
 728        pane.update(cx, |pane, cx| {
 729            pane.activate_item(item_index, true, focus, window, cx)
 730        })
 731    }
 732
 733    pub fn add_center_terminal(
 734        workspace: &mut Workspace,
 735        window: &mut Window,
 736        cx: &mut Context<Workspace>,
 737        create_terminal: impl FnOnce(
 738            &mut Project,
 739            &mut Context<Project>,
 740        ) -> Task<Result<Entity<Terminal>>>
 741        + 'static,
 742    ) -> Task<Result<WeakEntity<Terminal>>> {
 743        if !is_enabled_in_workspace(workspace, cx) {
 744            return Task::ready(Err(anyhow!(
 745                "terminal not yet supported for remote projects"
 746            )));
 747        }
 748        let project = workspace.project().downgrade();
 749        cx.spawn_in(window, async move |workspace, cx| {
 750            let terminal = project.update(cx, create_terminal)?.await?;
 751
 752            workspace.update_in(cx, |workspace, window, cx| {
 753                let terminal_view = cx.new(|cx| {
 754                    TerminalView::new(
 755                        terminal.clone(),
 756                        workspace.weak_handle(),
 757                        workspace.database_id(),
 758                        workspace.project().downgrade(),
 759                        window,
 760                        cx,
 761                    )
 762                });
 763                workspace.add_item_to_active_pane(Box::new(terminal_view), None, true, window, cx);
 764            })?;
 765            Ok(terminal.downgrade())
 766        })
 767    }
 768
 769    pub fn add_terminal_task(
 770        &mut self,
 771        task: SpawnInTerminal,
 772        reveal_strategy: RevealStrategy,
 773        window: &mut Window,
 774        cx: &mut Context<Self>,
 775    ) -> Task<Result<WeakEntity<Terminal>>> {
 776        let workspace = self.workspace.clone();
 777        cx.spawn_in(window, async move |terminal_panel, cx| {
 778            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 779                anyhow::bail!("terminal not yet supported for remote projects");
 780            }
 781            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 782                terminal_panel.pending_terminals_to_add += 1;
 783                terminal_panel.active_pane.clone()
 784            })?;
 785            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 786            let terminal = project
 787                .update(cx, |project, cx| project.create_terminal_task(task, cx))
 788                .await?;
 789            let result = workspace.update_in(cx, |workspace, window, cx| {
 790                let terminal_view = Box::new(cx.new(|cx| {
 791                    TerminalView::new(
 792                        terminal.clone(),
 793                        workspace.weak_handle(),
 794                        workspace.database_id(),
 795                        workspace.project().downgrade(),
 796                        window,
 797                        cx,
 798                    )
 799                }));
 800
 801                match reveal_strategy {
 802                    RevealStrategy::Always => {
 803                        workspace.focus_panel::<Self>(window, cx);
 804                    }
 805                    RevealStrategy::NoFocus => {
 806                        workspace.open_panel::<Self>(window, cx);
 807                    }
 808                    RevealStrategy::Never => {}
 809                }
 810
 811                pane.update(cx, |pane, cx| {
 812                    let focus = matches!(reveal_strategy, RevealStrategy::Always);
 813                    pane.add_item(terminal_view, true, focus, None, window, cx);
 814                });
 815
 816                Ok(terminal.downgrade())
 817            })?;
 818            terminal_panel.update(cx, |terminal_panel, cx| {
 819                terminal_panel.pending_terminals_to_add =
 820                    terminal_panel.pending_terminals_to_add.saturating_sub(1);
 821                terminal_panel.serialize(cx)
 822            })?;
 823            result
 824        })
 825    }
 826
 827    fn add_terminal_shell(
 828        &mut self,
 829        cwd: Option<PathBuf>,
 830        reveal_strategy: RevealStrategy,
 831        window: &mut Window,
 832        cx: &mut Context<Self>,
 833    ) -> Task<Result<WeakEntity<Terminal>>> {
 834        self.add_terminal_shell_internal(false, cwd, reveal_strategy, window, cx)
 835    }
 836
 837    fn add_local_terminal_shell(
 838        &mut self,
 839        reveal_strategy: RevealStrategy,
 840        window: &mut Window,
 841        cx: &mut Context<Self>,
 842    ) -> Task<Result<WeakEntity<Terminal>>> {
 843        self.add_terminal_shell_internal(true, None, reveal_strategy, window, cx)
 844    }
 845
 846    fn add_terminal_shell_internal(
 847        &mut self,
 848        force_local: bool,
 849        cwd: Option<PathBuf>,
 850        reveal_strategy: RevealStrategy,
 851        window: &mut Window,
 852        cx: &mut Context<Self>,
 853    ) -> Task<Result<WeakEntity<Terminal>>> {
 854        let workspace = self.workspace.clone();
 855
 856        cx.spawn_in(window, async move |terminal_panel, cx| {
 857            if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
 858                anyhow::bail!("terminal not yet supported for collaborative projects");
 859            }
 860            let pane = terminal_panel.update(cx, |terminal_panel, _| {
 861                terminal_panel.pending_terminals_to_add += 1;
 862                terminal_panel.active_pane.clone()
 863            })?;
 864            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 865            let terminal = if force_local {
 866                project
 867                    .update(cx, |project, cx| project.create_local_terminal(cx))
 868                    .await
 869            } else {
 870                project
 871                    .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))
 872                    .await
 873            };
 874
 875            match terminal {
 876                Ok(terminal) => {
 877                    let result = workspace.update_in(cx, |workspace, window, cx| {
 878                        let terminal_view = Box::new(cx.new(|cx| {
 879                            TerminalView::new(
 880                                terminal.clone(),
 881                                workspace.weak_handle(),
 882                                workspace.database_id(),
 883                                workspace.project().downgrade(),
 884                                window,
 885                                cx,
 886                            )
 887                        }));
 888
 889                        match reveal_strategy {
 890                            RevealStrategy::Always => {
 891                                workspace.focus_panel::<Self>(window, cx);
 892                            }
 893                            RevealStrategy::NoFocus => {
 894                                workspace.open_panel::<Self>(window, cx);
 895                            }
 896                            RevealStrategy::Never => {}
 897                        }
 898
 899                        pane.update(cx, |pane, cx| {
 900                            let focus = matches!(reveal_strategy, RevealStrategy::Always);
 901                            pane.add_item(terminal_view, true, focus, None, window, cx);
 902                        });
 903
 904                        Ok(terminal.downgrade())
 905                    })?;
 906                    terminal_panel.update(cx, |terminal_panel, cx| {
 907                        terminal_panel.pending_terminals_to_add =
 908                            terminal_panel.pending_terminals_to_add.saturating_sub(1);
 909                        terminal_panel.serialize(cx)
 910                    })?;
 911                    result
 912                }
 913                Err(error) => {
 914                    pane.update_in(cx, |pane, window, cx| {
 915                        let focus = pane.has_focus(window, cx);
 916                        let failed_to_spawn = cx.new(|cx| FailedToSpawnTerminal {
 917                            error: error.to_string(),
 918                            focus_handle: cx.focus_handle(),
 919                        });
 920                        pane.add_item(Box::new(failed_to_spawn), true, focus, None, window, cx);
 921                    })?;
 922                    Err(error)
 923                }
 924            }
 925        })
 926    }
 927
 928    fn serialize(&mut self, cx: &mut Context<Self>) {
 929        let height = self.height;
 930        let width = self.width;
 931        let Some(serialization_key) = self
 932            .workspace
 933            .read_with(cx, |workspace, _| {
 934                TerminalPanel::serialization_key(workspace)
 935            })
 936            .ok()
 937            .flatten()
 938        else {
 939            return;
 940        };
 941        self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
 942            cx.background_executor()
 943                .timer(Duration::from_millis(50))
 944                .await;
 945            let terminal_panel = terminal_panel.upgrade()?;
 946            let items = terminal_panel.update(cx, |terminal_panel, cx| {
 947                SerializedItems::WithSplits(serialize_pane_group(
 948                    &terminal_panel.center,
 949                    &terminal_panel.active_pane,
 950                    cx,
 951                ))
 952            });
 953            cx.background_spawn(
 954                async move {
 955                    KEY_VALUE_STORE
 956                        .write_kvp(
 957                            serialization_key,
 958                            serde_json::to_string(&SerializedTerminalPanel {
 959                                items,
 960                                active_item_id: None,
 961                                height,
 962                                width,
 963                            })?,
 964                        )
 965                        .await?;
 966                    anyhow::Ok(())
 967                }
 968                .log_err(),
 969            )
 970            .await;
 971            Some(())
 972        });
 973    }
 974
 975    fn replace_terminal(
 976        &self,
 977        spawn_task: SpawnInTerminal,
 978        task_pane: Entity<Pane>,
 979        terminal_item_index: usize,
 980        terminal_to_replace: Entity<TerminalView>,
 981        window: &mut Window,
 982        cx: &mut Context<Self>,
 983    ) -> Task<Result<WeakEntity<Terminal>>> {
 984        let reveal = spawn_task.reveal;
 985        let task_workspace = self.workspace.clone();
 986        cx.spawn_in(window, async move |terminal_panel, cx| {
 987            let project = terminal_panel.update(cx, |this, cx| {
 988                this.workspace
 989                    .update(cx, |workspace, _| workspace.project().clone())
 990            })??;
 991            let new_terminal = project
 992                .update(cx, |project, cx| {
 993                    project.create_terminal_task(spawn_task, cx)
 994                })
 995                .await?;
 996            terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
 997                terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
 998            })?;
 999
1000            let reveal_target = terminal_panel.update(cx, |panel, _| {
1001                if panel.center.panes().iter().any(|p| **p == task_pane) {
1002                    RevealTarget::Dock
1003                } else {
1004                    RevealTarget::Center
1005                }
1006            })?;
1007
1008            match reveal {
1009                RevealStrategy::Always => match reveal_target {
1010                    RevealTarget::Center => {
1011                        task_workspace.update_in(cx, |workspace, window, cx| {
1012                            let did_activate = workspace.activate_item(
1013                                &terminal_to_replace,
1014                                true,
1015                                true,
1016                                window,
1017                                cx,
1018                            );
1019
1020                            anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
1021
1022                            anyhow::Ok(())
1023                        })??;
1024                    }
1025                    RevealTarget::Dock => {
1026                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1027                            terminal_panel.activate_terminal_view(
1028                                &task_pane,
1029                                terminal_item_index,
1030                                true,
1031                                window,
1032                                cx,
1033                            )
1034                        })?;
1035
1036                        cx.spawn(async move |cx| {
1037                            task_workspace
1038                                .update_in(cx, |workspace, window, cx| {
1039                                    workspace.focus_panel::<Self>(window, cx)
1040                                })
1041                                .ok()
1042                        })
1043                        .detach();
1044                    }
1045                },
1046                RevealStrategy::NoFocus => match reveal_target {
1047                    RevealTarget::Center => {
1048                        task_workspace.update_in(cx, |workspace, window, cx| {
1049                            workspace.active_pane().focus_handle(cx).focus(window, cx);
1050                        })?;
1051                    }
1052                    RevealTarget::Dock => {
1053                        terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1054                            terminal_panel.activate_terminal_view(
1055                                &task_pane,
1056                                terminal_item_index,
1057                                false,
1058                                window,
1059                                cx,
1060                            )
1061                        })?;
1062
1063                        cx.spawn(async move |cx| {
1064                            task_workspace
1065                                .update_in(cx, |workspace, window, cx| {
1066                                    workspace.open_panel::<Self>(window, cx)
1067                                })
1068                                .ok()
1069                        })
1070                        .detach();
1071                    }
1072                },
1073                RevealStrategy::Never => {}
1074            }
1075
1076            Ok(new_terminal.downgrade())
1077        })
1078    }
1079
1080    fn has_no_terminals(&self, cx: &App) -> bool {
1081        self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1082    }
1083
1084    pub fn assistant_enabled(&self) -> bool {
1085        self.assistant_enabled
1086    }
1087
1088    /// Returns all panes in the terminal panel.
1089    pub fn panes(&self) -> Vec<&Entity<Pane>> {
1090        self.center.panes()
1091    }
1092
1093    /// Returns all non-empty terminal selections from all terminal views in all panes.
1094    pub fn terminal_selections(&self, cx: &App) -> Vec<String> {
1095        self.center
1096            .panes()
1097            .iter()
1098            .flat_map(|pane| {
1099                pane.read(cx).items().filter_map(|item| {
1100                    let terminal_view = item.downcast::<crate::TerminalView>()?;
1101                    terminal_view
1102                        .read(cx)
1103                        .terminal()
1104                        .read(cx)
1105                        .last_content
1106                        .selection_text
1107                        .clone()
1108                        .filter(|text| !text.is_empty())
1109                })
1110            })
1111            .collect()
1112    }
1113
1114    fn is_enabled(&self, cx: &App) -> bool {
1115        self.workspace
1116            .upgrade()
1117            .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1118    }
1119
1120    fn activate_pane_in_direction(
1121        &mut self,
1122        direction: SplitDirection,
1123        window: &mut Window,
1124        cx: &mut Context<Self>,
1125    ) {
1126        if let Some(pane) = self
1127            .center
1128            .find_pane_in_direction(&self.active_pane, direction, cx)
1129        {
1130            window.focus(&pane.focus_handle(cx), cx);
1131        } else {
1132            self.workspace
1133                .update(cx, |workspace, cx| {
1134                    workspace.activate_pane_in_direction(direction, window, cx)
1135                })
1136                .ok();
1137        }
1138    }
1139
1140    fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1141        if let Some(to) = self
1142            .center
1143            .find_pane_in_direction(&self.active_pane, direction, cx)
1144            .cloned()
1145        {
1146            self.center.swap(&self.active_pane, &to, cx);
1147            cx.notify();
1148        }
1149    }
1150
1151    fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1152        if self
1153            .center
1154            .move_to_border(&self.active_pane, direction, cx)
1155            .unwrap()
1156        {
1157            cx.notify();
1158        }
1159    }
1160}
1161
1162/// Prepares a `SpawnInTerminal` by computing the command, args, and command_label
1163/// based on the shell configuration. This is a pure function that can be tested
1164/// without spawning actual terminals.
1165pub fn prepare_task_for_spawn(
1166    task: &SpawnInTerminal,
1167    shell: &Shell,
1168    is_windows: bool,
1169) -> SpawnInTerminal {
1170    let builder = ShellBuilder::new(shell, is_windows);
1171    let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
1172    let (command, args) = builder.build_no_quote(task.command.clone(), &task.args);
1173
1174    SpawnInTerminal {
1175        command_label,
1176        command: Some(command),
1177        args,
1178        ..task.clone()
1179    }
1180}
1181
1182fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1183    workspace.project().read(cx).supports_terminal(cx)
1184}
1185
1186pub fn new_terminal_pane(
1187    workspace: WeakEntity<Workspace>,
1188    project: Entity<Project>,
1189    zoomed: bool,
1190    window: &mut Window,
1191    cx: &mut Context<TerminalPanel>,
1192) -> Entity<Pane> {
1193    let is_local = project.read(cx).is_local();
1194    let terminal_panel = cx.entity();
1195    let pane = cx.new(|cx| {
1196        let mut pane = Pane::new(
1197            workspace.clone(),
1198            project.clone(),
1199            Default::default(),
1200            None,
1201            workspace::NewTerminal::default().boxed_clone(),
1202            false,
1203            window,
1204            cx,
1205        );
1206        pane.set_zoomed(zoomed, cx);
1207        pane.set_can_navigate(false, cx);
1208        pane.display_nav_history_buttons(None);
1209        pane.set_should_display_tab_bar(|_, _| true);
1210        pane.set_zoom_out_on_close(false);
1211
1212        let split_closure_terminal_panel = terminal_panel.downgrade();
1213        pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1214            if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1215                let is_current_pane = tab.pane == cx.entity();
1216                let Some(can_drag_away) = split_closure_terminal_panel
1217                    .read_with(cx, |terminal_panel, _| {
1218                        let current_panes = terminal_panel.center.panes();
1219                        !current_panes.contains(&&tab.pane)
1220                            || current_panes.len() > 1
1221                            || (!is_current_pane || pane.items_len() > 1)
1222                    })
1223                    .ok()
1224                else {
1225                    return false;
1226                };
1227                if can_drag_away {
1228                    let item = if is_current_pane {
1229                        pane.item_for_index(tab.ix)
1230                    } else {
1231                        tab.pane.read(cx).item_for_index(tab.ix)
1232                    };
1233                    if let Some(item) = item {
1234                        return item.downcast::<TerminalView>().is_some();
1235                    }
1236                }
1237            }
1238            false
1239        })));
1240
1241        let buffer_search_bar = cx.new(|cx| {
1242            search::BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx)
1243        });
1244        let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1245        pane.toolbar().update(cx, |toolbar, cx| {
1246            toolbar.add_item(buffer_search_bar, window, cx);
1247            toolbar.add_item(breadcrumbs, window, cx);
1248        });
1249
1250        let drop_closure_project = project.downgrade();
1251        let drop_closure_terminal_panel = terminal_panel.downgrade();
1252        pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1253            let Some(project) = drop_closure_project.upgrade() else {
1254                return ControlFlow::Break(());
1255            };
1256            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1257                let this_pane = cx.entity();
1258                let item = if tab.pane == this_pane {
1259                    pane.item_for_index(tab.ix)
1260                } else {
1261                    tab.pane.read(cx).item_for_index(tab.ix)
1262                };
1263                if let Some(item) = item {
1264                    if item.downcast::<TerminalView>().is_some() {
1265                        let source = tab.pane.clone();
1266                        let item_id_to_move = item.item_id();
1267
1268                        // If no split direction, let the regular pane drop handler take care of it
1269                        let Some(split_direction) = pane.drag_split_direction() else {
1270                            return ControlFlow::Continue(());
1271                        };
1272
1273                        // Gather data synchronously before deferring
1274                        let is_zoomed = drop_closure_terminal_panel
1275                            .upgrade()
1276                            .map(|terminal_panel| {
1277                                let terminal_panel = terminal_panel.read(cx);
1278                                if terminal_panel.active_pane == this_pane {
1279                                    pane.is_zoomed()
1280                                } else {
1281                                    terminal_panel.active_pane.read(cx).is_zoomed()
1282                                }
1283                            })
1284                            .unwrap_or(false);
1285
1286                        let workspace = workspace.clone();
1287                        let terminal_panel = drop_closure_terminal_panel.clone();
1288
1289                        // Defer the split operation to avoid re-entrancy panic.
1290                        // The pane may be the one currently being updated, so we cannot
1291                        // call mark_positions (via split) synchronously.
1292                        cx.spawn_in(window, async move |_, cx| {
1293                            cx.update(|window, cx| {
1294                                let Ok(new_pane) =
1295                                    terminal_panel.update(cx, |terminal_panel, cx| {
1296                                        let new_pane = new_terminal_pane(
1297                                            workspace, project, is_zoomed, window, cx,
1298                                        );
1299                                        terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1300                                        terminal_panel.center.split(
1301                                            &this_pane,
1302                                            &new_pane,
1303                                            split_direction,
1304                                            cx,
1305                                        )?;
1306                                        anyhow::Ok(new_pane)
1307                                    })
1308                                else {
1309                                    return;
1310                                };
1311
1312                                let Some(new_pane) = new_pane.log_err() else {
1313                                    return;
1314                                };
1315
1316                                move_item(
1317                                    &source,
1318                                    &new_pane,
1319                                    item_id_to_move,
1320                                    new_pane.read(cx).active_item_index(),
1321                                    true,
1322                                    window,
1323                                    cx,
1324                                );
1325                            })
1326                            .ok();
1327                        })
1328                        .detach();
1329                    } else if let Some(project_path) = item.project_path(cx)
1330                        && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1331                    {
1332                        add_paths_to_terminal(pane, &[entry_path], window, cx);
1333                    }
1334                }
1335            } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1336                let project = project.read(cx);
1337                let paths_to_add = selection
1338                    .items()
1339                    .map(|selected_entry| selected_entry.entry_id)
1340                    .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1341                    .filter_map(|project_path| project.absolute_path(&project_path, cx))
1342                    .collect::<Vec<_>>();
1343                if !paths_to_add.is_empty() {
1344                    add_paths_to_terminal(pane, &paths_to_add, window, cx);
1345                }
1346            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1347                if let Some(entry_path) = project
1348                    .read(cx)
1349                    .path_for_entry(entry_id, cx)
1350                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1351                {
1352                    add_paths_to_terminal(pane, &[entry_path], window, cx);
1353                }
1354            } else if is_local && let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1355                add_paths_to_terminal(pane, paths.paths(), window, cx);
1356            }
1357
1358            ControlFlow::Break(())
1359        });
1360
1361        pane
1362    });
1363
1364    cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1365        .detach();
1366    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1367
1368    pane
1369}
1370
1371async fn wait_for_terminals_tasks(
1372    terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1373    cx: &mut AsyncApp,
1374) {
1375    let pending_tasks = terminals_for_task.iter().map(|(_, _, terminal)| {
1376        terminal.update(cx, |terminal_view, cx| {
1377            terminal_view
1378                .terminal()
1379                .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1380        })
1381    });
1382    join_all(pending_tasks).await;
1383}
1384
1385fn add_paths_to_terminal(
1386    pane: &mut Pane,
1387    paths: &[PathBuf],
1388    window: &mut Window,
1389    cx: &mut Context<Pane>,
1390) {
1391    if let Some(terminal_view) = pane
1392        .active_item()
1393        .and_then(|item| item.downcast::<TerminalView>())
1394    {
1395        window.focus(&terminal_view.focus_handle(cx), cx);
1396        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1397        new_text.push(' ');
1398        terminal_view.update(cx, |terminal_view, cx| {
1399            terminal_view.terminal().update(cx, |terminal, _| {
1400                terminal.paste(&new_text);
1401            });
1402        });
1403    }
1404}
1405
1406struct FailedToSpawnTerminal {
1407    error: String,
1408    focus_handle: FocusHandle,
1409}
1410
1411impl Focusable for FailedToSpawnTerminal {
1412    fn focus_handle(&self, _: &App) -> FocusHandle {
1413        self.focus_handle.clone()
1414    }
1415}
1416
1417impl Render for FailedToSpawnTerminal {
1418    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1419        let popover_menu = PopoverMenu::new("settings-popover")
1420            .trigger(
1421                IconButton::new("icon-button-popover", IconName::ChevronDown)
1422                    .icon_size(IconSize::XSmall),
1423            )
1424            .menu(move |window, cx| {
1425                Some(ContextMenu::build(window, cx, |context_menu, _, _| {
1426                    context_menu
1427                        .action("Open Settings", zed_actions::OpenSettings.boxed_clone())
1428                        .action(
1429                            "Edit settings.json",
1430                            zed_actions::OpenSettingsFile.boxed_clone(),
1431                        )
1432                }))
1433            })
1434            .anchor(Corner::TopRight)
1435            .offset(gpui::Point {
1436                x: px(0.0),
1437                y: px(2.0),
1438            });
1439
1440        v_flex()
1441            .track_focus(&self.focus_handle)
1442            .size_full()
1443            .p_4()
1444            .items_center()
1445            .justify_center()
1446            .bg(cx.theme().colors().editor_background)
1447            .child(
1448                v_flex()
1449                    .max_w_112()
1450                    .items_center()
1451                    .justify_center()
1452                    .text_center()
1453                    .child(Label::new("Failed to spawn terminal"))
1454                    .child(
1455                        Label::new(self.error.to_string())
1456                            .size(LabelSize::Small)
1457                            .color(Color::Muted)
1458                            .mb_4(),
1459                    )
1460                    .child(SplitButton::new(
1461                        ButtonLike::new("open-settings-ui")
1462                            .child(Label::new("Edit Settings").size(LabelSize::Small))
1463                            .on_click(|_, window, cx| {
1464                                window.dispatch_action(zed_actions::OpenSettings.boxed_clone(), cx);
1465                            }),
1466                        popover_menu.into_any_element(),
1467                    )),
1468            )
1469    }
1470}
1471
1472impl EventEmitter<()> for FailedToSpawnTerminal {}
1473
1474impl workspace::Item for FailedToSpawnTerminal {
1475    type Event = ();
1476
1477    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1478        SharedString::new_static("Failed to spawn terminal")
1479    }
1480}
1481
1482impl EventEmitter<PanelEvent> for TerminalPanel {}
1483
1484impl Render for TerminalPanel {
1485    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1486        let mut registrar = DivRegistrar::new(
1487            |panel, _, cx| {
1488                panel
1489                    .active_pane
1490                    .read(cx)
1491                    .toolbar()
1492                    .read(cx)
1493                    .item_of_type::<BufferSearchBar>()
1494            },
1495            cx,
1496        );
1497        BufferSearchBar::register(&mut registrar);
1498        let registrar = registrar.into_div();
1499        self.workspace
1500            .update(cx, |workspace, cx| {
1501                registrar.size_full().child(self.center.render(
1502                    workspace.zoomed_item(),
1503                    &workspace::PaneRenderContext {
1504                        follower_states: &HashMap::default(),
1505                        active_call: workspace.active_call(),
1506                        active_pane: &self.active_pane,
1507                        app_state: workspace.app_state(),
1508                        project: workspace.project(),
1509                        workspace: &workspace.weak_handle(),
1510                    },
1511                    window,
1512                    cx,
1513                ))
1514            })
1515            .ok()
1516            .map(|div| {
1517                div.on_action({
1518                    cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1519                        terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1520                    })
1521                })
1522                .on_action({
1523                    cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1524                        terminal_panel.activate_pane_in_direction(
1525                            SplitDirection::Right,
1526                            window,
1527                            cx,
1528                        );
1529                    })
1530                })
1531                .on_action({
1532                    cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1533                        terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1534                    })
1535                })
1536                .on_action({
1537                    cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1538                        terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1539                    })
1540                })
1541                .on_action(
1542                    cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1543                        let panes = terminal_panel.center.panes();
1544                        if let Some(ix) = panes
1545                            .iter()
1546                            .position(|pane| **pane == terminal_panel.active_pane)
1547                        {
1548                            let next_ix = (ix + 1) % panes.len();
1549                            window.focus(&panes[next_ix].focus_handle(cx), cx);
1550                        }
1551                    }),
1552                )
1553                .on_action(cx.listener(
1554                    |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1555                        let panes = terminal_panel.center.panes();
1556                        if let Some(ix) = panes
1557                            .iter()
1558                            .position(|pane| **pane == terminal_panel.active_pane)
1559                        {
1560                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1561                            window.focus(&panes[prev_ix].focus_handle(cx), cx);
1562                        }
1563                    },
1564                ))
1565                .on_action(
1566                    cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1567                        let panes = terminal_panel.center.panes();
1568                        if let Some(&pane) = panes.get(action.0) {
1569                            window.focus(&pane.read(cx).focus_handle(cx), cx);
1570                        } else {
1571                            let future =
1572                                terminal_panel.new_pane_with_active_terminal(true, window, cx);
1573                            cx.spawn_in(window, async move |terminal_panel, cx| {
1574                                if let Some(new_pane) = future.await {
1575                                    _ = terminal_panel.update_in(
1576                                        cx,
1577                                        |terminal_panel, window, cx| {
1578                                            terminal_panel
1579                                                .center
1580                                                .split(
1581                                                    &terminal_panel.active_pane,
1582                                                    &new_pane,
1583                                                    SplitDirection::Right,
1584                                                    cx,
1585                                                )
1586                                                .log_err();
1587                                            let new_pane = new_pane.read(cx);
1588                                            window.focus(&new_pane.focus_handle(cx), cx);
1589                                        },
1590                                    );
1591                                }
1592                            })
1593                            .detach();
1594                        }
1595                    }),
1596                )
1597                .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1598                    terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1599                }))
1600                .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1601                    terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1602                }))
1603                .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1604                    terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1605                }))
1606                .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1607                    terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1608                }))
1609                .on_action(cx.listener(|terminal_panel, _: &MovePaneLeft, _, cx| {
1610                    terminal_panel.move_pane_to_border(SplitDirection::Left, cx);
1611                }))
1612                .on_action(cx.listener(|terminal_panel, _: &MovePaneRight, _, cx| {
1613                    terminal_panel.move_pane_to_border(SplitDirection::Right, cx);
1614                }))
1615                .on_action(cx.listener(|terminal_panel, _: &MovePaneUp, _, cx| {
1616                    terminal_panel.move_pane_to_border(SplitDirection::Up, cx);
1617                }))
1618                .on_action(cx.listener(|terminal_panel, _: &MovePaneDown, _, cx| {
1619                    terminal_panel.move_pane_to_border(SplitDirection::Down, cx);
1620                }))
1621                .on_action(
1622                    cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1623                        let Some(&target_pane) =
1624                            terminal_panel.center.panes().get(action.destination)
1625                        else {
1626                            return;
1627                        };
1628                        move_active_item(
1629                            &terminal_panel.active_pane,
1630                            target_pane,
1631                            action.focus,
1632                            true,
1633                            window,
1634                            cx,
1635                        );
1636                    }),
1637                )
1638                .on_action(cx.listener(
1639                    |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1640                        let source_pane = &terminal_panel.active_pane;
1641                        if let Some(destination_pane) = terminal_panel
1642                            .center
1643                            .find_pane_in_direction(source_pane, action.direction, cx)
1644                        {
1645                            move_active_item(
1646                                source_pane,
1647                                destination_pane,
1648                                action.focus,
1649                                true,
1650                                window,
1651                                cx,
1652                            );
1653                        };
1654                    },
1655                ))
1656            })
1657            .unwrap_or_else(|| div())
1658    }
1659}
1660
1661impl Focusable for TerminalPanel {
1662    fn focus_handle(&self, cx: &App) -> FocusHandle {
1663        self.active_pane.focus_handle(cx)
1664    }
1665}
1666
1667impl Panel for TerminalPanel {
1668    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1669        match TerminalSettings::get_global(cx).dock {
1670            TerminalDockPosition::Left => DockPosition::Left,
1671            TerminalDockPosition::Bottom => DockPosition::Bottom,
1672            TerminalDockPosition::Right => DockPosition::Right,
1673        }
1674    }
1675
1676    fn position_is_valid(&self, _: DockPosition) -> bool {
1677        true
1678    }
1679
1680    fn set_position(
1681        &mut self,
1682        position: DockPosition,
1683        _window: &mut Window,
1684        cx: &mut Context<Self>,
1685    ) {
1686        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1687            let dock = match position {
1688                DockPosition::Left => TerminalDockPosition::Left,
1689                DockPosition::Bottom => TerminalDockPosition::Bottom,
1690                DockPosition::Right => TerminalDockPosition::Right,
1691            };
1692            settings.terminal.get_or_insert_default().dock = Some(dock);
1693        });
1694    }
1695
1696    fn size(&self, window: &Window, cx: &App) -> Pixels {
1697        let settings = TerminalSettings::get_global(cx);
1698        match self.position(window, cx) {
1699            DockPosition::Left | DockPosition::Right => {
1700                self.width.unwrap_or(settings.default_width)
1701            }
1702            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1703        }
1704    }
1705
1706    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1707        match self.position(window, cx) {
1708            DockPosition::Left | DockPosition::Right => self.width = size,
1709            DockPosition::Bottom => self.height = size,
1710        }
1711        cx.notify();
1712        cx.defer_in(window, |this, _, cx| {
1713            this.serialize(cx);
1714        })
1715    }
1716
1717    fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1718        self.active_pane.read(cx).is_zoomed()
1719    }
1720
1721    fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1722        for pane in self.center.panes() {
1723            pane.update(cx, |pane, cx| {
1724                pane.set_zoomed(zoomed, cx);
1725            })
1726        }
1727        cx.notify();
1728    }
1729
1730    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1731        let old_active = self.active;
1732        self.active = active;
1733        if !active || old_active == active || !self.has_no_terminals(cx) {
1734            return;
1735        }
1736        cx.defer_in(window, |this, window, cx| {
1737            let Ok(kind) = this
1738                .workspace
1739                .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1740            else {
1741                return;
1742            };
1743
1744            this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1745                .detach_and_log_err(cx)
1746        })
1747    }
1748
1749    fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1750        let count = self
1751            .center
1752            .panes()
1753            .into_iter()
1754            .map(|pane| pane.read(cx).items_len())
1755            .sum::<usize>();
1756        if count == 0 {
1757            None
1758        } else {
1759            Some(count.to_string())
1760        }
1761    }
1762
1763    fn persistent_name() -> &'static str {
1764        "TerminalPanel"
1765    }
1766
1767    fn panel_key() -> &'static str {
1768        TERMINAL_PANEL_KEY
1769    }
1770
1771    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1772        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1773            && TerminalSettings::get_global(cx).button
1774        {
1775            Some(IconName::TerminalAlt)
1776        } else {
1777            None
1778        }
1779    }
1780
1781    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1782        Some("Terminal Panel")
1783    }
1784
1785    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1786        Box::new(ToggleFocus)
1787    }
1788
1789    fn pane(&self) -> Option<Entity<Pane>> {
1790        Some(self.active_pane.clone())
1791    }
1792
1793    fn activation_priority(&self) -> u32 {
1794        1
1795    }
1796}
1797
1798struct TerminalProvider(Entity<TerminalPanel>);
1799
1800impl workspace::TerminalProvider for TerminalProvider {
1801    fn spawn(
1802        &self,
1803        task: SpawnInTerminal,
1804        window: &mut Window,
1805        cx: &mut App,
1806    ) -> Task<Option<Result<ExitStatus>>> {
1807        let terminal_panel = self.0.clone();
1808        window.spawn(cx, async move |cx| {
1809            let terminal = terminal_panel
1810                .update_in(cx, |terminal_panel, window, cx| {
1811                    terminal_panel.spawn_task(&task, window, cx)
1812                })
1813                .ok()?
1814                .await;
1815            match terminal {
1816                Ok(terminal) => {
1817                    let exit_status = terminal
1818                        .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1819                        .ok()?
1820                        .await?;
1821                    Some(Ok(exit_status))
1822                }
1823                Err(e) => Some(Err(e)),
1824            }
1825        })
1826    }
1827}
1828
1829struct InlineAssistTabBarButton {
1830    focus_handle: FocusHandle,
1831}
1832
1833impl Render for InlineAssistTabBarButton {
1834    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1835        let focus_handle = self.focus_handle.clone();
1836        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1837            .icon_size(IconSize::Small)
1838            .on_click(cx.listener(|_, _, window, cx| {
1839                window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1840            }))
1841            .tooltip(move |_window, cx| {
1842                Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1843            })
1844    }
1845}
1846
1847#[cfg(test)]
1848mod tests {
1849    use std::num::NonZero;
1850
1851    use super::*;
1852    use gpui::{TestAppContext, UpdateGlobal as _};
1853    use pretty_assertions::assert_eq;
1854    use project::FakeFs;
1855    use settings::SettingsStore;
1856
1857    #[test]
1858    fn test_prepare_empty_task() {
1859        let input = SpawnInTerminal::default();
1860        let shell = Shell::System;
1861
1862        let result = prepare_task_for_spawn(&input, &shell, false);
1863
1864        let expected_shell = util::get_system_shell();
1865        assert_eq!(result.env, HashMap::default());
1866        assert_eq!(result.cwd, None);
1867        assert_eq!(result.shell, Shell::System);
1868        assert_eq!(
1869            result.command,
1870            Some(expected_shell.clone()),
1871            "Empty tasks should spawn a -i shell"
1872        );
1873        assert_eq!(result.args, Vec::<String>::new());
1874        assert_eq!(
1875            result.command_label, expected_shell,
1876            "We show the shell launch for empty commands"
1877        );
1878    }
1879
1880    #[gpui::test]
1881    async fn test_bypass_max_tabs_limit(cx: &mut TestAppContext) {
1882        cx.executor().allow_parking();
1883        init_test(cx);
1884
1885        let fs = FakeFs::new(cx.executor());
1886        let project = Project::test(fs, [], cx).await;
1887        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1888
1889        let (window_handle, terminal_panel) = workspace
1890            .update(cx, |workspace, window, cx| {
1891                let window_handle = window.window_handle();
1892                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1893                (window_handle, terminal_panel)
1894            })
1895            .unwrap();
1896
1897        set_max_tabs(cx, Some(3));
1898
1899        for _ in 0..5 {
1900            let task = window_handle
1901                .update(cx, |_, window, cx| {
1902                    terminal_panel.update(cx, |panel, cx| {
1903                        panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1904                    })
1905                })
1906                .unwrap();
1907            task.await.unwrap();
1908        }
1909
1910        cx.run_until_parked();
1911
1912        let item_count =
1913            terminal_panel.read_with(cx, |panel, cx| panel.active_pane.read(cx).items_len());
1914
1915        assert_eq!(
1916            item_count, 5,
1917            "Terminal panel should bypass max_tabs limit and have all 5 terminals"
1918        );
1919    }
1920
1921    #[cfg(unix)]
1922    #[test]
1923    fn test_prepare_script_like_task() {
1924        let user_command = r#"REPO_URL=$(git remote get-url origin | sed -e \"s/^git@\\(.*\\):\\(.*\\)\\.git$/https:\\/\\/\\1\\/\\2/\"); COMMIT_SHA=$(git log -1 --format=\"%H\" -- \"${ZED_RELATIVE_FILE}\"); echo \"${REPO_URL}/blob/${COMMIT_SHA}/${ZED_RELATIVE_FILE}#L${ZED_ROW}-$(echo $(($(wc -l <<< \"$ZED_SELECTED_TEXT\") + $ZED_ROW - 1)))\" | xclip -selection clipboard"#.to_string();
1925        let expected_cwd = PathBuf::from("/some/work");
1926
1927        let input = SpawnInTerminal {
1928            command: Some(user_command.clone()),
1929            cwd: Some(expected_cwd.clone()),
1930            ..SpawnInTerminal::default()
1931        };
1932        let shell = Shell::System;
1933
1934        let result = prepare_task_for_spawn(&input, &shell, false);
1935
1936        let system_shell = util::get_system_shell();
1937        assert_eq!(result.env, HashMap::default());
1938        assert_eq!(result.cwd, Some(expected_cwd));
1939        assert_eq!(result.shell, Shell::System);
1940        assert_eq!(result.command, Some(system_shell.clone()));
1941        assert_eq!(
1942            result.args,
1943            vec!["-i".to_string(), "-c".to_string(), user_command.clone()],
1944            "User command should have been moved into the arguments, as we're spawning a new -i shell",
1945        );
1946        assert_eq!(
1947            result.command_label,
1948            format!(
1949                "{system_shell} {interactive}-c '{user_command}'",
1950                interactive = if cfg!(windows) { "" } else { "-i " }
1951            ),
1952            "We want to show to the user the entire command spawned"
1953        );
1954    }
1955
1956    #[gpui::test]
1957    async fn renders_error_if_default_shell_fails(cx: &mut TestAppContext) {
1958        cx.executor().allow_parking();
1959        init_test(cx);
1960
1961        cx.update(|cx| {
1962            SettingsStore::update_global(cx, |store, cx| {
1963                store.update_user_settings(cx, |settings| {
1964                    settings.terminal.get_or_insert_default().project.shell =
1965                        Some(settings::Shell::Program("__nonexistent_shell__".to_owned()));
1966                });
1967            });
1968        });
1969
1970        let fs = FakeFs::new(cx.executor());
1971        let project = Project::test(fs, [], cx).await;
1972        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1973
1974        let (window_handle, terminal_panel) = workspace
1975            .update(cx, |workspace, window, cx| {
1976                let window_handle = window.window_handle();
1977                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1978                (window_handle, terminal_panel)
1979            })
1980            .unwrap();
1981
1982        window_handle
1983            .update(cx, |_, window, cx| {
1984                terminal_panel.update(cx, |terminal_panel, cx| {
1985                    terminal_panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1986                })
1987            })
1988            .unwrap()
1989            .await
1990            .unwrap_err();
1991
1992        window_handle
1993            .update(cx, |_, _, cx| {
1994                terminal_panel.update(cx, |terminal_panel, cx| {
1995                    assert!(
1996                        terminal_panel
1997                            .active_pane
1998                            .read(cx)
1999                            .items()
2000                            .any(|item| item.downcast::<FailedToSpawnTerminal>().is_some()),
2001                        "should spawn `FailedToSpawnTerminal` pane"
2002                    );
2003                })
2004            })
2005            .unwrap();
2006    }
2007
2008    #[gpui::test]
2009    async fn test_local_terminal_in_local_project(cx: &mut TestAppContext) {
2010        cx.executor().allow_parking();
2011        init_test(cx);
2012
2013        let fs = FakeFs::new(cx.executor());
2014        let project = Project::test(fs, [], cx).await;
2015        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2016
2017        let (window_handle, terminal_panel) = workspace
2018            .update(cx, |workspace, window, cx| {
2019                let window_handle = window.window_handle();
2020                let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
2021                (window_handle, terminal_panel)
2022            })
2023            .unwrap();
2024
2025        let result = window_handle
2026            .update(cx, |_, window, cx| {
2027                terminal_panel.update(cx, |terminal_panel, cx| {
2028                    terminal_panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
2029                })
2030            })
2031            .unwrap()
2032            .await;
2033
2034        assert!(
2035            result.is_ok(),
2036            "local terminal should successfully create in local project"
2037        );
2038    }
2039
2040    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
2041        cx.update_global(|store: &mut SettingsStore, cx| {
2042            store.update_user_settings(cx, |settings| {
2043                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
2044            });
2045        });
2046    }
2047
2048    pub fn init_test(cx: &mut TestAppContext) {
2049        cx.update(|cx| {
2050            let store = SettingsStore::test(cx);
2051            cx.set_global(store);
2052            theme::init(theme::LoadThemes::JustBase, cx);
2053            editor::init(cx);
2054            crate::init(cx);
2055        });
2056    }
2057}