Frame.dev
pwaservice-workerindexeddboffline

How a PWA works offline: precaching and browser storage

Frame.dev Team12 min read

safeos.sh is a set of static files, and a service worker stores its pages, scripts, styles and everyday images in the browser on the first visit. From then on the app’s pages open with no connection, the motion and sound checks and Lost and Found run, and People and Wildlife run once their model is saved. This post follows the code that does it, from the build to the browser’s storage, and ends with what a browser may still take away.

The short version, with the other parts of SafeOS beside it, is the offline section of how SafeOS watches a room in your browser. Here is the whole path:

From build to an offline startThe build lists every file with one digest; the service worker stores the whole list or nothing, and serves it with no connection. The list under the drawing says each step in words.The build exports everypage as a static file.One list of the files tokeep, with a SHA-256 digestof them all.The service worker storesthe whole list, or none ofit.On taking over, it keepsthe build that ran last anddeletes the older ones.With no connection, a pagecomes from the storedbuild, or else the offlinepage.
From build to an offline start
  1. The build exports every page as a static file.
  2. One list of the files to keep, with a SHA-256 digest of them all.
  3. The service worker stores the whole list, or none of it.
  4. On taking over, it keeps the build that ran last and deletes the older ones.
  5. With no connection, a page comes from the stored build, or else the offline page.

Every page is a file

The web app is a Next.js 14 project set to output: 'export', with trailingSlash: true and unoptimised images, which a static export needs (next.config.js). After next build, Next.js writes an out folder of HTML, CSS and JavaScript (the Next.js 14 guide to static exports). With the trailing slash, each route is a folder holding an index.html, so /wildlife/ is out/wildlife/index.html. The deploy workflow uploads that folder and GitHub Pages serves it (deploy-pages.yml). No code of the app runs on a server at safeos.sh, which is what lets one stored copy of the folder be the whole app.

One hashed list of every file

The web app’s postbuild script runs a second step once the export is written (package.json). It walks out/ and keeps the files a visit needs: the HTML, the route data Next.js loads between pages, every script under _next/static/ including the chunks loaded later, the styles, fonts, icons and everyday images, and the web app manifest. It leaves out the home page’s recorded runs, the Lost and Found example photos, the capture pictures, the social card, the screenshots and any video file (generate-offline-manifest.mjs). Then it hashes the list:

const worker = await readFile('public/sw.js', 'utf8');
// Keep each path and content digest in a separate, unambiguous record.
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
const hash = createHash('sha256').update(JSON.stringify(['worker', digest(worker)]));
const urls = [];
for (const file of files) {
  const relative = relativePath(file);
  hash.update(JSON.stringify(['file', relative, digest(await readFile(file))]));
  urls.push('/' + relative.replace(/(^|\/)index\.html$/, '$1'));
}
if (!urls.includes('/') || !urls.some(url => url.startsWith('/_next/static/') && url.endsWith('.js'))) {
  throw new Error('Static export is missing HTML or scripts.');
}
const posterUrls = [];
for (const file of posters) {
  const relative = relativePath(file);
  hash.update(JSON.stringify(['poster', relative, digest(await readFile(file))]));
  posterUrls.push('/' + relative);
}
const manifest = { version: hash.digest('hex'), urls, posters: posterUrls };
await writeFile(path.join(root, 'sw.js'), `self.__SAFEOS_PRECACHE = ${JSON.stringify(manifest)};\n${worker}`);
generate-offline-manifest.mjs, lines 29–49 at commit 017b33b

Each file goes into the hash as its own JSON record, its path beside the SHA-256 digest of its bytes, after a record for the worker’s own source. Change one byte of one file, or of the worker, and the version changes. A build that produced no home page or no script stops here with an error. The last line writes the list and its version into the first line of out/sw.js, ahead of the worker’s code, so the worker that a browser downloads carries the exact list of the build it belongs to. The worker names its cache after that version, safeos-shell- and the digest (sw.js).

Stored whole, or not at all

Every page registers /sw.js when it has loaded (layout.tsx), so a visitor’s first page starts the install:

self.addEventListener('install', (event) => {
  if (UNBUILT) {
    self.skipWaiting();
    return;
  }
  event.waitUntil((async () => {
    if (!manifest?.urls?.length) throw new Error('Offline asset manifest is missing.');
    const cache = await caches.open(CACHE_NAME);
    // Installation succeeds only when HTML, scripts, styles and lazy chunks exist.
    await cache.addAll(manifest.urls);
    // The new build takes over once it is stored whole, so a returning visitor
    // gets it on the load after the one that found it, not after closing every
    // tab. A page already open keeps the scripts it loaded; one that then asks
    // for a file the new build replaced reloads once onto it (the app's error
    // page, once for each build).
    await self.skipWaiting();
  })());
});
sw.js, lines 56–73 at commit 017b33b

