[Background Fetch] Reject call to updateUI if event is inactive.

Spec:
https://wicg.github.io/background-fetch/#background-fetch-update-ui-event-update-ui

Bug: 901909
Change-Id: Ia319cd03e41e65c5a6a1f5e61cde6f4ae7705a32
Reviewed-on: https://chromium-review.googlesource.com/c/1320330
Commit-Queue: Rayan Kanso <rayankans@chromium.org>
Reviewed-by: Peter Beverloo <peter@chromium.org>
Reviewed-by: Matt Falkenhagen <falken@chromium.org>
Reviewed-by: Hiroki Nakagawa <nhiroki@chromium.org>
Cr-Commit-Position: refs/heads/master@{#606118}
diff --git a/background-fetch/service_workers/sw-update-ui.js b/background-fetch/service_workers/sw-update-ui.js
index 5dec087..3848dc4 100644
--- a/background-fetch/service_workers/sw-update-ui.js
+++ b/background-fetch/service_workers/sw-update-ui.js
@@ -1,3 +1,4 @@
+importScripts('/resources/testharness.js');
 importScripts('sw-helpers.js');
 
 async function updateUI(event) {
@@ -13,10 +14,20 @@
 
   return Promise.all(updateParams.map(param => event.updateUI(param)))
            .then(() => 'update success')
-           .catch(e => e.message);
+           .catch(e => e.name);
 }
 
 self.addEventListener('backgroundfetchsuccess', event => {
+  if (event.registration.id === 'update-inactive') {
+    // Post an async task before calling updateUI from the inactive event.
+    // Any async behaviour outside `waitUntil` should mark the event as
+    // inactive, and subsequent calls to `updateUI` should fail.
+    new Promise(r => step_timeout(r, 0))
+        .then(() => event.updateUI({ title: 'New title' }))
+        .catch(e => sendMessageToDocument({ update: e.name }));
+    return;
+  }
+
   event.waitUntil(updateUI(event)
-      .then(update => sendMessageToDocument({ type: event.type, update })))
+      .then(update => sendMessageToDocument({ update })));
 });
diff --git a/background-fetch/update-ui.https.window.js b/background-fetch/update-ui.https.window.js
index aed0bb8..90d3c2e 100644
--- a/background-fetch/update-ui.https.window.js
+++ b/background-fetch/update-ui.https.window.js
@@ -27,6 +27,17 @@
   assert_equals(registration.id, registrationId);
 
   const message = await getMessageFromServiceWorker();
-  assert_equals(message.update, 'updateUI may only be called once.');
+  assert_equals(message.update, 'InvalidStateError');
 
 }, 'Background Fetch updateUI called twice fails', swName);
+
+backgroundFetchTest(async (test, backgroundFetch) => {
+  const registrationId = 'update-inactive';
+  const registration =
+      await backgroundFetch.fetch(registrationId, 'resources/feature-name.txt');
+  assert_equals(registration.id, registrationId);
+
+  const message = await getMessageFromServiceWorker();
+  assert_equals(message.update, 'InvalidStateError');
+
+}, 'Background Fetch updateUI fails when event is not active', swName);