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};
  20
  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 toolbar = pane.toolbar().clone();
1242        if let Some(callbacks) = cx.try_global::<workspace::PaneSearchBarCallbacks>() {
1243            let languages = Some(project.read(cx).languages().clone());
1244            (callbacks.setup_search_bar)(languages, &toolbar, window, cx);
1245        }
1246        let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1247        toolbar.update(cx, |toolbar, cx| {
1248            toolbar.add_item(breadcrumbs, window, cx);
1249        });
1250
1251        let drop_closure_project = project.downgrade();
1252        let drop_closure_terminal_panel = terminal_panel.downgrade();
1253        pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1254            let Some(project) = drop_closure_project.upgrade() else {
1255                return ControlFlow::Break(());
1256            };
1257            if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1258                let this_pane = cx.entity();
1259                let item = if tab.pane == this_pane {
1260                    pane.item_for_index(tab.ix)
1261                } else {
1262                    tab.pane.read(cx).item_for_index(tab.ix)
1263                };
1264                if let Some(item) = item {
1265                    if item.downcast::<TerminalView>().is_some() {
1266                        let source = tab.pane.clone();
1267                        let item_id_to_move = item.item_id();
1268
1269                        // If no split direction, let the regular pane drop handler take care of it
1270                        let Some(split_direction) = pane.drag_split_direction() else {
1271                            return ControlFlow::Continue(());
1272                        };
1273
1274                        // Gather data synchronously before deferring
1275                        let is_zoomed = drop_closure_terminal_panel
1276                            .upgrade()
1277                            .map(|terminal_panel| {
1278                                let terminal_panel = terminal_panel.read(cx);
1279                                if terminal_panel.active_pane == this_pane {
1280                                    pane.is_zoomed()
1281                                } else {
1282                                    terminal_panel.active_pane.read(cx).is_zoomed()
1283                                }
1284                            })
1285                            .unwrap_or(false);
1286
1287                        let workspace = workspace.clone();
1288                        let terminal_panel = drop_closure_terminal_panel.clone();
1289
1290                        // Defer the split operation to avoid re-entrancy panic.
1291                        // The pane may be the one currently being updated, so we cannot
1292                        // call mark_positions (via split) synchronously.
1293                        cx.spawn_in(window, async move |_, cx| {
1294                            cx.update(|window, cx| {
1295                                let Ok(new_pane) =
1296                                    terminal_panel.update(cx, |terminal_panel, cx| {
1297                                        let new_pane = new_terminal_pane(
1298                                            workspace, project, is_zoomed, window, cx,
1299                                        );
1300                                        terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1301                                        terminal_panel.center.split(
1302                                            &this_pane,
1303                                            &new_pane,
1304                                            split_direction,
1305                                            cx,
1306                                        )?;
1307                                        anyhow::Ok(new_pane)
1308                                    })
1309                                else {
1310                                    return;
1311                                };
1312
1313                                let Some(new_pane) = new_pane.log_err() else {
1314                                    return;
1315                                };
1316
1317                                move_item(
1318                                    &source,
1319                                    &new_pane,
1320                                    item_id_to_move,
1321                                    new_pane.read(cx).active_item_index(),
1322                                    true,
1323                                    window,
1324                                    cx,
1325                                );
1326                            })
1327                            .ok();
1328                        })
1329                        .detach();
1330                    } else if let Some(project_path) = item.project_path(cx)
1331                        && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1332                    {
1333                        add_paths_to_terminal(pane, &[entry_path], window, cx);
1334                    }
1335                }
1336            } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1337                let project = project.read(cx);
1338                let paths_to_add = selection
1339                    .items()
1340                    .map(|selected_entry| selected_entry.entry_id)
1341                    .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1342                    .filter_map(|project_path| project.absolute_path(&project_path, cx))
1343                    .collect::<Vec<_>>();
1344                if !paths_to_add.is_empty() {
1345                    add_paths_to_terminal(pane, &paths_to_add, window, cx);
1346                }
1347            } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1348                if let Some(entry_path) = project
1349                    .read(cx)
1350                    .path_for_entry(entry_id, cx)
1351                    .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1352                {
1353                    add_paths_to_terminal(pane, &[entry_path], window, cx);
1354                }
1355            } else if is_local && let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1356                add_paths_to_terminal(pane, paths.paths(), window, cx);
1357            }
1358
1359            ControlFlow::Break(())
1360        });
1361
1362        pane
1363    });
1364
1365    cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1366        .detach();
1367    cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1368
1369    pane
1370}
1371
1372async fn wait_for_terminals_tasks(
1373    terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1374    cx: &mut AsyncApp,
1375) {
1376    let pending_tasks = terminals_for_task.iter().map(|(_, _, terminal)| {
1377        terminal.update(cx, |terminal_view, cx| {
1378            terminal_view
1379                .terminal()
1380                .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1381        })
1382    });
1383    join_all(pending_tasks).await;
1384}
1385
1386fn add_paths_to_terminal(
1387    pane: &mut Pane,
1388    paths: &[PathBuf],
1389    window: &mut Window,
1390    cx: &mut Context<Pane>,
1391) {
1392    if let Some(terminal_view) = pane
1393        .active_item()
1394        .and_then(|item| item.downcast::<TerminalView>())
1395    {
1396        window.focus(&terminal_view.focus_handle(cx), cx);
1397        let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1398        new_text.push(' ');
1399        terminal_view.update(cx, |terminal_view, cx| {
1400            terminal_view.terminal().update(cx, |terminal, _| {
1401                terminal.paste(&new_text);
1402            });
1403        });
1404    }
1405}
1406
1407struct FailedToSpawnTerminal {
1408    error: String,
1409    focus_handle: FocusHandle,
1410}
1411
1412impl Focusable for FailedToSpawnTerminal {
1413    fn focus_handle(&self, _: &App) -> FocusHandle {
1414        self.focus_handle.clone()
1415    }
1416}
1417
1418impl Render for FailedToSpawnTerminal {
1419    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1420        let popover_menu = PopoverMenu::new("settings-popover")
1421            .trigger(
1422                IconButton::new("icon-button-popover", IconName::ChevronDown)
1423                    .icon_size(IconSize::XSmall),
1424            )
1425            .menu(move |window, cx| {
1426                Some(ContextMenu::build(window, cx, |context_menu, _, _| {
1427                    context_menu
1428                        .action("Open Settings", zed_actions::OpenSettings.boxed_clone())
1429                        .action(
1430                            "Edit settings.json",
1431                            zed_actions::OpenSettingsFile.boxed_clone(),
1432                        )
1433                }))
1434            })
1435            .anchor(Corner::TopRight)
1436            .offset(gpui::Point {
1437                x: px(0.0),
1438                y: px(2.0),
1439            });
1440
1441        v_flex()
1442            .track_focus(&self.focus_handle)
1443            .size_full()
1444            .p_4()
1445            .items_center()
1446            .justify_center()
1447            .bg(cx.theme().colors().editor_background)
1448            .child(
1449                v_flex()
1450                    .max_w_112()
1451                    .items_center()
1452                    .justify_center()
1453                    .text_center()
1454                    .child(Label::new("Failed to spawn terminal"))
1455                    .child(
1456                        Label::new(self.error.to_string())
1457                            .size(LabelSize::Small)
1458                            .color(Color::Muted)
1459                            .mb_4(),
1460                    )
1461                    .child(SplitButton::new(
1462                        ButtonLike::new("open-settings-ui")
1463                            .child(Label::new("Edit Settings").size(LabelSize::Small))
1464                            .on_click(|_, window, cx| {
1465                                window.dispatch_action(zed_actions::OpenSettings.boxed_clone(), cx);
1466                            }),
1467                        popover_menu.into_any_element(),
1468                    )),
1469            )
1470    }
1471}
1472
1473impl EventEmitter<()> for FailedToSpawnTerminal {}
1474
1475impl workspace::Item for FailedToSpawnTerminal {
1476    type Event = ();
1477
1478    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1479        SharedString::new_static("Failed to spawn terminal")
1480    }
1481}
1482
1483impl EventEmitter<PanelEvent> for TerminalPanel {}
1484
1485impl Render for TerminalPanel {
1486    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1487        let registrar = cx
1488            .try_global::<workspace::PaneSearchBarCallbacks>()
1489            .map(|callbacks| {
1490                (callbacks.wrap_div_with_search_actions)(div(), self.active_pane.clone())
1491            })
1492            .unwrap_or_else(div);
1493        self.workspace
1494            .update(cx, |workspace, cx| {
1495                registrar.size_full().child(self.center.render(
1496                    workspace.zoomed_item(),
1497                    &workspace::PaneRenderContext {
1498                        follower_states: &HashMap::default(),
1499                        active_call: workspace.active_call(),
1500                        active_pane: &self.active_pane,
1501                        app_state: workspace.app_state(),
1502                        project: workspace.project(),
1503                        workspace: &workspace.weak_handle(),
1504                    },
1505                    window,
1506                    cx,
1507                ))
1508            })
1509            .ok()
1510            .map(|div| {
1511                div.on_action({
1512                    cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1513                        terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1514                    })
1515                })
1516                .on_action({
1517                    cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1518                        terminal_panel.activate_pane_in_direction(
1519                            SplitDirection::Right,
1520                            window,
1521                            cx,
1522                        );
1523                    })
1524                })
1525                .on_action({
1526                    cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1527                        terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1528                    })
1529                })
1530                .on_action({
1531                    cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1532                        terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1533                    })
1534                })
1535                .on_action(
1536                    cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1537                        let panes = terminal_panel.center.panes();
1538                        if let Some(ix) = panes
1539                            .iter()
1540                            .position(|pane| **pane == terminal_panel.active_pane)
1541                        {
1542                            let next_ix = (ix + 1) % panes.len();
1543                            window.focus(&panes[next_ix].focus_handle(cx), cx);
1544                        }
1545                    }),
1546                )
1547                .on_action(cx.listener(
1548                    |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1549                        let panes = terminal_panel.center.panes();
1550                        if let Some(ix) = panes
1551                            .iter()
1552                            .position(|pane| **pane == terminal_panel.active_pane)
1553                        {
1554                            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1555                            window.focus(&panes[prev_ix].focus_handle(cx), cx);
1556                        }
1557                    },
1558                ))
1559                .on_action(
1560                    cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1561                        let panes = terminal_panel.center.panes();
1562                        if let Some(&pane) = panes.get(action.0) {
1563                            window.focus(&pane.read(cx).focus_handle(cx), cx);
1564                        } else {
1565                            let future =
1566                                terminal_panel.new_pane_with_active_terminal(true, window, cx);
1567                            cx.spawn_in(window, async move |terminal_panel, cx| {
1568                                if let Some(new_pane) = future.await {
1569                                    _ = terminal_panel.update_in(
1570                                        cx,
1571                                        |terminal_panel, window, cx| {
1572                                            terminal_panel
1573                                                .center
1574                                                .split(
1575                                                    &terminal_panel.active_pane,
1576                                                    &new_pane,
1577                                                    SplitDirection::Right,
1578                                                    cx,
1579                                                )
1580                                                .log_err();
1581                                            let new_pane = new_pane.read(cx);
1582                                            window.focus(&new_pane.focus_handle(cx), cx);
1583                                        },
1584                                    );
1585                                }
1586                            })
1587                            .detach();
1588                        }
1589                    }),
1590                )
1591                .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1592                    terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1593                }))
1594                .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1595                    terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1596                }))
1597                .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1598                    terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1599                }))
1600                .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1601                    terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1602                }))
1603                .on_action(cx.listener(|terminal_panel, _: &MovePaneLeft, _, cx| {
1604                    terminal_panel.move_pane_to_border(SplitDirection::Left, cx);
1605                }))
1606                .on_action(cx.listener(|terminal_panel, _: &MovePaneRight, _, cx| {
1607                    terminal_panel.move_pane_to_border(SplitDirection::Right, cx);
1608                }))
1609                .on_action(cx.listener(|terminal_panel, _: &MovePaneUp, _, cx| {
1610                    terminal_panel.move_pane_to_border(SplitDirection::Up, cx);
1611                }))
1612                .on_action(cx.listener(|terminal_panel, _: &MovePaneDown, _, cx| {
1613                    terminal_panel.move_pane_to_border(SplitDirection::Down, cx);
1614                }))
1615                .on_action(
1616                    cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1617                        let Some(&target_pane) =
1618                            terminal_panel.center.panes().get(action.destination)
1619                        else {
1620                            return;
1621                        };
1622                        move_active_item(
1623                            &terminal_panel.active_pane,
1624                            target_pane,
1625                            action.focus,
1626                            true,
1627                            window,
1628                            cx,
1629                        );
1630                    }),
1631                )
1632                .on_action(cx.listener(
1633                    |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1634                        let source_pane = &terminal_panel.active_pane;
1635                        if let Some(destination_pane) = terminal_panel
1636                            .center
1637                            .find_pane_in_direction(source_pane, action.direction, cx)
1638                        {
1639                            move_active_item(
1640                                source_pane,
1641                                destination_pane,
1642                                action.focus,
1643                                true,
1644                                window,
1645                                cx,
1646                            );
1647                        };
1648                    },
1649                ))
1650            })
1651            .unwrap_or_else(|| div())
1652    }
1653}
1654
1655impl Focusable for TerminalPanel {
1656    fn focus_handle(&self, cx: &App) -> FocusHandle {
1657        self.active_pane.focus_handle(cx)
1658    }
1659}
1660
1661impl Panel for TerminalPanel {
1662    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1663        match TerminalSettings::get_global(cx).dock {
1664            TerminalDockPosition::Left => DockPosition::Left,
1665            TerminalDockPosition::Bottom => DockPosition::Bottom,
1666            TerminalDockPosition::Right => DockPosition::Right,
1667        }
1668    }
1669
1670    fn position_is_valid(&self, _: DockPosition) -> bool {
1671        true
1672    }
1673
1674    fn set_position(
1675        &mut self,
1676        position: DockPosition,
1677        _window: &mut Window,
1678        cx: &mut Context<Self>,
1679    ) {
1680        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1681            let dock = match position {
1682                DockPosition::Left => TerminalDockPosition::Left,
1683                DockPosition::Bottom => TerminalDockPosition::Bottom,
1684                DockPosition::Right => TerminalDockPosition::Right,
1685            };
1686            settings.terminal.get_or_insert_default().dock = Some(dock);
1687        });
1688    }
1689
1690    fn size(&self, window: &Window, cx: &App) -> Pixels {
1691        let settings = TerminalSettings::get_global(cx);
1692        match self.position(window, cx) {
1693            DockPosition::Left | DockPosition::Right => {
1694                self.width.unwrap_or(settings.default_width)
1695            }
1696            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1697        }
1698    }
1699
1700    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1701        match self.position(window, cx) {
1702            DockPosition::Left | DockPosition::Right => self.width = size,
1703            DockPosition::Bottom => self.height = size,
1704        }
1705        cx.notify();
1706        cx.defer_in(window, |this, _, cx| {
1707            this.serialize(cx);
1708        })
1709    }
1710
1711    fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1712        self.active_pane.read(cx).is_zoomed()
1713    }
1714
1715    fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1716        for pane in self.center.panes() {
1717            pane.update(cx, |pane, cx| {
1718                pane.set_zoomed(zoomed, cx);
1719            })
1720        }
1721        cx.notify();
1722    }
1723
1724    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1725        let old_active = self.active;
1726        self.active = active;
1727        if !active || old_active == active || !self.has_no_terminals(cx) {
1728            return;
1729        }
1730        cx.defer_in(window, |this, window, cx| {
1731            let Ok(kind) = this
1732                .workspace
1733                .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1734            else {
1735                return;
1736            };
1737
1738            this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1739                .detach_and_log_err(cx)
1740        })
1741    }
1742
1743    fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1744        let count = self
1745            .center
1746            .panes()
1747            .into_iter()
1748            .map(|pane| pane.read(cx).items_len())
1749            .sum::<usize>();
1750        if count == 0 {
1751            None
1752        } else {
1753            Some(count.to_string())
1754        }
1755    }
1756
1757    fn persistent_name() -> &'static str {
1758        "TerminalPanel"
1759    }
1760
1761    fn panel_key() -> &'static str {
1762        TERMINAL_PANEL_KEY
1763    }
1764
1765    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1766        if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1767            && TerminalSettings::get_global(cx).button
1768        {
1769            Some(IconName::TerminalAlt)
1770        } else {
1771            None
1772        }
1773    }
1774
1775    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1776        Some("Terminal Panel")
1777    }
1778
1779    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1780        Box::new(ToggleFocus)
1781    }
1782
1783    fn pane(&self) -> Option<Entity<Pane>> {
1784        Some(self.active_pane.clone())
1785    }
1786
1787    fn activation_priority(&self) -> u32 {
1788        1
1789    }
1790}
1791
1792struct TerminalProvider(Entity<TerminalPanel>);
1793
1794impl workspace::TerminalProvider for TerminalProvider {
1795    fn spawn(
1796        &self,
1797        task: SpawnInTerminal,
1798        window: &mut Window,
1799        cx: &mut App,
1800    ) -> Task<Option<Result<ExitStatus>>> {
1801        let terminal_panel = self.0.clone();
1802        window.spawn(cx, async move |cx| {
1803            let terminal = terminal_panel
1804                .update_in(cx, |terminal_panel, window, cx| {
1805                    terminal_panel.spawn_task(&task, window, cx)
1806                })
1807                .ok()?
1808                .await;
1809            match terminal {
1810                Ok(terminal) => {
1811                    let exit_status = terminal
1812                        .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1813                        .ok()?
1814                        .await?;
1815                    Some(Ok(exit_status))
1816                }
1817                Err(e) => Some(Err(e)),
1818            }
1819        })
1820    }
1821}
1822
1823struct InlineAssistTabBarButton {
1824    focus_handle: FocusHandle,
1825}
1826
1827impl Render for InlineAssistTabBarButton {
1828    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1829        let focus_handle = self.focus_handle.clone();
1830        IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1831            .icon_size(IconSize::Small)
1832            .on_click(cx.listener(|_, _, window, cx| {
1833                window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1834            }))
1835            .tooltip(move |_window, cx| {
1836                Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1837            })
1838    }
1839}
1840
1841#[cfg(test)]
1842mod tests {
1843    use std::num::NonZero;
1844
1845    use super::*;
1846    use gpui::{TestAppContext, UpdateGlobal as _};
1847    use pretty_assertions::assert_eq;
1848    use project::FakeFs;
1849    use settings::SettingsStore;
1850    use workspace::MultiWorkspace;
1851
1852    #[test]
1853    fn test_prepare_empty_task() {
1854        let input = SpawnInTerminal::default();
1855        let shell = Shell::System;
1856
1857        let result = prepare_task_for_spawn(&input, &shell, false);
1858
1859        let expected_shell = util::get_system_shell();
1860        assert_eq!(result.env, HashMap::default());
1861        assert_eq!(result.cwd, None);
1862        assert_eq!(result.shell, Shell::System);
1863        assert_eq!(
1864            result.command,
1865            Some(expected_shell.clone()),
1866            "Empty tasks should spawn a -i shell"
1867        );
1868        assert_eq!(result.args, Vec::<String>::new());
1869        assert_eq!(
1870            result.command_label, expected_shell,
1871            "We show the shell launch for empty commands"
1872        );
1873    }
1874
1875    #[gpui::test]
1876    async fn test_bypass_max_tabs_limit(cx: &mut TestAppContext) {
1877        cx.executor().allow_parking();
1878        init_test(cx);
1879
1880        let fs = FakeFs::new(cx.executor());
1881        let project = Project::test(fs, [], cx).await;
1882        let window_handle =
1883            cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1884
1885        let terminal_panel = window_handle
1886            .update(cx, |multi_workspace, window, cx| {
1887                multi_workspace.workspace().update(cx, |workspace, cx| {
1888                    cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1889                })
1890            })
1891            .unwrap();
1892
1893        set_max_tabs(cx, Some(3));
1894
1895        for _ in 0..5 {
1896            let task = window_handle
1897                .update(cx, |_, window, cx| {
1898                    terminal_panel.update(cx, |panel, cx| {
1899                        panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1900                    })
1901                })
1902                .unwrap();
1903            task.await.unwrap();
1904        }
1905
1906        cx.run_until_parked();
1907
1908        let item_count =
1909            terminal_panel.read_with(cx, |panel, cx| panel.active_pane.read(cx).items_len());
1910
1911        assert_eq!(
1912            item_count, 5,
1913            "Terminal panel should bypass max_tabs limit and have all 5 terminals"
1914        );
1915    }
1916
1917    #[cfg(unix)]
1918    #[test]
1919    fn test_prepare_script_like_task() {
1920        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();
1921        let expected_cwd = PathBuf::from("/some/work");
1922
1923        let input = SpawnInTerminal {
1924            command: Some(user_command.clone()),
1925            cwd: Some(expected_cwd.clone()),
1926            ..SpawnInTerminal::default()
1927        };
1928        let shell = Shell::System;
1929
1930        let result = prepare_task_for_spawn(&input, &shell, false);
1931
1932        let system_shell = util::get_system_shell();
1933        assert_eq!(result.env, HashMap::default());
1934        assert_eq!(result.cwd, Some(expected_cwd));
1935        assert_eq!(result.shell, Shell::System);
1936        assert_eq!(result.command, Some(system_shell.clone()));
1937        assert_eq!(
1938            result.args,
1939            vec!["-i".to_string(), "-c".to_string(), user_command.clone()],
1940            "User command should have been moved into the arguments, as we're spawning a new -i shell",
1941        );
1942        assert_eq!(
1943            result.command_label,
1944            format!(
1945                "{system_shell} {interactive}-c '{user_command}'",
1946                interactive = if cfg!(windows) { "" } else { "-i " }
1947            ),
1948            "We want to show to the user the entire command spawned"
1949        );
1950    }
1951
1952    #[gpui::test]
1953    async fn renders_error_if_default_shell_fails(cx: &mut TestAppContext) {
1954        cx.executor().allow_parking();
1955        init_test(cx);
1956
1957        cx.update(|cx| {
1958            SettingsStore::update_global(cx, |store, cx| {
1959                store.update_user_settings(cx, |settings| {
1960                    settings.terminal.get_or_insert_default().project.shell =
1961                        Some(settings::Shell::Program("__nonexistent_shell__".to_owned()));
1962                });
1963            });
1964        });
1965
1966        let fs = FakeFs::new(cx.executor());
1967        let project = Project::test(fs, [], cx).await;
1968        let window_handle =
1969            cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1970
1971        let terminal_panel = window_handle
1972            .update(cx, |multi_workspace, window, cx| {
1973                multi_workspace.workspace().update(cx, |workspace, cx| {
1974                    cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1975                })
1976            })
1977            .unwrap();
1978
1979        window_handle
1980            .update(cx, |_, window, cx| {
1981                terminal_panel.update(cx, |terminal_panel, cx| {
1982                    terminal_panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1983                })
1984            })
1985            .unwrap()
1986            .await
1987            .unwrap_err();
1988
1989        window_handle
1990            .update(cx, |_, _, cx| {
1991                terminal_panel.update(cx, |terminal_panel, cx| {
1992                    assert!(
1993                        terminal_panel
1994                            .active_pane
1995                            .read(cx)
1996                            .items()
1997                            .any(|item| item.downcast::<FailedToSpawnTerminal>().is_some()),
1998                        "should spawn `FailedToSpawnTerminal` pane"
1999                    );
2000                })
2001            })
2002            .unwrap();
2003    }
2004
2005    #[gpui::test]
2006    async fn test_local_terminal_in_local_project(cx: &mut TestAppContext) {
2007        cx.executor().allow_parking();
2008        init_test(cx);
2009
2010        let fs = FakeFs::new(cx.executor());
2011        let project = Project::test(fs, [], cx).await;
2012        let window_handle =
2013            cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
2014
2015        let terminal_panel = window_handle
2016            .update(cx, |multi_workspace, window, cx| {
2017                multi_workspace.workspace().update(cx, |workspace, cx| {
2018                    cx.new(|cx| TerminalPanel::new(workspace, window, cx))
2019                })
2020            })
2021            .unwrap();
2022
2023        let result = window_handle
2024            .update(cx, |_, window, cx| {
2025                terminal_panel.update(cx, |terminal_panel, cx| {
2026                    terminal_panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
2027                })
2028            })
2029            .unwrap()
2030            .await;
2031
2032        assert!(
2033            result.is_ok(),
2034            "local terminal should successfully create in local project"
2035        );
2036    }
2037
2038    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
2039        cx.update_global(|store: &mut SettingsStore, cx| {
2040            store.update_user_settings(cx, |settings| {
2041                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
2042            });
2043        });
2044    }
2045
2046    pub fn init_test(cx: &mut TestAppContext) {
2047        cx.update(|cx| {
2048            let store = SettingsStore::test(cx);
2049            cx.set_global(store);
2050            theme::init(theme::LoadThemes::JustBase, cx);
2051            editor::init(cx);
2052            crate::init(cx);
2053        });
2054    }
2055}