Skip to content

Interactive static assets stop loading after the browser stops the idle service worker, which keeps them only in memory #1797

Open

Description

@joshunrau

An interactive instrument's static assets stop loading once the browser stops its idle service worker. worker.js keeps the assets only in a module-level Map. Browsers terminate a service worker that has handled no event for about 30 seconds (Chrome and Firefox both use a 30 s idle timeout), even while a page it controls is open, and the next fetch starts a fresh copy of the script with an empty map. bootstrap.js posts the assets only once, before render. So any asset first requested after a pause of more than 30 s with no network activity misses the map and goes to the network, where it does not exist. Typical cases are a stimulus image shown after an instruction screen, or a sound played on a later trial. The participant sees a broken image or hears nothing, partway through a task whose data is then recorded as if the stimulus had been shown.

Where

packages/runtime-internal/src/interactive/worker.js:5-6 and 53-77:

/** @type {Map<string, string>} */
const staticAssets = new Map();
// ...
addEventListener('message', (event) => {
  // ...
  Object.entries(data.staticAssets).forEach(([key, value]) => {
    staticAssets.set(key, value);
  });
  event.ports[0]?.postMessage({ type: 'STATIC_ASSETS_READY' });
});

worker.addEventListener('fetch', (_event) => {
  // ...
  if (staticAssets.has(pathname)) {

packages/runtime-internal/src/interactive/bootstrap.js:49-74 sends STATIC_ASSETS once, at startup, and never again.

Reproduce

  1. Use the playground example "Interactive Instrument with Static Assets", changed so the <img src="smiley.png"> is inserted on a button click instead of being in the initial HTML.
  2. Open it in apps/web in Chrome.
  3. Wait more than 30 s without interacting, or click "stop" for the worker under DevTools > Application > Service workers, which does the same as an idle termination. Then click the button.

Actual: the restarted worker has an empty staticAssets map, /runtime/v1/@opendatacapture/runtime-internal/interactive/smiley.png goes to the server, and the image is broken.
Expected: the asset is served however long the task has been running.

Tests

packages/runtime-internal/src/interactive/__tests__/worker.test.ts: it('should still serve registered assets after the worker script is re-evaluated, so an idle termination does not lose them'). Load the assets, call vi.resetModules() and re-import worker.js to simulate a restart, then fetch. This needs a stubbed caches (Cache Storage) in the test globals.

e2e, in testing/src/specs/instrument-completion.spec.ts: open an interactive instrument with static assets, stop its service worker through CDP (ServiceWorker.stopWorker), then trigger an asset request and assert it loads.

Suggested fix

Persist the assets where a restarted worker can read them. On STATIC_ASSETS, write each one as a Response into a named Cache Storage cache (caches.open(...)), and acknowledge only after the writes resolve. In fetch, respond from caches.match(pathname) and fall back to the network on a miss. Clear the cache whenever a new STATIC_ASSETS message arrives, so one instrument's assets are never served to the next.

Activity

  1. added
    BugType: existing behavior is wrong
    Difficulty: MediumStraightforward change, about a day or less
    Area: InstrumentsInstrument authoring API, bundling, runtime, rendering, measures and the built-in library
    on Oct 7, 2026
  2. joshunrau commented on Oct 26, 2026

    @joshunrau
    CollaboratorAuthor

    Still reproduces on main (d86740e). Nothing has touched packages/runtime-internal since this was filed, and no open PR does. apps/gateway and the playground preview load the same worker through react-core's InteractiveContent (InteractiveContent.tsx:182), so remote participants hit this too.

    Changes to the suggested fix

    • One cache per iframe, not one shared cache. One worker serves every iframe in its scope on the origin. With two apps/web tabs running interactive tasks, clearing on each STATIC_ASSETS deletes the first tab's assets mid-task. An instrument without staticAssets never posts the message, so it would be served the previous instrument's files. Name the cache static-assets:<id>, where <id> is event.source.id in the message handler. That document's fetches carry the same id as event.clientId, and it does not change when the worker restarts. Write inside event.waitUntil(...). On each STATIC_ASSETS, delete the static-assets:* caches whose id is not in await clients.matchAll({ includeUncontrolled: true }).
    • Keep the name the same across worker versions, and delete nothing on activate. Any iframe.html load makes the browser check worker.js for changes, and skipWaiting() + clients.claim() (worker.js:8-14) then hand every open iframe to the new worker, including one mid-task.
    • A miss cannot be left alone. respondWith must be called synchronously, so the respond-only-on-a-hit pattern at worker.js:73-76 cannot wait for an async lookup. For every GET with a non-empty clientId (navigations have none), call event.respondWith(caches.match(pathname, { cacheName }).then((hit) => hit ?? fetch(event.request))). Do not narrow this to the interactive prefix: the example's fragment.html requests /smiley.png from the origin root. Use caches.match with cacheName, not caches.open, which would create an empty cache for every iframe without assets.
    • Report write failures. Decoding moves to store time, so the throw worker.test.ts:101-104 asserts moves into the message handler, and cache.put can also reject on quota. If nothing is posted back, bootstrap.js:60-73 waits forever and the instrument never renders. Post an error on the port and have bootstrap reject on it.

    Add a trap to packages/runtime-internal/AGENTS.md: the browser can stop worker.js at any time, so it keeps no state in module scope.

    Tests

    worker.test.ts, beside the restart case from the issue:

    • it('should serve each iframe only the assets it registered, so a second tab cannot replace or delete them')
    • it('should delete the caches of iframes that are gone when new assets arrive')
    • it('should acknowledge only after the writes finish')
    • it('should report on the port when the assets cannot be stored, so the iframe does not wait forever')
    • it('should leave navigations and non-GET requests to the browser')

    Rewrite :96-99 so a miss responds with fetch(event.request). bootstrap.test.ts needs it('should fail instead of waiting when the worker reports that the assets could not be stored').

    e2e: testing/ has no bundler, so instrument-completion.spec.ts cannot build an instrument with staticAssets. Use testing/src/specs/playground.spec.ts. On main no spec reaches worker.js (:123 sets image.src to the data URL), and the example test #1825 adds there never stops the worker. Build a share link from STIM_PNG_BASE64 (:100) whose instrument declares staticAssets: { '/stim.png': stim } and appends <img src="stim.png"> on click. Once the button is visible, open page.context().newCDPSession(page) and send ServiceWorker.enable, then ServiceWorker.stopAllWorkers. It takes no versionId, unlike stopWorker, and fails with "ServiceWorker domain not enabled" without enable. Then click and assert naturalWidth > 0. CDP is Chromium-only, so no @smoke tag. Rebase onto #1825, which adds a describe to that file.

    Land #1796 first or in the same PR: it rewrites dataUrlToResponse, which this moves into the message path.

    Triage note written with Claude Code. Code references point at main @ d86740e.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: InstrumentsInstrument authoring API, bundling, runtime, rendering, measures and the built-in libraryBugType: existing behavior is wrongDifficulty: MediumStraightforward change, about a day or lessPriority: MediumReal value; schedule normally

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions