Skip to content

Fix service worker handling, #167

Merged
sudip-mondal-2002 merged 19 commits into
sudip-mondal-2002:mainfrom
ANSHIKATYAGI30:fix-service-worker-handling
Jun 4, 2026
Merged

Fix service worker handling, #167
sudip-mondal-2002 merged 19 commits into
sudip-mondal-2002:mainfrom
ANSHIKATYAGI30:fix-service-worker-handling

Conversation

@ANSHIKATYAGI30

@ANSHIKATYAGI30 ANSHIKATYAGI30 commented May 21, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR improves the reliability and stability of the COOP/COEP service worker used for enabling SharedArrayBuffer support in Amplitron.

Changes included:

  1. Added proper error handling for failed fetch() requests.
  2. Prevented invalid responses when network requests fail.
  3. Improved service worker registration safety checks.
  4. Added protection against infinite reload loops.
  5. Improved compatibility checks for browsers without Service Worker support.
  6. Refactored activation/install handlers for better readability and maintainability.
  7. Reduced unnecessary console logs in production environments.

These changes help improve audio engine stability and prevent runtime crashes or blank-screen issues caused by failed service worker responses.

Related Issue

Fixes #161

Type of Change

  • 🐛 Bug fix
  • ✨ New feature
  • ♻️ Refactor / code cleanup
  • 📝 Documentation
  • ✅ Tests
  • 🔧 Build / CI / Configuration

How Was This Tested?

  • Platform(s) tested on: Windows 11, Chrome Browser
  • Test command run: ./amplitron-tests
  • Manual test steps (if applicable):
    1. Start the application locally.
    2. Open the browser and verify service worker registration.
    3. Reload the page multiple times.
    4. Simulate offline/network failure scenarios.
    5. Confirm no blank screen or broken audio initialization occurs.
    6. Verify SharedArrayBuffer-dependent features still function correctly.

Checklist

  • Code compiles and builds successfully on my platform
  • All existing tests pass (./amplitron-tests)
  • New tests added for new functionality (if applicable)
  • Documentation updated (README, code comments) if applicable
  • No blocking calls on the audio thread (no std::mutex::lock() on the hot path)
  • Tested on: Windows 11/Chrome

##Summary
Before

  1. Page occasionally failed to load after service worker registration.
  2. Fetch failures sometimes returned undefined responses.
  3. Repeated reload loops observed in some browsers.

After

  1. Stable service worker registration.
  2. Proper fallback handling on network errors.
  3. No infinite reload behavior.
  4. Improved browser compatibility and smoother initialization.

Summary by CodeRabbit

  • Bug Fixes

    • Returns a clear error response and logs when network fetches fail during service worker handling
    • Prevents duplicate service worker registrations
  • Compatibility

    • Checks runtime support and skips registration when the environment disallows it
  • Performance

    • Limits page reload to once per session after service worker activation, reducing unnecessary reloads

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Service worker fetch failures now return plain-text 503 responses; window bootstrap guards registration for unsupported/duplicate/crossOriginIsolated cases and derives script URL; after activation the page reloads once per session using sessionStorage["coiReloaded"].

Changes

Service Worker Reliability and Error Handling

