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        let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
245        for workspace in &self.workspaces {
246            workspace.update(cx, |workspace, cx| {
247                workspace.set_workspace_sidebar_open(true, cx);
248                workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
249            });
250        }
251        self.serialize(cx);
252        cx.notify();
253    }
254
255    fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
256        self.sidebar_open = false;
257        for workspace in &self.workspaces {
258            workspace.update(cx, |workspace, cx| {
259                workspace.set_workspace_sidebar_open(false, cx);
260                workspace.set_sidebar_focus_handle(None);
261            });
262        }
263        let pane = self.workspace().read(cx).active_pane().clone();
264        let pane_focus = pane.read(cx).focus_handle(cx);
265        window.focus(&pane_focus, cx);
266        self.serialize(cx);
267        cx.notify();
268    }
269
270    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
271        cx.spawn_in(window, async move |this, cx| {
272            let workspaces = this.update(cx, |multi_workspace, _cx| {
273                multi_workspace.workspaces().to_vec()
274            })?;
275
276            for workspace in workspaces {
277                let should_continue = workspace
278                    .update_in(cx, |workspace, window, cx| {
279                        workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
280                    })?
281                    .await?;
282                if !should_continue {
283                    return anyhow::Ok(());
284                }
285            }
286
287            cx.update(|window, _cx| {
288                window.remove_window();
289            })?;
290
291            anyhow::Ok(())
292        })
293        .detach_and_log_err(cx);
294    }
295
296    fn subscribe_to_workspace(workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
297        cx.subscribe(workspace, |this, workspace, event, cx| {
298            if let WorkspaceEvent::Activate = event {
299                this.activate(workspace, cx);
300            }
301        })
302        .detach();
303    }
304
305    pub fn workspace(&self) -> &Entity<Workspace> {
306        &self.workspaces[self.active_workspace_index]
307    }
308
309    pub fn workspaces(&self) -> &[Entity<Workspace>] {
310        &self.workspaces
311    }
312
313    pub fn active_workspace_index(&self) -> usize {
314        self.active_workspace_index
315    }
316
317    pub fn activate(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
318        if !self.multi_workspace_enabled(cx) {
319            self.workspaces[0] = workspace;
320            self.active_workspace_index = 0;
321            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
322            cx.notify();
323            return;
324        }
325
326        let old_index = self.active_workspace_index;
327        let new_index = self.set_active_workspace(workspace, cx);
328        if old_index != new_index {
329            self.serialize(cx);
330        }
331    }
332
333    fn set_active_workspace(
334        &mut self,
335        workspace: Entity<Workspace>,
336        cx: &mut Context<Self>,
337    ) -> usize {
338        let index = self.add_workspace(workspace, cx);
339        let changed = self.active_workspace_index != index;
340        self.active_workspace_index = index;
341        if changed {
342            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
343        }
344        cx.notify();
345        index
346    }
347
348    /// Adds a workspace to this window without changing which workspace is active.
349    /// Returns the index of the workspace (existing or newly inserted).
350    pub fn add_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
351        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
352            index
353        } else {
354            if self.sidebar_open {
355                let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
356                workspace.update(cx, |workspace, cx| {
357                    workspace.set_workspace_sidebar_open(true, cx);
358                    workspace.set_sidebar_focus_handle(sidebar_focus_handle);
359                });
360            }
361            Self::subscribe_to_workspace(&workspace, cx);
362            self.workspaces.push(workspace.clone());
363            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
364            cx.notify();
365            self.workspaces.len() - 1
366        }
367    }
368
369    pub fn activate_index(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
370        debug_assert!(
371            index < self.workspaces.len(),
372            "workspace index out of bounds"
373        );
374        let changed = self.active_workspace_index != index;
375        self.active_workspace_index = index;
376        self.serialize(cx);
377        self.focus_active_workspace(window, cx);
378        if changed {
379            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
380        }
381        cx.notify();
382    }
383
384    fn serialize(&mut self, cx: &mut App) {
385        let window_id = self.window_id;
386        let state = crate::persistence::model::MultiWorkspaceState {
387            active_workspace_id: self.workspace().read(cx).database_id(),
388            sidebar_open: self.sidebar_open,
389        };
390        let kvp = db::kvp::KeyValueStore::global(cx);
391        self._serialize_task = Some(cx.background_spawn(async move {
392            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
393        }));
394    }
395
396    /// Returns the in-flight serialization task (if any) so the caller can
397    /// await it. Used by the quit handler to ensure pending DB writes
398    /// complete before the process exits.
399    pub fn flush_serialization(&mut self) -> Task<()> {
400        self._serialize_task.take().unwrap_or(Task::ready(()))
401    }
402
403    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
404        let mut tasks: Vec<Task<()>> = Vec::new();
405        if let Some(task) = self._serialize_task.take() {
406            tasks.push(task);
407        }
408        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
409
410        async move {
411            futures::future::join_all(tasks).await;
412        }
413    }
414
415    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
416        // If a dock panel is zoomed, focus it instead of the center pane.
417        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
418        // which closes the zoomed dock.
419        let focus_handle = {
420            let workspace = self.workspace().read(cx);
421            let mut target = None;
422            for dock in workspace.all_docks() {
423                let dock = dock.read(cx);
424                if dock.is_open() {
425                    if let Some(panel) = dock.active_panel() {
426                        if panel.is_zoomed(window, cx) {
427                            target = Some(panel.panel_focus_handle(cx));
428                            break;
429                        }
430                    }
431                }
432            }
433            target.unwrap_or_else(|| {
434                let pane = workspace.active_pane().clone();
435                pane.read(cx).focus_handle(cx)
436            })
437        };
438        window.focus(&focus_handle, cx);
439    }
440
441    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
442        self.workspace().read(cx).panel::<T>(cx)
443    }
444
445    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
446        self.workspace().read(cx).active_modal::<V>(cx)
447    }
448
449    pub fn add_panel<T: Panel>(
450        &mut self,
451        panel: Entity<T>,
452        window: &mut Window,
453        cx: &mut Context<Self>,
454    ) {
455        self.workspace().update(cx, |workspace, cx| {
456            workspace.add_panel(panel, window, cx);
457        });
458    }
459
460    pub fn focus_panel<T: Panel>(
461        &mut self,
462        window: &mut Window,
463        cx: &mut Context<Self>,
464    ) -> Option<Entity<T>> {
465        self.workspace()
466            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
467    }
468
469    // used in a test
470    pub fn toggle_modal<V: ModalView, B>(
471        &mut self,
472        window: &mut Window,
473        cx: &mut Context<Self>,
474        build: B,
475    ) where
476        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
477    {
478        self.workspace().update(cx, |workspace, cx| {
479            workspace.toggle_modal(window, cx, build);
480        });
481    }
482
483    pub fn toggle_dock(
484        &mut self,
485        dock_side: DockPosition,
486        window: &mut Window,
487        cx: &mut Context<Self>,
488    ) {
489        self.workspace().update(cx, |workspace, cx| {
490            workspace.toggle_dock(dock_side, window, cx);
491        });
492    }
493
494    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
495        self.workspace().read(cx).active_item_as::<I>(cx)
496    }
497
498    pub fn items_of_type<'a, T: Item>(
499        &'a self,
500        cx: &'a App,
501    ) -> impl 'a + Iterator<Item = Entity<T>> {
502        self.workspace().read(cx).items_of_type::<T>(cx)
503    }
504
505    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
506        self.workspace().read(cx).database_id()
507    }
508
509    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
510        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
511            .into_iter()
512            .filter(|task| !task.is_ready())
513            .collect();
514        tasks
515    }
516
517    #[cfg(any(test, feature = "test-support"))]
518    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
519        self.workspace().update(cx, |workspace, _cx| {
520            workspace.set_random_database_id();
521        });
522    }
523
524    #[cfg(any(test, feature = "test-support"))]
525    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
526        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
527        Self::new(workspace, window, cx)
528    }
529
530    #[cfg(any(test, feature = "test-support"))]
531    pub fn test_add_workspace(
532        &mut self,
533        project: Entity<Project>,
534        window: &mut Window,
535        cx: &mut Context<Self>,
536    ) -> Entity<Workspace> {
537        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
538        self.activate(workspace.clone(), cx);
539        workspace
540    }
541
542    #[cfg(any(test, feature = "test-support"))]
543    pub fn create_test_workspace(
544        &mut self,
545        window: &mut Window,
546        cx: &mut Context<Self>,
547    ) -> Task<()> {
548        let app_state = self.workspace().read(cx).app_state().clone();
549        let project = Project::local(
550            app_state.client.clone(),
551            app_state.node_runtime.clone(),
552            app_state.user_store.clone(),
553            app_state.languages.clone(),
554            app_state.fs.clone(),
555            None,
556            project::LocalProjectFlags::default(),
557            cx,
558        );
559        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
560        self.set_active_workspace(new_workspace.clone(), cx);
561        self.focus_active_workspace(window, cx);
562
563        let weak_workspace = new_workspace.downgrade();
564        let db = crate::persistence::WorkspaceDb::global(cx);
565        cx.spawn_in(window, async move |this, cx| {
566            let workspace_id = db.next_id().await.unwrap();
567            let workspace = weak_workspace.upgrade().unwrap();
568            let task: Task<()> = this
569                .update_in(cx, |this, window, cx| {
570                    let session_id = workspace.read(cx).session_id();
571                    let window_id = window.window_handle().window_id().as_u64();
572                    workspace.update(cx, |workspace, _cx| {
573                        workspace.set_database_id(workspace_id);
574                    });
575                    this.serialize(cx);
576                    let db = db.clone();
577                    cx.background_spawn(async move {
578                        db.set_session_binding(workspace_id, session_id, Some(window_id))
579                            .await
580                            .log_err();
581                    })
582                })
583                .unwrap();
584            task.await
585        })
586    }
587
588    pub fn remove_workspace(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
589        if self.workspaces.len() <= 1 || index >= self.workspaces.len() {
590            return;
591        }
592
593        let removed_workspace = self.workspaces.remove(index);
594
595        if self.active_workspace_index >= self.workspaces.len() {
596            self.active_workspace_index = self.workspaces.len() - 1;
597        } else if self.active_workspace_index > index {
598            self.active_workspace_index -= 1;
599        }
600
601        if let Some(workspace_id) = removed_workspace.read(cx).database_id() {
602            let db = crate::persistence::WorkspaceDb::global(cx);
603            self.pending_removal_tasks.retain(|task| !task.is_ready());
604            self.pending_removal_tasks
605                .push(cx.background_spawn(async move {
606                    // Clear the session binding instead of deleting the row so
607                    // the workspace still appears in the recent-projects list.
608                    db.set_session_binding(workspace_id, None, None)
609                        .await
610                        .log_err();
611                }));
612        }
613
614        self.serialize(cx);
615        self.focus_active_workspace(window, cx);
616        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
617            removed_workspace.entity_id(),
618        ));
619        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
620        cx.notify();
621    }
622
623    pub fn open_project(
624        &mut self,
625        paths: Vec<PathBuf>,
626        window: &mut Window,
627        cx: &mut Context<Self>,
628    ) -> Task<Result<Entity<Workspace>>> {
629        let workspace = self.workspace().clone();
630
631        if self.multi_workspace_enabled(cx) {
632            workspace.update(cx, |workspace, cx| {
633                workspace.open_workspace_for_paths(true, paths, window, cx)
634            })
635        } else {
636            cx.spawn_in(window, async move |_this, cx| {
637                let should_continue = workspace
638                    .update_in(cx, |workspace, window, cx| {
639                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
640                    })?
641                    .await?;
642                if should_continue {
643                    workspace
644                        .update_in(cx, |workspace, window, cx| {
645                            workspace.open_workspace_for_paths(true, paths, window, cx)
646                        })?
647                        .await
648                } else {
649                    Ok(workspace)
650                }
651            })
652        }
653    }
654}
655
656impl Render for MultiWorkspace {
657    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
658        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
659
660        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
661            self.sidebar.as_ref().map(|sidebar_handle| {
662                let weak = cx.weak_entity();
663
664                let sidebar_width = sidebar_handle.width(cx);
665                let resize_handle = deferred(
666                    div()
667                        .id("sidebar-resize-handle")
668                        .absolute()
669                        .right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
670                        .top(px(0.))
671                        .h_full()
672                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
673                        .cursor_col_resize()
674                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
675                            cx.stop_propagation();
676                            cx.new(|_| dragged.clone())
677                        })
678                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
679                            cx.stop_propagation();
680                        })
681                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
682                            if event.click_count == 2 {
683                                weak.update(cx, |this, cx| {
684                                    if let Some(sidebar) = this.sidebar.as_mut() {
685                                        sidebar.set_width(None, cx);
686                                    }
687                                })
688                                .ok();
689                                cx.stop_propagation();
690                            }
691                        })
692                        .occlude(),
693                );
694
695                div()
696                    .id("sidebar-container")
697                    .relative()
698                    .h_full()
699                    .w(sidebar_width)
700                    .flex_shrink_0()
701                    .child(sidebar_handle.to_any())
702                    .child(resize_handle)
703                    .into_any_element()
704            })
705        } else {
706            None
707        };
708
709        let ui_font = theme::setup_ui_font(window, cx);
710        let text_color = cx.theme().colors().text;
711
712        let workspace = self.workspace().clone();
713        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
714        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
715
716        client_side_decorations(
717            root.key_context(workspace_key_context)
718                .relative()
719                .size_full()
720                .font(ui_font)
721                .text_color(text_color)
722                .on_action(cx.listener(Self::close_window))
723                .when(self.multi_workspace_enabled(cx), |this| {
724                    this.on_action(cx.listener(
725                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
726                            this.toggle_sidebar(window, cx);
727                        },
728                    ))
729                    .on_action(cx.listener(
730                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
731                            this.focus_sidebar(window, cx);
732                        },
733                    ))
734                })
735                .when(
736                    self.sidebar_open() && self.multi_workspace_enabled(cx),
737                    |this| {
738                        this.on_drag_move(cx.listener(
739                            |this: &mut Self, e: &DragMoveEvent<DraggedSidebar>, _window, cx| {
740                                if let Some(sidebar) = &this.sidebar {
741                                    let new_width = e.event.position.x;
742                                    sidebar.set_width(Some(new_width), cx);
743                                }
744                            },
745                        ))
746                        .children(sidebar)
747                    },
748                )
749                .child(
750                    div()
751                        .flex()
752                        .flex_1()
753                        .size_full()
754                        .overflow_hidden()
755                        .child(self.workspace().clone()),
756                )
757                .child(self.workspace().read(cx).modal_layer.clone()),
758            window,
759            cx,
760            Tiling {
761                left: multi_workspace_enabled && self.sidebar_open(),
762                ..Tiling::default()
763            },
764        )
765    }
766}
767
768#[cfg(test)]
769mod tests {
770    use super::*;
771    use fs::FakeFs;
772    use gpui::TestAppContext;
773    use settings::SettingsStore;
774
775    fn init_test(cx: &mut TestAppContext) {
776        cx.update(|cx| {
777            let settings_store = SettingsStore::test(cx);
778            cx.set_global(settings_store);
779            theme::init(theme::LoadThemes::JustBase, cx);
780            DisableAiSettings::register(cx);
781            cx.update_flags(false, vec!["agent-v2".into()]);
782        });
783    }
784
785    #[gpui::test]
786    async fn test_sidebar_disabled_when_disable_ai_is_enabled(cx: &mut TestAppContext) {
787        init_test(cx);
788        let fs = FakeFs::new(cx.executor());
789        let project = Project::test(fs, [], cx).await;
790
791        let (multi_workspace, cx) =
792            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
793
794        multi_workspace.read_with(cx, |mw, cx| {
795            assert!(mw.multi_workspace_enabled(cx));
796        });
797
798        multi_workspace.update_in(cx, |mw, _window, cx| {
799            mw.open_sidebar(cx);
800            assert!(mw.sidebar_open());
801        });
802
803        cx.update(|_window, cx| {
804            DisableAiSettings::override_global(DisableAiSettings { disable_ai: true }, cx);
805        });
806        cx.run_until_parked();
807
808        multi_workspace.read_with(cx, |mw, cx| {
809            assert!(
810                !mw.sidebar_open(),
811                "Sidebar should be closed when disable_ai is true"
812            );
813            assert!(
814                !mw.multi_workspace_enabled(cx),
815                "Multi-workspace should be disabled when disable_ai is true"
816            );
817        });
818
819        multi_workspace.update_in(cx, |mw, window, cx| {
820            mw.toggle_sidebar(window, cx);
821        });
822        multi_workspace.read_with(cx, |mw, _cx| {
823            assert!(
824                !mw.sidebar_open(),
825                "Sidebar should remain closed when toggled with disable_ai true"
826            );
827        });
828
829        cx.update(|_window, cx| {
830            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
831        });
832        cx.run_until_parked();
833
834        multi_workspace.read_with(cx, |mw, cx| {
835            assert!(
836                mw.multi_workspace_enabled(cx),
837                "Multi-workspace should be enabled after re-enabling AI"
838            );
839            assert!(
840                !mw.sidebar_open(),
841                "Sidebar should still be closed after re-enabling AI (not auto-opened)"
842            );
843        });
844
845        multi_workspace.update_in(cx, |mw, window, cx| {
846            mw.toggle_sidebar(window, cx);
847        });
848        multi_workspace.read_with(cx, |mw, _cx| {
849            assert!(
850                mw.sidebar_open(),
851                "Sidebar should open when toggled after re-enabling AI"
852            );
853        });
854    }
855}