cache.addAll fetches every address on the list and rejects if any answer’s status is not in the 200 range (MDN on Cache.addAll). It writes to the cache only once every response has arrived, as one batch that is undone if any part of it fails (the Service Workers specification). Its promise goes to event.waitUntil, and MDN states the consequence: “If the promise passed to waitUntil() rejects, the install is considered a failure, and the installing service worker is discarded” (MDN, Mozilla Contributors, CC BY-SA 2.5). So a browser holds either the whole build or none of it, never a page whose scripts are missing. A worker with no list, which is what next dev serves, stores nothing and steps aside (sw.js).

skipWaiting() makes the new worker the active one without waiting for the visitor to close every tab (MDN on skipWaiting), so a returning visitor gets a new build on the load after the one that found it. Activation then tidies up:

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    const names = await caches.keys();
    const older = names.filter(name => (name.startsWith('safeos-shell-') || /^safeos-v\d+$/.test(name)) && name !== CACHE_NAME);
    // The build that ran last stays, since a page loaded from it may still ask
    // for its own scripts; every build before it goes. A worker with no build
    // list keeps none.
    let kept = null;
    if (!UNBUILT && older.length) {
      const times = await Promise.all(older.map(takenOver));
      kept = older[times.indexOf(Math.max(...times))];
    }
    await Promise.all(older.filter(name => name !== kept).map(name => caches.delete(name)));
    if (!UNBUILT) await markTakenOver(await caches.open(CACHE_NAME));
    await self.clients.claim();
  })());
});
sw.js, lines 102–118 at commit 017b33b

Each build writes the time it took over into its own cache, under /__safeos-taken-over (sw.js). On activation the new worker keeps the one older build that took over last and deletes every build before it. The kept build is there for pages still open from it, which may yet ask for scripts the new build renamed. clients.claim() makes the new worker the controller of every open page in its scope (MDN on Clients.claim). The cache filter matches nothing else, so the detection model’s own cache survives every update.

Answering a request with no connection

The worker answers only GET requests to its own origin. It leaves requests to /api/, MP4 videos and range requests to the network (sw.js), and every other origin too, so the model’s download from Google’s storage passes by it into the loader’s own cache, which the post on object detection in the browser follows. For everything else it looks in this order:

const cached = await cache.match(request) ||
  (request.mode === 'navigate' ? await cache.match(storedPage(url)) : undefined) ||
  (url.pathname.endsWith('.txt') ? await cache.match(url.origin + url.pathname) : undefined) ||
  // A page loaded from the build before this one may still ask for its own
  // scripts and styles, which this build replaced: that build's files stay
  // until the next build takes over.
  (request.mode !== 'navigate' && url.pathname.startsWith('/_next/') ? await caches.match(request) : undefined);
if (cached) return cached;
sw.js, lines 157–164 at commit 017b33b

First the request exactly as stored. Then, for a page, its path with the closing slash added and the query left out, so /monitor, /monitor/ and /monitor/?source=shortcut are one stored page (sw.js). Then, for route data, the file without its ?_rsc= query, which a static host ignores anyway. Last, for a file under _next/, any cache at all, which is how the kept older build serves the pages still open from it. Only when every lookup misses does the request go to the network:

try {
  const answer = await fetch(request);
  if (!answer.ok && alternative) return (await cache.match(alternative)) || answer;
  if (request.mode === 'navigate') event.waitUntil(refillIfEmpty(cache));
  return answer;
} catch {
  if (alternative) {
    const poster = await cache.match(alternative);
    if (poster) return poster;
  }
  if (request.mode === 'navigate') {
    const fallback = await cache.match('/offline.html');
    if (fallback) return fallback;
  }
  return new Response('Offline', { status: 503 });
}
sw.js, lines 166–181 at commit 017b33b

Offline, a page the build does not hold gets /offline.html, a page titled “This page is not on this device” that points to the dashboard (offline.html), and any other file gets a 503. A page that does reach the network also calls refillIfEmpty: if the build’s cache was emptied while the worker stayed active, as “Clear all data on this device” does, the worker stores the whole list again, and tries again after a passing error while the device has a connection (sw.js).

Proving it before each deploy

The deploy workflow builds the export on every pull request and deploys only from master (deploy-pages.yml, deploy-pages.yml). Between the build and the upload it runs one check in Chromium (deploy-pages.yml). The script serves out/ on a local port, opens only the home page and waits for the worker to report ready (check-offline-start.mjs). Then:

