multi_workspace.rs

  1use anyhow::Result;
  2use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
  3use gpui::{
  4    AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
  5    ManagedView, MouseButton, Pixels, Render, Subscription, Task, Tiling, Window, WindowId,
  6    actions, deferred, px,
  7};
  8use project::DisableAiSettings;
  9#[cfg(any(test, feature = "test-support"))]
 10use project::Project;
 11use settings::Settings;
 12use std::future::Future;
 13use std::path::PathBuf;
 14use ui::prelude::*;
 15use util::ResultExt;
 16
 17const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
 18
 19use crate::{
 20    CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, Panel,
 21    Workspace, WorkspaceId, client_side_decorations,
 22};
 23
 24actions!(
 25    multi_workspace,
 26    [
 27        /// Toggles the workspace switcher sidebar.
 28        ToggleWorkspaceSidebar,
 29        /// Moves focus to or from the workspace sidebar without closing it.
 30        FocusWorkspaceSidebar,
 31    ]
 32);
 33
 34pub enum MultiWorkspaceEvent {
 35    ActiveWorkspaceChanged,
 36    WorkspaceAdded(Entity<Workspace>),
 37    WorkspaceRemoved(EntityId),
 38}
 39
 40pub trait Sidebar: Focusable + Render + Sized {
 41    fn width(&self, cx: &App) -> Pixels;
 42    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
 43    fn has_notifications(&self, cx: &App) -> bool;
 44    fn toggle_recent_projects_popover(&self, window: &mut Window, cx: &mut App);
 45    fn is_recent_projects_popover_deployed(&self) -> bool;
 46    fn is_threads_list_view_active(&self) -> bool {
 47        true
 48    }
 49    /// Makes focus reset bac to the search editor upon toggling the sidebar from outside
 50    fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
 51}
 52
 53pub trait SidebarHandle: 'static + Send + Sync {
 54    fn width(&self, cx: &App) -> Pixels;
 55    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
 56    fn focus_handle(&self, cx: &App) -> FocusHandle;
 57    fn focus(&self, window: &mut Window, cx: &mut App);
 58    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
 59    fn has_notifications(&self, cx: &App) -> bool;
 60    fn to_any(&self) -> AnyView;
 61    fn entity_id(&self) -> EntityId;
 62    fn toggle_recent_projects_popover(&self, window: &mut Window, cx: &mut App);
 63    fn is_recent_projects_popover_deployed(&self, cx: &App) -> bool;
 64    fn is_threads_list_view_active(&self, cx: &App) -> bool;
 65}
 66
 67#[derive(Clone)]
 68pub struct DraggedSidebar;
 69
 70impl Render for DraggedSidebar {
 71    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 72        gpui::Empty
 73    }
 74}
 75
 76impl<T: Sidebar> SidebarHandle for Entity<T> {
 77    fn width(&self, cx: &App) -> Pixels {
 78        self.read(cx).width(cx)
 79    }
 80
 81    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
 82        self.update(cx, |this, cx| this.set_width(width, cx))
 83    }
 84
 85    fn focus_handle(&self, cx: &App) -> FocusHandle {
 86        self.read(cx).focus_handle(cx)
 87    }
 88
 89    fn focus(&self, window: &mut Window, cx: &mut App) {
 90        let handle = self.read(cx).focus_handle(cx);
 91        window.focus(&handle, cx);
 92    }
 93
 94    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
 95        self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
 96    }
 97
 98    fn has_notifications(&self, cx: &App) -> bool {
 99        self.read(cx).has_notifications(cx)
100    }
101
102    fn to_any(&self) -> AnyView {
103        self.clone().into()
104    }
105
106    fn entity_id(&self) -> EntityId {
107        Entity::entity_id(self)
108    }
109
110    fn toggle_recent_projects_popover(&self, window: &mut Window, cx: &mut App) {
111        self.update(cx, |this, cx| {
112            this.toggle_recent_projects_popover(window, cx);
113        });
114    }
115
116    fn is_recent_projects_popover_deployed(&self, cx: &App) -> bool {
117        self.read(cx).is_recent_projects_popover_deployed()
118    }
119
120    fn is_threads_list_view_active(&self, cx: &App) -> bool {
121        self.read(cx).is_threads_list_view_active()
122    }
123}
124
125pub struct MultiWorkspace {
126    window_id: WindowId,
127    workspaces: Vec<Entity<Workspace>>,
128    active_workspace_index: usize,
129    sidebar: Option<Box<dyn SidebarHandle>>,
130    sidebar_open: bool,
131    pending_removal_tasks: Vec<Task<()>>,
132    _serialize_task: Option<Task<()>>,
133    _subscriptions: Vec<Subscription>,
134}
135
136impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
137
138impl MultiWorkspace {
139    pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
140        let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
141            if let Some(task) = this._serialize_task.take() {
142                task.detach();
143            }
144            for task in std::mem::take(&mut this.pending_removal_tasks) {
145                task.detach();
146            }
147        });
148        let quit_subscription = cx.on_app_quit(Self::app_will_quit);
149        let settings_subscription =
150            cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
151                if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
152                    this.close_sidebar(window, cx);
153                }
154            });
155        Self::subscribe_to_workspace(&workspace, cx);
156        Self {
157            window_id: window.window_handle().window_id(),
158            workspaces: vec![workspace],
159            active_workspace_index: 0,
160            sidebar: None,
161            sidebar_open: false,
162            pending_removal_tasks: Vec::new(),
163            _serialize_task: None,
164            _subscriptions: vec![
165                release_subscription,
166                quit_subscription,
167                settings_subscription,
168            ],
169        }
170    }
171
172    pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
173        self._subscriptions
174            .push(cx.observe(&sidebar, |this, _, cx| {
175                let has_notifications = this.sidebar_has_notifications(cx);
176                let is_open = this.sidebar_open;
177                let show_toggle = this.multi_workspace_enabled(cx);
178                for workspace in &this.workspaces {
179                    workspace.update(cx, |workspace, cx| {
180                        workspace.set_workspace_sidebar_open(
181                            is_open,
182                            has_notifications,
183                            show_toggle,
184                            cx,
185                        );
186                    });
187                }
188            }));
189        self.sidebar = Some(Box::new(sidebar));
190    }
191
192    pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
193        self.sidebar.as_deref()
194    }
195
196    pub fn sidebar_open(&self) -> bool {
197        self.sidebar_open
198    }
199
200    pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
201        self.sidebar
202            .as_ref()
203            .map_or(false, |s| s.has_notifications(cx))
204    }
205
206    pub fn toggle_recent_projects_popover(&self, window: &mut Window, cx: &mut App) {
207        if let Some(sidebar) = &self.sidebar {
208            sidebar.toggle_recent_projects_popover(window, cx);
209        }
210    }
211
212    pub fn is_recent_projects_popover_deployed(&self, cx: &App) -> bool {
213        self.sidebar
214            .as_ref()
215            .map_or(false, |s| s.is_recent_projects_popover_deployed(cx))
216    }
217
218    pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
219        self.sidebar
220            .as_ref()
221            .map_or(false, |s| s.is_threads_list_view_active(cx))
222    }
223
224    pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
225        cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
226    }
227
228    pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
229        if !self.multi_workspace_enabled(cx) {
230            return;
231        }
232
233        if self.sidebar_open {
234            self.close_sidebar(window, cx);
235        } else {
236            self.open_sidebar(cx);
237            if let Some(sidebar) = &self.sidebar {
238                sidebar.prepare_for_focus(window, cx);
239                sidebar.focus(window, cx);
240            }
241        }
242    }
243
244    pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
245        if !self.multi_workspace_enabled(cx) {
246            return;
247        }
248
249        if self.sidebar_open {
250            let sidebar_is_focused = self
251                .sidebar
252                .as_ref()
253                .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
254
255            if sidebar_is_focused {
256                let pane = self.workspace().read(cx).active_pane().clone();
257                let pane_focus = pane.read(cx).focus_handle(cx);
258                window.focus(&pane_focus, cx);
259            } else if let Some(sidebar) = &self.sidebar {
260                sidebar.prepare_for_focus(window, cx);
261                sidebar.focus(window, cx);
262            }
263        } else {
264            self.open_sidebar(cx);
265            if let Some(sidebar) = &self.sidebar {
266                sidebar.prepare_for_focus(window, cx);
267                sidebar.focus(window, cx);
268            }
269        }
270    }
271
272    pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
273        self.sidebar_open = true;
274        let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
275        let has_notifications = self.sidebar_has_notifications(cx);
276        let show_toggle = self.multi_workspace_enabled(cx);
277        for workspace in &self.workspaces {
278            workspace.update(cx, |workspace, cx| {
279                workspace.set_workspace_sidebar_open(true, has_notifications, show_toggle, cx);
280                workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
281            });
282        }
283        self.serialize(cx);
284        cx.notify();
285    }
286
287    fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
288        self.sidebar_open = false;
289        let has_notifications = self.sidebar_has_notifications(cx);
290        let show_toggle = self.multi_workspace_enabled(cx);
291        for workspace in &self.workspaces {
292            workspace.update(cx, |workspace, cx| {
293                workspace.set_workspace_sidebar_open(false, has_notifications, show_toggle, cx);
294                workspace.set_sidebar_focus_handle(None);
295            });
296        }
297        let pane = self.workspace().read(cx).active_pane().clone();
298        let pane_focus = pane.read(cx).focus_handle(cx);
299        window.focus(&pane_focus, cx);
300        self.serialize(cx);
301        cx.notify();
302    }
303
304    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
305        cx.spawn_in(window, async move |this, cx| {
306            let workspaces = this.update(cx, |multi_workspace, _cx| {
307                multi_workspace.workspaces().to_vec()
308            })?;
309
310            for workspace in workspaces {
311                let should_continue = workspace
312                    .update_in(cx, |workspace, window, cx| {
313                        workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
314                    })?
315                    .await?;
316                if !should_continue {
317                    return anyhow::Ok(());
318                }
319            }
320
321            cx.update(|window, _cx| {
322                window.remove_window();
323            })?;
324
325            anyhow::Ok(())
326        })
327        .detach_and_log_err(cx);
328    }
329
330    fn subscribe_to_workspace(workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
331        cx.subscribe(workspace, |this, workspace, event, cx| {
332            if let WorkspaceEvent::Activate = event {
333                this.activate(workspace, cx);
334            }
335        })
336        .detach();
337    }
338
339    pub fn workspace(&self) -> &Entity<Workspace> {
340        &self.workspaces[self.active_workspace_index]
341    }
342
343    pub fn workspaces(&self) -> &[Entity<Workspace>] {
344        &self.workspaces
345    }
346
347    pub fn active_workspace_index(&self) -> usize {
348        self.active_workspace_index
349    }
350
351    pub fn activate(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
352        if !self.multi_workspace_enabled(cx) {
353            self.workspaces[0] = workspace;
354            self.active_workspace_index = 0;
355            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
356            cx.notify();
357            return;
358        }
359
360        let old_index = self.active_workspace_index;
361        let new_index = self.set_active_workspace(workspace, cx);
362        if old_index != new_index {
363            self.serialize(cx);
364        }
365    }
366
367    fn set_active_workspace(
368        &mut self,
369        workspace: Entity<Workspace>,
370        cx: &mut Context<Self>,
371    ) -> usize {
372        let index = self.add_workspace(workspace, cx);
373        let changed = self.active_workspace_index != index;
374        self.active_workspace_index = index;
375        if changed {
376            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
377        }
378        cx.notify();
379        index
380    }
381
382    /// Adds a workspace to this window without changing which workspace is active.
383    /// Returns the index of the workspace (existing or newly inserted).
384    pub fn add_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
385        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
386            index
387        } else {
388            if self.sidebar_open {
389                let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
390                let has_notifications = self.sidebar_has_notifications(cx);
391                let show_toggle = self.multi_workspace_enabled(cx);
392                workspace.update(cx, |workspace, cx| {
393                    workspace.set_workspace_sidebar_open(true, has_notifications, show_toggle, cx);
394                    workspace.set_sidebar_focus_handle(sidebar_focus_handle);
395                });
396            }
397            Self::subscribe_to_workspace(&workspace, cx);
398            self.workspaces.push(workspace.clone());
399            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
400            cx.notify();
401            self.workspaces.len() - 1
402        }
403    }
404
405    pub fn activate_index(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
406        debug_assert!(
407            index < self.workspaces.len(),
408            "workspace index out of bounds"
409        );
410        let changed = self.active_workspace_index != index;
411        self.active_workspace_index = index;
412        self.serialize(cx);
413        self.focus_active_workspace(window, cx);
414        if changed {
415            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
416        }
417        cx.notify();
418    }
419
420    fn serialize(&mut self, cx: &mut App) {
421        let window_id = self.window_id;
422        let state = crate::persistence::model::MultiWorkspaceState {
423            active_workspace_id: self.workspace().read(cx).database_id(),
424            sidebar_open: self.sidebar_open,
425        };
426        let kvp = db::kvp::KeyValueStore::global(cx);
427        self._serialize_task = Some(cx.background_spawn(async move {
428            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
429        }));
430    }
431
432    /// Returns the in-flight serialization task (if any) so the caller can
433    /// await it. Used by the quit handler to ensure pending DB writes
434    /// complete before the process exits.
435    pub fn flush_serialization(&mut self) -> Task<()> {
436        self._serialize_task.take().unwrap_or(Task::ready(()))
437    }
438
439    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
440        let mut tasks: Vec<Task<()>> = Vec::new();
441        if let Some(task) = self._serialize_task.take() {
442            tasks.push(task);
443        }
444        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
445
446        async move {
447            futures::future::join_all(tasks).await;
448        }
449    }
450
451    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
452        // If a dock panel is zoomed, focus it instead of the center pane.
453        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
454        // which closes the zoomed dock.
455        let focus_handle = {
456            let workspace = self.workspace().read(cx);
457            let mut target = None;
458            for dock in workspace.all_docks() {
459                let dock = dock.read(cx);
460                if dock.is_open() {
461                    if let Some(panel) = dock.active_panel() {
462                        if panel.is_zoomed(window, cx) {
463                            target = Some(panel.panel_focus_handle(cx));
464                            break;
465                        }
466                    }
467                }
468            }
469            target.unwrap_or_else(|| {
470                let pane = workspace.active_pane().clone();
471                pane.read(cx).focus_handle(cx)
472            })
473        };
474        window.focus(&focus_handle, cx);
475    }
476
477    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
478        self.workspace().read(cx).panel::<T>(cx)
479    }
480
481    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
482        self.workspace().read(cx).active_modal::<V>(cx)
483    }
484
485    pub fn add_panel<T: Panel>(
486        &mut self,
487        panel: Entity<T>,
488        window: &mut Window,
489        cx: &mut Context<Self>,
490    ) {
491        self.workspace().update(cx, |workspace, cx| {
492            workspace.add_panel(panel, window, cx);
493        });
494    }
495
496    pub fn focus_panel<T: Panel>(
497        &mut self,
498        window: &mut Window,
499        cx: &mut Context<Self>,
500    ) -> Option<Entity<T>> {
501        self.workspace()
502            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
503    }
504
505    // used in a test
506    pub fn toggle_modal<V: ModalView, B>(
507        &mut self,
508        window: &mut Window,
509        cx: &mut Context<Self>,
510        build: B,
511    ) where
512        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
513    {
514        self.workspace().update(cx, |workspace, cx| {
515            workspace.toggle_modal(window, cx, build);
516        });
517    }
518
519    pub fn toggle_dock(
520        &mut self,
521        dock_side: DockPosition,
522        window: &mut Window,
523        cx: &mut Context<Self>,
524    ) {
525        self.workspace().update(cx, |workspace, cx| {
526            workspace.toggle_dock(dock_side, window, cx);
527        });
528    }
529
530    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
531        self.workspace().read(cx).active_item_as::<I>(cx)
532    }
533
534    pub fn items_of_type<'a, T: Item>(
535        &'a self,
536        cx: &'a App,
537    ) -> impl 'a + Iterator<Item = Entity<T>> {
538        self.workspace().read(cx).items_of_type::<T>(cx)
539    }
540
541    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
542        self.workspace().read(cx).database_id()
543    }
544
545    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
546        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
547            .into_iter()
548            .filter(|task| !task.is_ready())
549            .collect();
550        tasks
551    }
552
553    #[cfg(any(test, feature = "test-support"))]
554    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
555        self.workspace().update(cx, |workspace, _cx| {
556            workspace.set_random_database_id();
557        });
558    }
559
560    #[cfg(any(test, feature = "test-support"))]
561    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
562        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
563        Self::new(workspace, window, cx)
564    }
565
566    #[cfg(any(test, feature = "test-support"))]
567    pub fn test_add_workspace(
568        &mut self,
569        project: Entity<Project>,
570        window: &mut Window,
571        cx: &mut Context<Self>,
572    ) -> Entity<Workspace> {
573        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
574        self.activate(workspace.clone(), cx);
575        workspace
576    }
577
578    #[cfg(any(test, feature = "test-support"))]
579    pub fn create_test_workspace(
580        &mut self,
581        window: &mut Window,
582        cx: &mut Context<Self>,
583    ) -> Task<()> {
584        let app_state = self.workspace().read(cx).app_state().clone();
585        let project = Project::local(
586            app_state.client.clone(),
587            app_state.node_runtime.clone(),
588            app_state.user_store.clone(),
589            app_state.languages.clone(),
590            app_state.fs.clone(),
591            None,
592            project::LocalProjectFlags::default(),
593            cx,
594        );
595        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
596        self.set_active_workspace(new_workspace.clone(), cx);
597        self.focus_active_workspace(window, cx);
598
599        let weak_workspace = new_workspace.downgrade();
600        let db = crate::persistence::WorkspaceDb::global(cx);
601        cx.spawn_in(window, async move |this, cx| {
602            let workspace_id = db.next_id().await.unwrap();
603            let workspace = weak_workspace.upgrade().unwrap();
604            let task: Task<()> = this
605                .update_in(cx, |this, window, cx| {
606                    let session_id = workspace.read(cx).session_id();
607                    let window_id = window.window_handle().window_id().as_u64();
608                    workspace.update(cx, |workspace, _cx| {
609                        workspace.set_database_id(workspace_id);
610                    });
611                    this.serialize(cx);
612                    let db = db.clone();
613                    cx.background_spawn(async move {
614                        db.set_session_binding(workspace_id, session_id, Some(window_id))
615                            .await
616                            .log_err();
617                    })
618                })
619                .unwrap();
620            task.await
621        })
622    }
623
624    pub fn remove_workspace(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
625        if self.workspaces.len() <= 1 || index >= self.workspaces.len() {
626            return;
627        }
628
629        let removed_workspace = self.workspaces.remove(index);
630
631        if self.active_workspace_index >= self.workspaces.len() {
632            self.active_workspace_index = self.workspaces.len() - 1;
633        } else if self.active_workspace_index > index {
634            self.active_workspace_index -= 1;
635        }
636
637        if let Some(workspace_id) = removed_workspace.read(cx).database_id() {
638            let db = crate::persistence::WorkspaceDb::global(cx);
639            self.pending_removal_tasks.retain(|task| !task.is_ready());
640            self.pending_removal_tasks
641                .push(cx.background_spawn(async move {
642                    // Clear the session binding instead of deleting the row so
643                    // the workspace still appears in the recent-projects list.
644                    db.set_session_binding(workspace_id, None, None)
645                        .await
646                        .log_err();
647                }));
648        }
649
650        self.serialize(cx);
651        self.focus_active_workspace(window, cx);
652        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
653            removed_workspace.entity_id(),
654        ));
655        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
656        cx.notify();
657    }
658
659    pub fn open_project(
660        &mut self,
661        paths: Vec<PathBuf>,
662        window: &mut Window,
663        cx: &mut Context<Self>,
664    ) -> Task<Result<Entity<Workspace>>> {
665        let workspace = self.workspace().clone();
666
667        if self.multi_workspace_enabled(cx) {
668            workspace.update(cx, |workspace, cx| {
669                workspace.open_workspace_for_paths(true, paths, window, cx)
670            })
671        } else {
672            cx.spawn_in(window, async move |_this, cx| {
673                let should_continue = workspace
674                    .update_in(cx, |workspace, window, cx| {
675                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
676                    })?
677                    .await?;
678                if should_continue {
679                    workspace
680                        .update_in(cx, |workspace, window, cx| {
681                            workspace.open_workspace_for_paths(true, paths, window, cx)
682                        })?
683                        .await
684                } else {
685                    Ok(workspace)
686                }
687            })
688        }
689    }
690}
691
692impl Render for MultiWorkspace {
693    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
694        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
695
696        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
697            self.sidebar.as_ref().map(|sidebar_handle| {
698                let weak = cx.weak_entity();
699
700                let sidebar_width = sidebar_handle.width(cx);
701                let resize_handle = deferred(
702                    div()
703                        .id("sidebar-resize-handle")
704                        .absolute()
705                        .right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
706                        .top(px(0.))
707                        .h_full()
708                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
709                        .cursor_col_resize()
710                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
711                            cx.stop_propagation();
712                            cx.new(|_| dragged.clone())
713                        })
714                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
715                            cx.stop_propagation();
716                        })
717                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
718                            if event.click_count == 2 {
719                                weak.update(cx, |this, cx| {
720                                    if let Some(sidebar) = this.sidebar.as_mut() {
721                                        sidebar.set_width(None, cx);
722                                    }
723                                })
724                                .ok();
725                                cx.stop_propagation();
726                            }
727                        })
728                        .occlude(),
729                );
730
731                div()
732                    .id("sidebar-container")
733                    .relative()
734                    .h_full()
735                    .w(sidebar_width)
736                    .flex_shrink_0()
737                    .child(sidebar_handle.to_any())
738                    .child(resize_handle)
739                    .into_any_element()
740            })
741        } else {
742            None
743        };
744
745        let ui_font = theme::setup_ui_font(window, cx);
746        let text_color = cx.theme().colors().text;
747
748        let workspace = self.workspace().clone();
749        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
750        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
751
752        client_side_decorations(
753            root.key_context(workspace_key_context)
754                .relative()
755                .size_full()
756                .font(ui_font)
757                .text_color(text_color)
758                .on_action(cx.listener(Self::close_window))
759                .when(self.multi_workspace_enabled(cx), |this| {
760                    this.on_action(cx.listener(
761                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
762                            this.toggle_sidebar(window, cx);
763                        },
764                    ))
765                    .on_action(cx.listener(
766                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
767                            this.focus_sidebar(window, cx);
768                        },
769                    ))
770                })
771                .when(
772                    self.sidebar_open() && self.multi_workspace_enabled(cx),
773                    |this| {
774                        this.on_drag_move(cx.listener(
775                            |this: &mut Self, e: &DragMoveEvent<DraggedSidebar>, _window, cx| {
776                                if let Some(sidebar) = &this.sidebar {
777                                    let new_width = e.event.position.x;
778                                    sidebar.set_width(Some(new_width), cx);
779                                }
780                            },
781                        ))
782                        .children(sidebar)
783                    },
784                )
785                .child(
786                    div()
787                        .flex()
788                        .flex_1()
789                        .size_full()
790                        .overflow_hidden()
791                        .child(self.workspace().clone()),
792                )
793                .child(self.workspace().read(cx).modal_layer.clone()),
794            window,
795            cx,
796            Tiling {
797                left: multi_workspace_enabled && self.sidebar_open(),
798                ..Tiling::default()
799            },
800        )
801    }
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807    use fs::FakeFs;
808    use gpui::TestAppContext;
809    use settings::SettingsStore;
810
811    fn init_test(cx: &mut TestAppContext) {
812        cx.update(|cx| {
813            let settings_store = SettingsStore::test(cx);
814            cx.set_global(settings_store);
815            theme::init(theme::LoadThemes::JustBase, cx);
816            DisableAiSettings::register(cx);
817            cx.update_flags(false, vec!["agent-v2".into()]);
818        });
819    }
820
821    #[gpui::test]
822    async fn test_sidebar_disabled_when_disable_ai_is_enabled(cx: &mut TestAppContext) {
823        init_test(cx);
824        let fs = FakeFs::new(cx.executor());
825        let project = Project::test(fs, [], cx).await;
826
827        let (multi_workspace, cx) =
828            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
829
830        multi_workspace.read_with(cx, |mw, cx| {
831            assert!(mw.multi_workspace_enabled(cx));
832        });
833
834        multi_workspace.update_in(cx, |mw, _window, cx| {
835            mw.open_sidebar(cx);
836            assert!(mw.sidebar_open());
837        });
838
839        cx.update(|_window, cx| {
840            DisableAiSettings::override_global(DisableAiSettings { disable_ai: true }, cx);
841        });
842        cx.run_until_parked();
843
844        multi_workspace.read_with(cx, |mw, cx| {
845            assert!(
846                !mw.sidebar_open(),
847                "Sidebar should be closed when disable_ai is true"
848            );
849            assert!(
850                !mw.multi_workspace_enabled(cx),
851                "Multi-workspace should be disabled when disable_ai is true"
852            );
853        });
854
855        multi_workspace.update_in(cx, |mw, window, cx| {
856            mw.toggle_sidebar(window, cx);
857        });
858        multi_workspace.read_with(cx, |mw, _cx| {
859            assert!(
860                !mw.sidebar_open(),
861                "Sidebar should remain closed when toggled with disable_ai true"
862            );
863        });
864
865        cx.update(|_window, cx| {
866            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
867        });
868        cx.run_until_parked();
869
870        multi_workspace.read_with(cx, |mw, cx| {
871            assert!(
872                mw.multi_workspace_enabled(cx),
873                "Multi-workspace should be enabled after re-enabling AI"
874            );
875            assert!(
876                !mw.sidebar_open(),
877                "Sidebar should still be closed after re-enabling AI (not auto-opened)"
878            );
879        });
880
881        multi_workspace.update_in(cx, |mw, window, cx| {
882            mw.toggle_sidebar(window, cx);
883        });
884        multi_workspace.read_with(cx, |mw, _cx| {
885            assert!(
886                mw.sidebar_open(),
887                "Sidebar should open when toggled after re-enabling AI"
888            );
889        });
890    }
891}