Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

fix: bust stale PWA/browser caches on upgrade with versioned service worker, revalidated static assets, and no-cache locale fetches (#357)

Murtaza Nasirc6e8596de68a
diff --git a/src/app.py b/src/app.py
index 9ff875fc..211dd5a3 100644
--- a/src/app.py
+++ b/src/app.py
@@ -361,6 +361,13 @@ app = Flask(__name__,
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')
app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER', '/data/uploads')
+# Static files ship with no Cache-Control by default, which lets browsers
+# apply heuristic freshness (often days/weeks for rarely-changed files).
+# After an image upgrade that served users a mix of new templates and stale
+# JS/locale JSON — a blank UI with "Translation not found" spam (issue #357).
+# max-age=0 forces a cheap conditional revalidation (304 unless changed).
+app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
+
# SQLite concurrency settings for multi-worker job queue
if 'sqlite' in app.config['SQLALCHEMY_DATABASE_URI']:
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
@@ -631,6 +638,15 @@ def csrf_token_aware_check():
def inject_now():
return {'now': datetime.now()}
+# Expose the app version to templates so the service worker registration URL
+# (and therefore its cache namespace) changes on every release, forcing the
+# browser to install the new worker and refetch the app shell (issue #357).
+_app_version = get_version()
+
+def inject_app_version():
+ return {'app_version': _app_version}
+
@app.context_processor
def inject_group_admin_status():
"""Inject is_group_admin flag into all templates."""
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index faa3d8a9..605d4d2d 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -219,9 +219,15 @@ document.addEventListener('DOMContentLoaded', async () => {
// Register Service Worker (non-blocking)
if ('serviceWorker' in navigator) {
+ // Version the registration URL so every release installs a fresh
+ // worker with its own cache namespace; otherwise a byte-identical
+ // sw.js keeps serving the previous release's cached app shell
+ // forever (issue #357).
+ const appVersion = document.querySelector('meta[name="app-version"]')?.getAttribute('content') || '';
+ const swUrl = appVersion ? `/static/sw.js?v=${encodeURIComponent(appVersion)}` : '/static/sw.js';
// Delay registration to not block page load
setTimeout(() => {
- navigator.serviceWorker.register('/static/sw.js')
+ navigator.serviceWorker.register(swUrl)
.then(registration => {
console.log('ServiceWorker registration successful with scope:', registration.scope);
})
diff --git a/static/js/i18n.js b/static/js/i18n.js
index f7fe3ed1..6cf90e07 100644
--- a/static/js/i18n.js
+++ b/static/js/i18n.js
@@ -41,7 +41,11 @@ class I18n {
}
try {
- const response = await fetch(`/static/locales/${locale}.json`);
+ // 'no-cache' forces a conditional revalidation so a browser (or
+ // proxy) heuristic cache can never serve a previous release's
+ // locale file against newer templates — the "Translation not
+ // found" spam after upgrades (issue #357).
+ const response = await fetch(`/static/locales/${locale}.json`, { cache: 'no-cache' });
if (!response.ok) {
throw new Error(`Failed to load locale: ${locale}`);
}
diff --git a/static/sw.js b/static/sw.js
index 0a865208..d48e0124 100644
--- a/static/sw.js
+++ b/static/sw.js
@@ -1,4 +1,9 @@
-const CACHE_NAME = 'Speakr-cache-v4';
+// The registration URL carries the app version as ?v=<version> (see
+// app.modular.js). Deriving the cache name from it gives every release its
+// own cache namespace, so the activate handler below clears the previous
+// release's app shell instead of serving it forever (issue #357).
+const APP_VERSION = new URLSearchParams(self.location.search).get('v') || 'v5';
+const CACHE_NAME = `Speakr-cache-${APP_VERSION}`;
const ASSETS_TO_CACHE = [
'/',
'/static/offline.html',
@@ -230,12 +235,13 @@ self.addEventListener('fetch', (event) => {
return;
}
- // For static assets listed in ASSETS_TO_CACHE, use cache-first.
- // This ensures that if an asset path is directly requested, it's served from cache if possible.
- // We need to match against the origin + pathname for ASSETS_TO_CACHE.
+ // For static assets listed in ASSETS_TO_CACHE, use stale-while-revalidate:
+ // the cached copy keeps loads fast (and works offline), while the
+ // background refetch means a stale shell self-heals on the next load
+ // instead of being pinned until the service worker itself changes.
const requestPath = url.origin === self.origin ? url.pathname : request.url;
if (ASSETS_TO_CACHE.includes(requestPath)) {
- event.respondWith(cacheFirst(request));
+ event.respondWith(staleWhileRevalidate(request));
return;
}
diff --git a/templates/index.html b/templates/index.html
index cf51e6d2..81329661 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -56,6 +56,7 @@
})();
</script>
<meta name="csrf-token" content="{{ csrf_token() }}">
+ <meta name="app-version" content="{{ app_version }}">
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>Speakr - Audio Transcription & Summarization</title>
{% include 'includes/loading_overlay.html' %}