await context.setOffline(true);
const offlinePage = await context.newPage();
await offlinePage.goto(base + '/wildlife/');
await offlinePage.getByRole('button', { name: 'Settings', exact: true }).click();
await expect(offlinePage.getByRole('heading', { name: 'Wildlife Settings', exact: true })).toBeVisible();
console.log('Previously unopened Wildlife page starts and responds offline.');
check-offline-start.mjs, lines 46–51 at commit 017b33b

With the browser context offline, it opens the Wildlife page, which it never visited, presses Settings and finds the Wildlife Settings heading. That proves the precache holds an unvisited route and enough of its scripts to respond. A failure stops the build job, and the deploy job waits on it. The check runs no watch, and it runs in Chromium alone; no phone was tried.

Where the app keeps what it saves

The worker’s cache holds the app’s files. What the app saves goes to three places in the same browser: the IndexedDB database safeos-guardian, version 8, opened through the idb library (client-db.ts, client-db.ts); localStorage, where the settings and Wildlife’s sightings live as persisted stores (settings-store.ts); and Cache Storage, which also holds the detection model once the person agrees to it.

What this browser keeps, where and for how long
WhatWhereHow long
The app’s own files: every page, script, style and font of the buildCache Storage, one cache for each buildUntil the next build takes over; the build before it stays for pages still open
The detection model, 18.6 MB, after you agree to itCache Storage, safeos-detection-model-v1Kept through app updates
Alerts and their pictures, Lost and Found’s sightings, People’s picturesIndexedDB, the database safeos-guardianPictures 3 days unless you choose 1, 7 or 30 days or to keep them
People’s alerts; your pets and their photosIndexedDB and localStoragePeople keeps 100 alerts; pets until you remove them
Your settings, Wildlife’s sightings with their pictures, your yes to the model downloadlocalStorageWildlife keeps 100 sightings, their pictures as long as alert pictures; the rest until you change them
An alert sound you addedIndexedDB, a database of its ownUntil you remove it

Every row goes with Clear all data on this device on Settings, Data, or when the browser deletes the site’s storage.

The limits are in the code that writes each store. People keeps 100 alerts (client-db.ts), and Wildlife keeps 100 sightings with their pictures (animal-alert-store.ts, animal-alert-store.ts).

A database version change is one moment two tabs of the same site can get in each other’s way. When a new build raises the version, the browser fires versionchange at every older connection (MDN on versionchange), and an open request that those connections hold up fires blocked (MDN on blocked). The idb library hands both to callbacks named blocking and blocked (idb’s README):

