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