Flush account refresh debouncer on window focus

While refreshing authentication, listen to the window focus event rather
than visibilitychange to flush the check debouncer. This results in
a quicker response from the UI after the refresh popup closes.

Change-Id: I87d424e6cb8c42f8072110a7683fd09cd24431d9
diff --git a/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager.js b/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager.js
index bd890b8..870e7ea 100644
--- a/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager.js
+++ b/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager.js
@@ -154,17 +154,12 @@
       // undefined).
       if (document.hidden !== false) { return; }
 
-      // If we're currently in a credential refresh, flush the debouncer so that
-      // it can be checked immediately.
-      if (this._refreshingCredentials) {
-        this.flushDebouncer('checkLoggedIn');
-        return;
-      }
-
-      // If the credentials are old, request them to confirm their validity or
-      // (display an auth toast if it fails).
+      // If not currently refreshing credentials and the credentials are old,
+      // request them to confirm their validity or (display an auth toast if it
+      // fails).
       var timeSinceLastCheck = Date.now() - this._lastCredentialCheck;
-      if (this.knownAccountId !== undefined &&
+      if (!this._refreshingCredentials &&
+          this.knownAccountId !== undefined &&
           timeSinceLastCheck > STALE_CREDENTIAL_THRESHOLD_MS) {
         this._lastCredentialCheck = Date.now();
         this.$.restAPI.checkCredentials();
@@ -212,13 +207,19 @@
         'top=' + top,
       ];
       window.open('/login/%3FcloseAfterLogin', '_blank', options.join(','));
+      this.listen(window, 'focus', '_handleWindowFocus');
     },
 
     _handleCredentialRefreshed: function() {
+      this.unlisten(window, 'focus', '_handleWindowFocus');
       this._refreshingCredentials = false;
       this.unlisten(this._alertElement, 'action', '_createLoginPopup');
       this._hideAlert();
       this._showAlert('Credentials refreshed.');
     },
+
+    _handleWindowFocus: function() {
+      this.flushDebouncer('checkLoggedIn');
+    },
   });
 })();
diff --git a/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html b/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
index da15c08..9be32af 100644
--- a/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
+++ b/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
@@ -130,6 +130,7 @@
 
         var hideToastSpy = sandbox.spy(toast, 'hide');
 
+        element._handleWindowFocus();
         assert.isTrue(refreshStub.called);
         element.flushDebouncer('checkLoggedIn');
         flush(function() {