Layer / File(s) Summary
Fetch error handling in service worker
web/coi-serviceworker.js
Service worker fetch event listener catches promise rejections and returns a plain-text 503 Service Unavailable response when fetch(event.request) fails.
Service worker registration guards and browser compatibility
web/coi-serviceworker.js
Window-side registration checks for navigator.serviceWorker, skips registration if window.crossOriginIsolated === false (clearing sessionStorage["coiReloaded"]), derives script URL from currentScript.src, and prevents duplicate registration by comparing existing registration scriptURL.
Post-registration activation and reload management
web/coi-serviceworker.js
After register/getRegistration, waits for installing/waiting worker to reach activated (or resolves immediately if already activated) and performs window.location.reload() only once per session by setting sessionStorage["coiReloaded"].

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I sniff the network, catch the fall,
I log the fail and answer all: a 503 call.
I mind the bootstrap, skip repeats,
I wake once per session, then stay discreet,
A tiny hop that keeps the demo tall.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is incomplete and vague, lacking specificity about what service worker handling was fixed. Provide a more descriptive title such as 'Fix service worker error handling and registration safeguards' to clarify the main improvements.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR addresses all major objectives from #161: fetch error handling with fallback responses, reload loop prevention, registration safeguards, graceful error handling, and improved reliability.
Out of Scope Changes check ✅ Passed All changes in web/coi-serviceworker.js directly address objectives from #161; no out-of-scope modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/coi-serviceworker.js`:
- Around line 89-97: The current service worker activation wait creates a
Promise whose executor uses await (and thus is improperly async) and never
resolves; replace that pattern with a single non-async Promise that (a)
immediately checks sw.state and resolves if already "activated", and (b)
otherwise adds a "statechange" listener on sw that calls resolve when
event.target.state === "activated" and removes the listener afterwards; ensure
the Promise executor is not declared async and do not nest another await inside
it so the outer await can actually complete.
- Around line 73-79: Capture the current script URL into a local variable (e.g.,
const scriptSrc = window.document.currentScript?.src) before calling await
navigator.serviceWorker.getRegistration(); then call
navigator.serviceWorker.getRegistration(), and only treat the worker as "already
registered" if existingRegistration exists and existingRegistration.scriptURL
=== scriptSrc; otherwise proceed to register using the captured scriptSrc. Also
handle the case where scriptSrc is null/undefined by failing early with an
explanatory log/error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0c069edc-ccc8-4c84-8f7c-5f46ff5cce38

📥 Commits

Reviewing files that changed from the base of the PR and between c2f4266 and ac27091.

📒 Files selected for processing (1)
  • web/coi-serviceworker.js

Comment thread web/coi-serviceworker.js Outdated
Comment thread web/coi-serviceworker.js Outdated
@sudip-mondal-2002

Copy link
Copy Markdown
Owner

@ANSHIKATYAGI30 please check the CI failure

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/coi-serviceworker.js`:
- Around line 103-109: The guard logic around RELOAD_KEY makes the inner branch
unreachable because RELOAD_KEY equals "coiReloaded" and you set that key
immediately before re-checking it; remove the redundant inner check and call
window.location.reload() right after setting the key (i.e., in the block where
!sessionStorage.getItem(RELOAD_KEY) is true), using the existing RELOAD_KEY
constant and sessionStorage.getItem/setItem to ensure a one-time reload.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 638a3458-503f-4ea1-8375-3a67f93d9242

📥 Commits

Reviewing files that changed from the base of the PR and between ac27091 and 80cb0cf.

📒 Files selected for processing (1)
  • web/coi-serviceworker.js

Comment thread web/coi-serviceworker.js Outdated
@ANSHIKATYAGI30

Copy link
Copy Markdown
Contributor Author

@sudip-mondal-2002 Kindly review whenever convenient.
Thank you!

@sudip-mondal-2002

Copy link
Copy Markdown
Owner

@ANSHIKATYAGI30 Please look at the test failure

@github-actions

github-actions Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

🌍 Cross-Platform Coverage Report

Platforms: Linux + Windows
Merged Line Coverage: 78.2%

✅ Coverage meets threshold: 78.2% >= 60%

Full Merged Coverage Summary
Summary coverage rate:
  lines......: 78.2% (7832 of 10014 lines)
  functions..: 85.3% (984 of 1154 functions)
  branches...: no data found

@sudip-mondal-2002 sudip-mondal-2002 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Check the CI failure

@sudip-mondal-2002 sudip-mondal-2002 added type:bug Something isn't working Quality-of-Life Improves usability and developer experience level:intermediate Intermediate task · 25 GSSoC points platform: web Web/Emscripten-specific issue or feature labels May 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/coi-serviceworker.js`:
- Around line 106-121: The Promise executor currently contains an invalid
async-await usage causing a SyntaxError; fix by ensuring the executor is a plain
synchronous function and only use a single top-level await with new Promise that
resolves when sw reaches "activated". Locate the activation-wait block using the
sw variable and the onStateChange handler, remove any inner await or async
keywords inside the Promise executor, and implement the logic so the executor
immediately resolves if sw.state === "activated" or otherwise adds a
"statechange" listener (onStateChange) that removes itself and calls resolve()
when e.target.state === "activated".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7c74218c-c64a-4f4e-a0f2-ba5d359db8fc

