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