Skip to content

fix: bump service worker cache to v4 and evict stale caches (#99)#100

Merged
enaboapps merged 3 commits intomainfrom
fix/issue-99-service-worker-cache-bust
Apr 9, 2026
Merged

fix: bump service worker cache to v4 and evict stale caches (#99)#100
enaboapps merged 3 commits intomainfrom
fix/issue-99-service-worker-cache-bust

Conversation

@enaboapps
Copy link
Copy Markdown
Owner

@enaboapps enaboapps commented Apr 9, 2026

Summary

  • Bumps service worker cache key from podium-v4 to evict old /_next/static/ chunks cached by the previous cacheFirst strategy
  • Adds old-cache cleanup in the activate event so stale caches are automatically deleted on every future SW update

Problem

After PR #89 replaced the /api/tts/speak server-side proxy with direct js-tts-wrapper browser calls, browsers that already had the service worker installed kept serving old cached JS bundles. Those bundles still contained the old fetch('/api/tts/speak', ...) call, causing repeated 404 errors and complete TTS failure.

Test plan

  • Hard-refresh or open the app in a new profile — TTS should work without any /api/tts/speak 404s
  • Confirm old browser sessions (with cached SW) recover automatically after the new SW installs and activates

Closes #99

Summary by CodeRabbit

  • Improvements
    • Refined talk audio caching process for improved reliability and handling of edge cases
    • Updated service worker cache management with enhanced cleanup of outdated cached content during app updates

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 9, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
podium-web Ready Ready Preview, Comment Apr 9, 2026 0:34am

Request Review

…te (#99)

After the js-tts-wrapper migration (PR #89), browsers with the service
worker installed were serving old cached chunks that still called the
removed /api/tts/speak route, causing 404 errors and TTS failure.

Bumping CACHE to podium-v4 forces all clients to fetch fresh bundles.
Added old-cache cleanup in the activate handler so stale caches are
automatically deleted on each SW update going forward.
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

Warning

Rate limit exceeded

@enaboapps has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 47 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 11 minutes and 47 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 34851e11-4c0c-441c-9307-d60698549042

📥 Commits

Reviewing files that changed from the base of the PR and between 6d43da8 and ef1d6f4.

📒 Files selected for processing (3)
  • app/layout.tsx
  • next.config.ts
  • public/sw.js
📝 Walkthrough

Walkthrough

Changes modify TTS audio caching from concurrent to sequential processing with updated abort handling in OnlineTalkPage, and bump the service worker cache version from podium-v3 to podium-v4 with automatic stale cache cleanup during activation.

Changes

Cohort / File(s) Summary
TTS Audio Caching Logic
app/talk/[id]/OnlineTalkPage.tsx
Refactored miss segment processing from concurrent Promise.all(misses.map(...)) to sequential for...of loop with await, adjusting abort handling from per-promise early returns to loop break statements; progress tracking preserved but now reflects only processed iterations.
Service Worker Cache Management
public/sw.js
Bumped cache version constant from podium-v3 to podium-v4; enhanced activate event handler to delete all non-matching caches before claiming clients, enabling automatic cleanup of stale cached assets on service worker updates.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PR #66: Both modify public/sw.js and its cache version/activation behavior; this PR introduces the cache cleanup logic that PR #66 may depend on or build upon.
  • PR #25: Both PRs modify TTS audio caching flow using getCachedAudio/setCachedAudio; this PR changes miss processing concurrency patterns from the approach in that PR.

Poem

🐰 Sequential hops now fetch our speech,
No more racing—each task in reach,
Old caches swept, the cache refreshed clean,
Service worker's the best we've seen! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes an unexpected change to TTS audio caching logic in OnlineTalkPage.tsx that is unrelated to the service worker cache versioning issue. Remove the sequential caching refactor from OnlineTalkPage.tsx; it should be addressed in a separate PR focused on TTS caching optimization.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and concisely summarizes the main changes: bumping the service worker cache version and evicting stale caches, directly matching the changeset.
Linked Issues check ✅ Passed The PR fully addresses the linked issue #99 requirements: bumps cache to v4 and implements stale cache cleanup in the activate handler.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-99-service-worker-cache-bust

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/talk/[id]/OnlineTalkPage.tsx (1)

150-180: ⚠️ Potential issue | 🟠 Major

Return on abort before saving prepared-state metadata.

Breaking out of the loop still falls through to saveTalkPreparedState(...) below. After cleanup runs, Line 188 clears currentAudioUrls, so an aborted run can persist cachedAudioSegments: 0 / hasAudio: false even when some blobs were already written to IndexedDB.

Suggested change
       for (const { segmentIndex, cacheKey, segment } of misses) {
         if (signal.aborted) break;
         try {
           const ttsText = isAzure && segment.elements
             ? buildSSML(segment.elements as SegmentElement[])
             : segment.text;
           const blob = await fetchTTSBlob(ttsText, activeTtsConfig);
           if (signal.aborted) break;
           await setCachedAudio(cacheKey, blob);
           audioUrls.current.set(segmentIndex, URL.createObjectURL(blob));
         } catch (err) {
           if ((err as Error).name === 'AbortError') break;
           hadFailure = true;
           setCacheFailed(true);
         } finally {
           if (!signal.aborted) {
             completed++;
             setCacheLoaded(completed);
             if (completed === segments.length) setCacheReady(true);
           }
         }
       }
+
+      if (signal.aborted) return;
 
       await saveTalkPreparedState(userId, id, {
         talkId: id,
         hasDocument: true,
         hasAudio: !hadFailure && currentAudioUrls.size === segments.length,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/talk/`[id]/OnlineTalkPage.tsx around lines 150 - 180, The loop that
processes `misses` can break on `signal.aborted` but the function still falls
through to calling `saveTalkPreparedState(...)`, causing incorrect metadata
since cleanup later clears `currentAudioUrls`; update the control flow so that
if `signal.aborted` is observed (inside the for loop or immediately after it)
you return early (or otherwise skip calling `saveTalkPreparedState`) to avoid
persisting partial/incorrect state — adjust logic around the `for (const {
segmentIndex, cacheKey, segment } of misses)` loop and the subsequent call to
`saveTalkPreparedState`, ensuring checks for `signal.aborted` occur before
calling `setCachedAudio`, `setCacheFailed`, or `saveTalkPreparedState` and
referencing `currentAudioUrls`, `setCacheLoaded`, and `setCacheReady` as needed.
🧹 Nitpick comments (1)
public/sw.js (1)

21-25: Scope cache eviction to Podium-owned caches.

keys.filter((k) => k !== CACHE) removes every other CacheStorage entry for this origin, not just old Podium service-worker caches. That makes future unrelated caches easy to wipe accidentally. Filter by your cache namespace instead.

Suggested change
 self.addEventListener('activate', (event) => {
   event.waitUntil(
     caches.keys()
-      .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
+      .then((keys) => Promise.all(
+        keys
+          .filter((k) => k.startsWith('podium-v') && k !== CACHE)
+          .map((k) => caches.delete(k))
+      ))
       .then(() => self.clients.claim())
   );
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@public/sw.js` around lines 21 - 25, The activate handler currently deletes
all caches except the current CACHE which can remove unrelated origin caches;
update the eviction to only target Podium-owned caches by filtering cache keys
using your Podium namespace (e.g., a prefix or pattern) instead of comparing to
CACHE directly. In the activate event listener where caches.keys() is used (and
where CACHE is referenced), change keys.filter((k) => k !== CACHE) to filter
keys that startWith/contain your Podium cache prefix (or match a RegExp) and
then delete only those matching keys, keeping unrelated caches untouched and
still removing old Podium caches.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@app/talk/`[id]/OnlineTalkPage.tsx:
- Around line 150-180: The loop that processes `misses` can break on
`signal.aborted` but the function still falls through to calling
`saveTalkPreparedState(...)`, causing incorrect metadata since cleanup later
clears `currentAudioUrls`; update the control flow so that if `signal.aborted`
is observed (inside the for loop or immediately after it) you return early (or
otherwise skip calling `saveTalkPreparedState`) to avoid persisting
partial/incorrect state — adjust logic around the `for (const { segmentIndex,
cacheKey, segment } of misses)` loop and the subsequent call to
`saveTalkPreparedState`, ensuring checks for `signal.aborted` occur before
calling `setCachedAudio`, `setCacheFailed`, or `saveTalkPreparedState` and
referencing `currentAudioUrls`, `setCacheLoaded`, and `setCacheReady` as needed.

---

Nitpick comments:
In `@public/sw.js`:
- Around line 21-25: The activate handler currently deletes all caches except
the current CACHE which can remove unrelated origin caches; update the eviction
to only target Podium-owned caches by filtering cache keys using your Podium
namespace (e.g., a prefix or pattern) instead of comparing to CACHE directly. In
the activate event listener where caches.keys() is used (and where CACHE is
referenced), change keys.filter((k) => k !== CACHE) to filter keys that
startWith/contain your Podium cache prefix (or match a RegExp) and then delete
only those matching keys, keeping unrelated caches untouched and still removing
old Podium caches.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5acff146-4066-4e96-ae98-e6523b5b90ae

📥 Commits

Reviewing files that changed from the base of the PR and between f0d4dc1 and 6d43da8.

📒 Files selected for processing (2)
  • app/talk/[id]/OnlineTalkPage.tsx
  • public/sw.js

Instead of a manually-bumped hardcoded version string, the SW cache key
is now derived from the app version:

- next.config.ts exposes npm_package_version as NEXT_PUBLIC_APP_VERSION
- layout.tsx registers /sw.js?v=<version> so the query string changes
  automatically on each release
- sw.js reads self.location.search to build its cache key (podium-<version>)

Cache busting now happens automatically whenever package.json version is
bumped — no manual SW edits required.
@enaboapps enaboapps merged commit 6bb0149 into main Apr 9, 2026
3 checks passed
@enaboapps enaboapps deleted the fix/issue-99-service-worker-cache-bust branch April 9, 2026 12:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: service worker serves stale cached chunks after js-tts-wrapper migration

2 participants