ash: Fix crash when creating a new desk while exiting overview

DeskBarViewBase observes desk creations and does the necessary work to
update the desk bar. If the desk bar is in its "zero state" (the
collapsed desk bar state in overview mode), it expands the desk bar to
show mini views.

When exiting overview, there's a short animation that happens with the
desk bar. The events are as follows:

  1. Overview exit starts, the overview grid is immediately destroyed.
  2. Animation progresses.
  3. When the animation finishes, the desk bar is destroyed and it
     automatically unregisters itself as a desk controller observer.

If a new desk is created during #2, the desk bar would incorrectly
determine that we are still in overview mode and downstream code would
assume that the overview grid still exists. This CL fixes that check so
that we don't think overview mode is still active.

BUG=b:365546169

Change-Id: Ie8e39cbedaeeef3dbd89090000ce1210f639278b
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5846865
Commit-Queue: Daniel Andersson <dandersson@chromium.org>
Reviewed-by: Yongshun Liu <yongshun@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1353411}
diff --git a/ash/wm/desks/desk_bar_view_base.cc b/ash/wm/desks/desk_bar_view_base.cc
index b0f30b5..d05d574b 100644
--- a/ash/wm/desks/desk_bar_view_base.cc
+++ b/ash/wm/desks/desk_bar_view_base.cc
@@ -1513,7 +1513,10 @@
 void DeskBarViewBase::OnDeskAdded(const Desk* desk, bool from_undo) {
   DeskNameView::CommitChanges(GetWidget());
 
+  // If a desk is added while overview mode is exiting, then the overview grid
+  // will have already been destroyed and we must not try to expand the bar.
   const bool is_expanding_bar_view =
+      overview_grid() &&
       new_desk_button_->state() == DeskIconButton::State::kZero;
   UpdateNewMiniViews(/*initializing_bar_view=*/false, is_expanding_bar_view);
   MaybeUpdateDeskActionButtonTooltips();
diff --git a/ash/wm/desks/desks_unittests.cc b/ash/wm/desks/desks_unittests.cc
index f2b1a4a..ca87df3 100644
--- a/ash/wm/desks/desks_unittests.cc
+++ b/ash/wm/desks/desks_unittests.cc
@@ -2621,6 +2621,22 @@
   EXPECT_EQ(desk_2, controller->active_desk());
 }
 
+// Tests that creating a new desk while overview is exiting doesn't cause a
+// crash. Regression test for http://b/365546169
+TEST_P(DesksTest, AddDeskWhileExitingOverview) {
+  UpdateDisplay("800x600");
+
+  EnterOverview();
+  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
+
+  ui::ScopedAnimationDurationScaleMode animation_scale(
+      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);
+
+  // Exit overview (with an animation) and immediately create a second desk.
+  ExitOverview();
+  NewDesk();
+}
+
 class DesksWithMultiDisplayOverview : public AshTestBase {
  public:
   DesksWithMultiDisplayOverview() = default;