const opening = openDB<SafeOSDB>(DB_NAME, DB_VERSION, {
  blocked() {
    requestDatabaseReload(BLOCKED_NOTICE);
    rejectBlocked(new Error(BLOCKED_NOTICE));
  },
  blocking(_currentVersion, _blockedVersion, event) {
    (event.target as IDBDatabase).close();
    dbPromise = null;
    requestDatabaseReload(UPDATED_NOTICE);
  },
  terminated() {
    dbPromise = null;
  },
client-db.ts, lines 356–368 at commit 017b33b

The older tab closes its connection, so the upgrade can go ahead, and asks the person to reload. The newer tab, if it is the one held up, tells the person to close the other SafeOS tabs and reload. Until a reload, new alerts in that tab show but are not saved, and the notice says so (client-db.ts).

A device out of room refuses the write. SafeOS notes it once for the visit, so the dashboard can say so, and the alert sound plays all the same: a save that fails for lack of room never stops the alert it was saving (storage-full.ts).

One watch across tabs

Every tab of the site joins one channel. A tab says when an alert was saved, seen or deleted, and when its watch starts and ends; a tab about to start a watch asks first, and a watching tab answers. Of two tabs that ask at once, the one that asked first goes on, with the tab’s random id breaking a tie (tab-channel.ts, tab-channel.ts). The channel is a BroadcastChannel named safeos, which carries messages between documents of the same origin (MDN on BroadcastChannel). A browser without one gets the same words through localStorage: each write fires a storage event in the site’s other tabs, never in the tab that wrote it (MDN on the storage event; tab-channel.ts). Either way the words stay inside the browser.

What a browser may take away

A site’s storage is best-effort by default: it stays while the site is under its quota and the device has room, and the browser may delete it under storage pressure, least recently used site first (MDN on storage quotas and eviction). A site can ask for persistent storage with navigator.storage.persist() (MDN on persist); SafeOS does not ask. Safari, with cross-site tracking prevention on, deletes a site’s script-written data when it has had no click or tap in the last seven days of browser use. An eviction takes all of a site’s data at once, IndexedDB and Cache Storage together (MDN, the same page).

So a device that has not opened safeos.sh for a while may hold nothing of it. The next visit online stores the build again, and People and Wildlife ask again before the model downloads. The person can also empty everything on purpose with “Clear all data on this device”, on Settings, Data. It empties both databases, then:

if ('caches' in window) {
  const names = await caches.keys();
  await Promise.all(names.filter((name) => name.startsWith('safeos')).map((name) => caches.delete(name)));
}
for (const storage of [localStorage, sessionStorage]) {
  const keys = Array.from({ length: storage.length }, (_, index) => storage.key(index));
  for (const key of keys) {
    // The clear markers survive every clear, so other tabs can tell that one happened.
    if (!key || key === LOCAL_CLEAR_MARKER_KEY || key === ACCOUNT_CLEAR_MARKER_KEY || key === PICTURES_CLEAR_MARKER_KEY || (options.preserveBackendConfig && key === 'safeos_backend_config')) continue;
    if (key.startsWith('safeos') || GUARDIAN_KEYS.includes(key)) storage.removeItem(key);
  }
}
local-data.ts, lines 54–65 at commit 017b33b

Every cache whose name starts with safeos goes, the app’s build and the model among them, and so does every localStorage and sessionStorage key that starts with safeos, with three older guardian- keys. Three markers stay, so the site’s other tabs can tell that a clear happened (local-data.ts).

Three more limits come from the browser rather than the storage:

  • Browsers slow the timers of a tab out of sight; Firefox for Android waits at least 15 minutes in an inactive tab and may unload it (MDN on setTimeout). Keep the watching page open and in front.
  • SafeOS keeps no screen awake: it does not use the Screen Wake Lock API (MDN on Screen Wake Lock).
  • Notifications come from the open page. The worker has a push handler (sw.js), but the web app makes no push subscription, so nothing alerts with the browser closed.

What leaves the device

Stored files are only half of the picture. These are the connections the app makes or leads to, each with when it happens, who sees what and how to stop it. The privacy page shows the same table from the same component (DeviceConnections.tsx).

What leaves this device
ConnectionWhenWho sees whatHow to stop it
The host’s logEach time you open a page of safeos.sh.GitHub, which hosts safeos.sh, logs your IP address and keeps it for security purposes.Serve your own copy of SafeOS from a host you choose; that host’s own log then applies.
The detection modelOnly after you agree to it, on People, Wildlife or Settings, Models; again if the browser’s storage is cleared.Google’s storage (storage.googleapis.com) sees your IP address when the browser downloads the model.Do not agree to the download. Motion and sound, and Lost & Found, need no model.
A spoken alertOnly after you choose an online voice under Spoken alert voice, on Settings, Alert sounds; then each time People, Wildlife or Lost & Found speaks an alert with it.People, Wildlife and Lost & Found speak their alerts with a voice on this device. An online voice is a service run by the browser’s maker, which receives the words to speak. Alert sounds names each online voice with “(online)”.Choose Use a voice on this device under Spoken alert voice. To stop spoken alerts as well: on People, turn off Voice Warnings; on Wildlife, choose Sound or Silent under Alert Mode; on Lost & Found, turn off Speak alert message under Image Flash Overlay.
A server you connectOnly after you save the address of a server you run, while Processing Mode on Settings, Models is Hybrid or AI queue. Hybrid is the default.The monitor sends camera frames, with their motion and sound readings, to that server, and whoever runs it can see them. With cloud AI keys set, when Ollama is down or its analysis fails, the server sends the frame to the first of OpenRouter, OpenAI and Anthropic it has a key for and, if that one fails, to the next.Choose Local instant under Processing Mode on Settings, Models, or clear the server address.

The first row is GitHub’s: on a Pages site, “the visitor’s IP address is logged and stored for security purposes” (GitHub Docs). The last row is a server the person runs, which the next post takes apart.

SafeOS adds an alert. It does not replace a person nearby. A phone or a browser can sleep, lose power or drop the camera, so stay within reach.

Next: self-hosted camera AI with Ollama, Moondream and LLaVA, what that server receives, how long it keeps a frame and when a cloud provider sees one.

Next.js, Safari, Firefox, Chrome, Chromium and GitHub are named to describe what SafeOS is built with and runs on. Product names belong to their owners; SafeOS is not affiliated with them.

— The Frame.dev Team

Frame.dev Team

Frame makes SafeOS and AgentOS. frame.dev