📥 Commits

Reviewing files that changed from the base of the PR and between c076f24 and a82e525.

📒 Files selected for processing (1)
  • web/coi-serviceworker.js

Comment thread web/coi-serviceworker.js Outdated
Comment on lines +106 to +121
if (sw) {
await new Promise((resolve) => {
// Resolve immediately if already activated
if (sw.state === "activated") {
resolve();
return;
}
const onStateChange = (e) => {
if (e.target.state === "activated") {
sw.removeEventListener("statechange", onStateChange);
resolve();
}
};
sw.addEventListener("statechange", onStateChange);
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check if the file has valid JavaScript syntax

# Use node to check syntax
node --check web/coi-serviceworker.js || echo "Syntax error detected"

# Show the problematic lines
echo "=== Lines 105-122 ==="
sed -n '105,122p' web/coi-serviceworker.js | cat -n

Repository: sudip-mondal-2002/Amplitron

Length of output: 1201


Critical: Fix await inside non-async Promise executor (parse-time SyntaxError).

web/coi-serviceworker.js fails a syntax check: Node reports SyntaxError: await is only valid in async functions ... at the inner await new Promise((resolve) => { ... (around line 107 in the file). This means the service worker activation wait logic cannot run as written.

Remove the invalid await usage from inside the Promise executor and rewrite the activation-wait to use a single await new Promise(...) (with the executor being non-async), only waiting for the "activated" state.

🧰 Tools
🪛 Biome (2.4.15)

[error] 107-107: await is only allowed within async functions and at the top levels of modules.

(parse)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/coi-serviceworker.js` around lines 106 - 121, The Promise executor
currently contains an invalid async-await usage causing a SyntaxError; fix by
ensuring the executor is a plain synchronous function and only use a single
top-level await with new Promise that resolves when sw reaches "activated".
Locate the activation-wait block using the sw variable and the onStateChange
handler, remove any inner await or async keywords inside the Promise executor,
and implement the logic so the executor immediately resolves if sw.state ===
"activated" or otherwise adds a "statechange" listener (onStateChange) that
removes itself and calls resolve() when e.target.state === "activated".

@sudip-mondal-2002

Copy link
Copy Markdown
Owner

@ANSHIKATYAGI30 are you still working on this?

@ANSHIKATYAGI30

Copy link
Copy Markdown
Contributor Author

@sudip-mondal-2002 yes, I'm.

@sudip-mondal-2002

Copy link
Copy Markdown
Owner

@ANSHIKATYAGI30 PTAL at the CI failures

@sudip-mondal-2002 sudip-mondal-2002 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

@ANSHIKATYAGI30 Are you still working on this? the CI is failing, please take a look

@MohitBareja16

Copy link
Copy Markdown
Collaborator

@ANSHIKATYAGI30 CI checks on web demo are still failing, fix it

@ANSHIKATYAGI30

Copy link
Copy Markdown
Contributor Author

@sudip-mondal-2002
Hi,
Please check once!
Thanks.

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

PR Preview Removed

The GitHub Pages preview for this PR has been removed because the PR was closed.

@sudip-mondal-2002 sudip-mondal-2002 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

LGTM

@codecov

codecov Bot commented Jun 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@sudip-mondal-2002 sudip-mondal-2002 merged commit 50899b6 into sudip-mondal-2002:main Jun 4, 2026
10 checks passed
@sudip-mondal-2002 sudip-mondal-2002 added the gssoc:approved GSSoC 2026 contribution label Jun 4, 2026
github-actions Bot added a commit that referenced this pull request Jun 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gssoc:approved GSSoC 2026 contribution level:intermediate Intermediate task · 25 GSSoC points mentor:sudip-mondal-2002 platform: web Web/Emscripten-specific issue or feature Quality-of-Life Improves usability and developer experience type:bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve Service Worker Error Handling, Reload Logic, and Security Reliability

3 participants