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