Skip to content

Conversation

@SydneyBao
Copy link
Contributor

Create a service worker that removes the old cached service worker.

Related issue: 156910

Pre-launch Checklist

  • I read the [Contributor Guide] and followed the process outlined there for submitting PRs.
  • I read the [Tree Hygiene] wiki page, which explains my responsibilities.
  • I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement].
  • I signed the [CLA].
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///).
  • I added new tests to check the change I am making, or this PR is [test-exempt].
  • I followed the [breaking change policy] and added [Data Driven Fixes] where supported.
  • All existing and new tests are passing.

@github-actions github-actions bot added tool Affects the "flutter" command-line tool. See also t: labels. engine flutter/engine related. See also e: labels. platform-web Web applications specifically labels Sep 5, 2025
@SydneyBao SydneyBao mentioned this pull request Sep 5, 2025
9 tasks
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request removes the service worker functionality from Flutter's web builds. The existing service worker, which handled caching, is replaced by a new, simple "cleanup" worker. This new worker's only purpose is to delete old caches and unregister itself, ensuring a clean state for users with a previously cached application. The changes span flutter_tools to generate this new worker, flutter.js to remove the service worker registration logic, and the test suite to verify the cleanup process.

My review focuses on the new test implementation, where I've found a critical issue in the test-specific service worker content that would cause the test to fail, and a medium-severity issue regarding redundant file operations in the test setup. The rest of the changes appear correct and effectively achieve the goal of removing the service worker.

Comment on lines +40 to +85
const String cleanupWorkerContent = '''
'use strict';
const CACHE_NAME = 'flutter-app-cache';
self.addEventListener('install', () => {
self.skipWaiting();
console.log('Deprecated service worker installed. It will not be used.');
});
// remove old caches and unregister the service worker
self.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
try {
const deletePromises = OLD_CACHE_NAMES.map((key) => self.caches.delete(key));
await Promise.all(deletePromises);
} catch (e) {
console.warn('Failed to delete old service worker caches:', e);
}
Future<void> _generateEntrypoint() async {
final Directory tempDirectory = Directory.systemTemp.createTempSync(
'flutter_web_generated_entrypoint.',
);
await runCommand(_flutter, <String>[
'create',
'generated_entrypoint_test',
], workingDirectory: tempDirectory.path);
final File generatedEntrypoint = File(
path.join(tempDirectory.path, 'generated_entrypoint_test', 'web', 'index.html'),
);
final String generatedEntrypointCode = generatedEntrypoint.readAsStringSync();
final File testEntrypoint = File(
path.join(
_testAppWebDirectory,
_testTypeToIndexFile(ServiceWorkerTestType.generatedEntrypoint),
),
);
testEntrypoint.writeAsStringSync(generatedEntrypointCode);
tempDirectory.deleteSync(recursive: true);
}
try {
await self.registration.unregister();
} catch (e) {
console.warn('Failed to unregister service worker:', e);
}
Future<void> _setAppVersion(int version) async {
final File targetFile = File(_targetPath);
await targetFile.writeAsString(
(await targetFile.readAsString()).replaceFirst(
RegExp(r'CLOSE\?version=\d+'),
'CLOSE?version=$version',
),
try {
const clients = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true,
});
// Reload clients to ensure they are not using the old service worker.
clients.forEach((client) => {
if (client.url && 'navigate' in client) {
client.navigate(client.url);
}
});
} catch (e) {
console.warn('Failed to navigate service worker clients:', e);
}
})()
);
}
});
''';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The cleanupWorkerContent constant is incorrect and will cause the test to fail. It's missing the definition for OLD_CACHE_NAMES (which it references) and contains an unused CACHE_NAME constant from the old service worker. The content should match the new service worker template to accurately test the cleanup scenario.

  const String cleanupWorkerContent = '''
'use strict';

const OLD_CACHE_NAMES = ['flutter-app-manifest', 'flutter-app-cache', 'flutter-temp-cache'];

self.addEventListener('install', () => {
  self.skipWaiting();
  console.log('Deprecated service worker installed. It will not be used.');
});

// remove old caches and unregister the service worker
self.addEventListener('activate', (event) => {
  event.waitUntil(
    (async () => {
      try {
        const deletePromises = OLD_CACHE_NAMES.map((key) => self.caches.delete(key));
        await Promise.all(deletePromises);
      } catch (e) {
        console.warn('Failed to delete old service worker caches:', e);
      }

      try {
        await self.registration.unregister();
      } catch (e) {
        console.warn('Failed to unregister service worker:', e);
      }

      try {
        const clients = await self.clients.matchAll({
          type: 'window',
          includeUncontrolled: true,
        });
        // Reload clients to ensure they are not using the old service worker.
        clients.forEach((client) => {
          if (client.url && 'navigate' in client) {
            client.navigate(client.url);
          }
        });
      } catch (e) {
        console.warn('Failed to navigate service worker clients:', e);
      }
    })()
  );
});

''';

);

try {
cleanupWorkerFile.writeAsStringSync(cleanupWorkerContent);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This line writes cleanupWorkerContent to a file in the source directory. However, the flutter build web command on the next lines generates its own flutter_service_worker.js and does not use this file. This operation, along with the definition of cleanupWorkerFile (lines 33-38) and its deletion in the finally block (lines 162-164), is redundant. Consider removing these parts to simplify the test.

@ash2moon ash2moon marked this pull request as draft September 8, 2025 18:05
@ash2moon
Copy link
Contributor

ash2moon commented Sep 8, 2025

Marking as draft for now so we can investigate why the checks are not passing.
Main conversation in this PR:
#173609

@flutter-dashboard
Copy link

This pull request has been changed to a draft. The currently pending flutter-gold status will not be able to resolve until a new commit is pushed or the change is marked ready for review again.

For more guidance, visit Writing a golden file test for package:flutter.

Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing.

@mdebbar
Copy link
Contributor

mdebbar commented Oct 16, 2025

This is being worked on here: #176834

@mdebbar mdebbar closed this Oct 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

engine flutter/engine related. See also e: labels. platform-web Web applications specifically tool Affects the "flutter" command-line tool. See also t: labels.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants