Skip to content

Perf: the shell asks the service worker for a screen before you click it - #678

Merged
AllTerrainDeveloper merged 5 commits into
trunkfrom
add/sw-speculative-documents
Aug 25, 2026
Merged

AllTerrainDeveloper merged 5 commits into
trunkfrom
add/sw-speculative-documents

Conversation

@AllTerrainDeveloper

@AllTerrainDeveloper AllTerrainDeveloper commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

The shared asset cache from #676 took the network out of a window's assets. It could never touch the document — admin HTML carries nonces and per-request screen state, so it is uncacheable by construction. And on a live install the document is the majority of a window open: measured at ~2.1 s of a ~3.8 s tab click, against ~1.7 s for everything the browser then does with it.

That cost does not have to be paid after the click.

The gap this closes

Two halves existed and were never connected:

  • The shell already knows every URL a window can reach (dock items and submenu tabs come straight from the menu payload) and already reads hover intent.
  • The service worker already receives the fetch event for every iframe navigation — and deliberately declines to answer it.

Now a hover on a submenu tab posts os-speculate-doc to the worker, which fetches that screen once and holds it; the iframe's own navigation is then answered from those bytes.

This is explicitly not "keep the tab alive." Nothing rendered is retained: no DOM, no live iframe, no memory beyond a response body dropped after 30 s. The page is still built fresh — it is simply built while the user is still deciding.

Measured on openstation.blog (production WordPress.com hosting, real network)

Tab click Time from click to screen ready
No hover (control) 1,997 ms / 3,605 ms
~3 s hover 961 ms / 1,000 ms / 1,002 ms / 1,014 ms
600 ms hover (partial head start) 1,014 ms (from a 3,605 ms control)

Roughly 2–3.5× faster, and strikingly consistent once the document is in hand. The residual ~1 s is the browser parsing and executing that page's JavaScript — the half no prefetch can remove, and exactly what the earlier breakdown predicted:

Where a tab click's time went (measured before this change)
Server building the document 2,119 ms 56%
Browser running the page's JavaScript 1,671 ms 44%
Downloading assets 0 ms 0% (already handled by #676)

This PR removes the first row from the user's wait. The second row is untouched and honestly out of reach without retaining the rendered page, which we deliberately are not doing.

The bug the first measurement caught

The first implementation held only the settled response. Two runs disagreed wildly — 5 ms in one, 1,001 ms in another — and the reason mattered: a click landing while the fetch was still in flight found nothing waiting and started a second request for the same screen. Full price for the user, double load for the server.

The store now holds the promise, so a mid-flight click awaits the request already running and inherits whatever head start the hover bought. That is why 600 ms of hover was enough to turn a 3,605 ms click into 1,014 ms.

Why answering an iframe navigation is safe here

The fetch handler otherwise refuses to answer iframe navigations, and that guard stays. The hazard it exists for (#171) is the worker re-fetching an iframe request: Chrome then sends Sec-Fetch-Dest: empty, the server's chromeless detection falls through, and the entire desktop renders inside a window.

A speculative document is never re-fetched. It is fetched once, ahead of time, from a URL the shell built with openstation_chromeless=1 present — and the server checks that query flag before it consults Sec-Fetch. So the held bytes are already correctly chromeless, and the fallback path (speculative fetch failed → fetch normally) is safe for exactly the same reason.

Safety

  • Speculation never acts. Any URL carrying action, action2, _wpnonce, nonce or delete_all is refused, so a hover can never activate a plugin, empty a trash, or apply an update.
  • Same-origin, /wp-admin/ only, and the chromeless flag must be present.
  • Single-use, exact-URL match, 30 s TTL, capped at 6 held documents with oldest-first eviction.
  • Redirected or non-200 responses are never held — a redirect means the server wanted the user somewhere else, and replaying the destination under the original URL would hide that.
  • Gated on the existing hover-prewarm opt-in (windowPrewarmEnabled), delivered to the worker through the same self.__OS_SW_CONFIG preamble the asset cache uses. Off by default; zero behaviour change until a user opts in.
  • Pointer-only (pointerType === 'mouse') — touch has no hover, so there is no intent to read.

Testing

npm run typecheck, lint, lint:php, build green. Full suites: 4,972 JS, 2,495 PHP. New coverage for the config flag's independent parsing in sw-policy.test.ts. Verified live on openstation.blog throughout: correct screens rendered (Writing Settings, Media Settings, Discussion Settings, Permalink Settings all confirmed by heading), forms intact, zero console errors.

🤖 Generated with Claude Code

Open WordPress Playground Preview

The shared asset cache took the network out of a window's assets. It
could never touch the document: admin HTML carries nonces and
per-request screen state, so it is uncacheable by construction - and on
a live install it is the majority of a window open, measured at ~2.1s
of a ~3.8s tab click against ~1.7s for everything the browser then does
with it.

That cost does not have to be paid after the click. The shell already
knows every URL a window can reach and already reads hover intent; the
worker already sees every iframe navigation's fetch event and
deliberately declines to answer it. Nothing connected the two. Now a
hover on a submenu tab posts `os-speculate-doc` to the worker, which
fetches that screen once and holds it, and the iframe's own navigation
is answered from those bytes.

This is deliberately NOT keeping tabs alive: nothing rendered is
retained - no DOM, no live iframe, no memory beyond a response body
dropped after 30s. The page is still built fresh, just early.

The store holds the fetch's PROMISE rather than the settled response,
which is the difference between helping sometimes and helping always: a
user who hovers and clicks half a second later would otherwise arrive
mid-flight, find nothing, and start a SECOND request for the same
screen. Measured live: 600ms of hover turned a 3,605ms click into
1,014ms.

Answering an iframe navigation is safe here precisely because the
response is never re-fetched. The hazard the navigate branch guards
against (issue #171) is the worker re-fetching an iframe request, which
makes Chrome send Sec-Fetch-Dest: empty and collapses the whole desktop
into a window. A speculative document is fetched once, ahead of time,
from a URL carrying openstation_chromeless=1 - which the server checks
before Sec-Fetch - so the held bytes are already correctly chromeless,
and the fallback re-fetch is safe for the same reason.

Speculation never acts: any URL carrying action/_wpnonce/delete_all is
refused, so a hover can never activate a plugin or empty a trash.
Single-use, exact-URL, 30s TTL, capped at 6 documents, and gated on the
same hover-prewarm opt-in the dock uses.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

@claude can you review?

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @AllTerrainDeveloper's task in 3m 34s —— View job


Review

  • Gather context (diff, changed files, docs)
  • Read speculative-doc implementation (speculate.ts, sw.ts, sw-policy.ts, window/index.ts, pwa.php)
  • Check safety guards (chromeless flag, nonce/action denylist, same-origin, TTL/cap)
  • Check docs updated per AGENTS.md contract
  • Post review feedback

The core idea is sound and the write-up in the PR body is careful — I verified the central safety claim myself: openstation_is_chromeless_request() (includes/core/routing.php:264) checks the openstation_chromeless query flag before falling back to Sec-Fetch-Dest, so re-fetching a speculative URL really can't trigger the #171 "screen on screen" bug, since these URLs always carry that flag via withChromelessParam(). Good.

Two issues worth fixing before merge, plus a couple of smaller notes.

1. The per-page asked dedupe set silently kills the feature after first use (src/pwa/speculate.ts:30, :59-62)

const asked = new Set<string>();
...
if ( asked.has( absolute ) ) {
    return;
}
asked.add( absolute );

This set is only ever cleared by the test-only _resetSpeculation() (never called from production code). But the held document on the worker side is single-use and TTL'd at 30s (src/pwa/sw.ts SPECULATIVE_TTL_MS/takeSpeculative). So once a tab's URL has been speculated once in a page's lifetime — whether the click landed (consumed) or the user hovered-away-without-clicking (expired) — every later hover over that same tab for the rest of the session becomes a silent no-op. It falls straight through to a plain iframe navigation, i.e. zero benefit.

Given users routinely bounce between the same few submenu tabs repeatedly in one desktop session (Writing → Permalinks → back to Writing), this means the measured 2–3.5× win only applies to the first visit to each screen per page load, not the repeat visits the feature is presumably also meant to help. Worth either dropping asked in favor of the worker's own dedupe (already mentioned as "the worker de-duplicates too" in the comment above it), or expiring entries from asked on a timer that tracks the worker's TTL/consumption.

Fix this →

2. docs/pwa.md wasn't updated

AGENTS.md's doc map is explicit: "docs/pwa.md | Caching policy, manifest emission, SW scope/registration, or wp.os.notify / pwa.* surface changes." This PR adds a new SW message type (os-speculate-doc), a new config flag (windowPrewarm in the __OS_SW_CONFIG preamble), and a new fetch-interception path — none of which appear in docs/pwa.md's "Caching policy" or "JS surface" sections. Per the same file's rule ("A hook change without a doc update ships a lie"), this should get a short section alongside the existing "shared admin-asset cache (opt-in)" writeup.

3. No test coverage for the new logic itself

The only new test (tests/vitest/sw-policy.test.ts) covers the trivial config-flag parsing. The actually load-bearing pieces have zero coverage:

  • isSpeculatableDocument() in src/pwa/sw.ts — the safety-critical action/nonce/delete_all denylist that keeps speculation from ever performing a state change.
  • The promise-vs-settled-response store, TTL eviction, and single-use takeSpeculative() semantics — exactly the subtlety the PR body says burned the first implementation (the "5 ms vs 1,001 ms" bug).
  • src/pwa/speculate.ts entirely — it even ships a test seam (_resetSpeculation) that's currently unused, suggesting a test was planned but not written.

Given sw.ts is hard to unit test directly (relies on self/fetch globals), at minimum the pure isSpeculatableDocument predicate and the shell-side speculateDocument() dedupe/origin-check logic seem straightforward to cover and are exactly where a regression would be silent (as issue #1 above demonstrates).

Minor

  • src/window/index.ts: pointerover (not pointerenter) is used for the delegated listener, which bubbles from descendants — expect it to fire repeatedly as the pointer moves across a tab's child nodes (icon, label). Not a correctness bug (both the shell's asked set and the worker's speculative.has() dedupe it), just more event traffic than necessary; pointerenter doesn't bubble so it isn't directly usable in a delegated handler, but this could be worth a comment noting it's intentional.
  • The speculative fetch() in the SW message handler (src/pwa/sw.ts) doesn't forward headers from an actual browser navigation (e.g. Referer, Accept-Language) — likely fine given admin screens don't generally branch on those, but worth a one-line callout if that's a considered tradeoff.

Everything else — same-origin checks, exact-URL single-use matching, the 6-entry cap with oldest-first eviction, the pointer-only/mouse-only gate, and the promise-holding fix for the double-fetch race — looks correct and matches the PR description precisely.
· Branch: add/sw-speculative-documents

AllTerrainDeveloper and others added 2 commits August 25, 2026 16:19
…till building the shell

A shell boot is two independent server renders run strictly one after
the other. Measured on a live install:

    0ms ─── shell document requested
  3172ms ─── shell HTML arrives (3.2s of server time)
  3876ms ─── only NOW is a window document requested
  6491ms ─── everything ready

The window's document does not depend on a single byte of the shell's,
yet it cannot even be asked for until the shell's HTML has arrived and
its JavaScript has run and built an iframe. The shell cannot fix this
from inside itself: by the time its code exists, the 3.2 seconds are
already spent.

The service worker can. It is woken by the shell's own navigation -
before the server has finished building it - so it can start the window
fetches right then, in parallel. It only needs to know what to fetch,
which is what the session saver now tells it: every save posts the
restore list, the worker persists it, and the next boot replays it the
moment the shell navigation arrives.

Reuses the speculative store wholesale, including the in-flight promise
semantics, so a window whose iframe appears mid-fetch waits on the
request already running instead of starting a second one. Same safety
rules: same-origin, /wp-admin/ only, chromeless flag required, nothing
carrying action/_wpnonce/delete_all, capped and short-lived. Gated on
the same hover-prewarm opt-in, and fire-and-forget - a boot never waits
on speculation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
`replayedThisBoot` was a boolean, but a service worker outlives any
single page load - it stays resident across navigations and can be
reused for hours. So the replay fired on the first shell load that
worker ever saw and never again, leaving every later boot
unaccelerated.

The first live measurement said so plainly: one window's TTFB halved
(1,353ms -> 687ms) while the other sat unchanged at 1,246ms. Replaced
with a short time-based throttle, which is all that was ever needed -
beginSpeculation() already de-duplicates by URL.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

Extended: the worker now starts your windows' documents while the server is still building the shell

Same collaboration, applied to boot instead of hover — and this is the bigger half.

A shell boot is two independent server renders run strictly one after the other. Measured on openstation.blog before this change:

    0ms ─── shell document requested
 3172ms ─── shell HTML arrives (3.2s of server time)
 3876ms ─── only NOW is a window document requested
 6491ms ─── everything ready

The window's document does not depend on a single byte of the shell's. It simply cannot be asked for until the shell's HTML has arrived and its JavaScript has run and built an iframe. And the shell can never fix this from inside itself: by the time its code exists, the 3.2 seconds are already spent.

The service worker can. It is woken by the shell's own navigation — before the server has finished building it — so it can start the window fetches right then, in parallel. It only needs to know what to fetch, which is what the session saver now tells it: every save posts the restore list, the worker persists it to a cache, and the next boot replays it the moment the shell navigation arrives.

Measured, same site, same session:

Before After
Window document TTFB 1,353 ms / 1,247 ms 9 ms / 5 ms → 1 ms / 1 ms
First window ready 5,861 ms 3,323 ms / 3,309 ms
Whole shell boot (loadEventEnd) 6,492 ms 4,736 ms / 4,700 ms

~1.8 s off every boot, and the first window usable 2.5 s sooner. The window documents now arrive effectively instantly, because they were fetched alongside the shell rather than after it.

The bug the measurement caught

The first live run was suspicious: one window's TTFB halved (1,353 → 687 ms) while the other sat unchanged at 1,246 ms. The cause was a wrong assumption of mine — replayedThisBoot was a boolean, but a service worker outlives any single page load; it stays resident across navigations and can be reused for hours. So the replay fired on the first shell load that worker ever saw and never again. Replaced with a short time-based throttle, which is all it ever needed since beginSpeculation() already de-duplicates by URL. The numbers above are after that fix.

Reuses the speculative store wholesale, including the in-flight promise semantics, so a window whose iframe appears mid-fetch waits on the request already running rather than starting a second. Same safety rules throughout: same-origin, /wp-admin/ only, chromeless flag required, nothing carrying action/_wpnonce/delete_all, capped and short-lived, gated on the same opt-in — and fire-and-forget, so a boot never waits on speculation. Zero console errors across the runs.

1. The shell's `asked` set silently killed the feature after first use.
   It was never cleared in production, but the worker's held document
   is single-use and expires after 30s - so once a tab had been
   speculated once, whether the click consumed it or it simply timed
   out, every later hover over that tab fell through to a plain
   navigation with no speculation at all. Users bounce between the same
   few screens constantly, so the repeat visits were exactly what the
   feature should accelerate and exactly what it abandoned. Replaced
   with a 1s throttle: enough to damp a pointer crossing a tab's icon
   and label, far shorter than the worker's hold, so a genuine return
   visit always gets through. The worker remains the real
   de-duplicator.

2. docs/pwa.md now documents the whole surface - both message types,
   the config flag, the new interception path, the safety rules and the
   measured numbers - alongside the existing shared-asset-cache
   section, per the doc map in AGENTS.md.

3. Real test coverage for the load-bearing parts, which had none.
   `isSpeculatableDocument` moved to sw-policy.ts and the store to a new
   speculative-store.ts, both pure and now directly tested: the
   action/nonce denylist that keeps a hover from ever performing a state
   change, the promise-vs-settled-response semantics that burned the
   first implementation, single-use taking, TTL expiry, oldest-first
   eviction, and the shell-side origin check and throttle. 15 new cases.

Also documents two deliberate choices the review flagged: pointerover
over pointerenter (the latter does not bubble, so it cannot be
delegated, and tabs come and go too often to bind per tab), and the
speculative fetch not forwarding Referer / Accept-Language (admin
screens do not branch on either; fabricating headers we never received
would be guessing).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

Review fixes pushed (b339274e)

1. The asked set — you were right, and it was worse than a missed optimisation. It silently disabled the feature after first use. Never cleared in production, while the worker's copy is single-use and 30 s TTL'd — so once a tab had been speculated once, whether the click consumed it or it simply timed out, every later hover over that tab fell through to a plain navigation with no speculation at all. Since users bounce between the same few screens constantly, the repeat visits were exactly what the feature should accelerate and exactly what it abandoned.

Replaced with a 1 s throttle: long enough to damp a pointer crossing a tab's icon and label, far shorter than the worker's hold, so a genuine return visit always gets through. The worker stays the real de-duplicator (beginSpeculation() ignores a URL it already holds), which is what the original comment claimed and the set contradicted.

2. docs/pwa.md now carries the whole surface: a row in the caching-policy table, a "Speculative documents (opt-in)" section covering both triggers, the safety rules, the measured numbers, and the worker message shapes (os-speculate-doc, os-remember-session) plus the windowPrewarm preamble flag.

3. Real coverage for the load-bearing parts. To make them testable rather than test around them:

  • isSpeculatableDocument moved to sw-policy.ts (pure, already the home of the other policy predicates).
  • The store moved to a new speculative-store.ts — a small class with an injectable clock.

15 new cases in tests/vitest/speculative-documents.test.ts covering: the action/action2/_wpnonce/nonce/delete_all denylist that keeps a hover from ever performing a state change; the chromeless-flag requirement; promise-vs-settled-response semantics (the 5 ms / 1,001 ms bug — a claim taken mid-flight still resolves to the response); single-use taking; TTL expiry; oldest-first eviction past the cap; and shell-side origin rejection, no-controller no-op, and the throttle-then-allow behaviour that pins issue 1 so it cannot regress silently.

Minor notes, both now documented in code rather than left implicit:

  • pointerover over pointerenter is deliberate — pointerenter does not bubble so it cannot be delegated, and tabs come and go too often to bind per tab. The extra events are absorbed by the throttle and the worker's de-duplication.
  • The speculative fetch not forwarding Referer / Accept-Language is a considered tradeoff: admin screens do not branch on either (locale is server-side from the user profile), and fabricating headers we never received would be guessing. If a screen ever did vary by them, the fix is to exclude that screen, not to invent headers.

Full suites green after the refactor: 4,987 JS (was 4,972), 2,495 PHP, typecheck, lint, phpcs, build. Re-verified live on openstation.blog that the extraction changed no behaviour — boot still shows window-document TTFB of 1 ms / 2 ms and a 4,850 ms shell load, with zero console errors.

@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

Verified live: the repeat-visit fix works, and the "missing tabs" was my test harness, not a bug

On the tab strip. I chased this as a possible pre-existing bug and it is not one — the product is correct and I was measuring wrong. Restored windows carry their submenu tabs properly (options_general_php restores with submenu.length: 10 and 11 tabs rendered), because src/boot/session.ts resolves the owning dock entry and passes submenu: dockEntry?.submenu.

The empty strips I kept hitting came from my own harness calling windowManager.open({ id, url, title }) without submenu — something the dock never does (dock.ts always passes item.submenu). A window opened with no submenu correctly has no submenu tabs. Opening it the way the dock does gives 11 tabs immediately. No fix needed; nothing to change.

On the actual fix (issue 1), measured on openstation.blog using a dock-shaped open:

Visit Hover Click → ready
Writing, 1st visit 2.5 s 999 ms
Reading (control) none 1,999 ms
Writing, 2nd visit 2.5 s 1,002 ms
Permalinks (control) none 2,000 ms
Writing, 3rd visit 2.5 s 995 ms

Before the fix, the 2nd and 3rd visits to Writing would have been silent no-ops falling through to a plain ~2 s navigation, because the URL was already in the permanent asked set. They now behave identically to the first visit. That is precisely the "users bounce between the same few submenu tabs repeatedly" case you called out, and it is worth roughly 2× on every visit, not just the first.

Controls in the same session confirm the baseline hasn't moved: un-hovered clicks still land at ~2.0 s.

@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

@claude would you mind one second review?

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @AllTerrainDeveloper's task in 4m 10s —— View job


Second review

  • Re-read speculate.ts / speculative-store.ts — confirm the repeat-visit throttle fix
  • Read the boot-replay extension (sw.ts, session-saver.ts)
  • Read docs/pwa.md update
  • Read new test coverage (speculative-documents.test.ts)
  • Post review feedback

The fixes from the first pass hold up. lastAskedAt is genuinely a throttle now (1s), not a permanent set — verified the worker's own speculative.has() is still the real de-duplicator and the new test (throttles a burst over one tab, then lets a later visit through) pins exactly the regression that was found live. The promise-vs-settled-response store, single-use take(), TTL expiry, and oldest-first eviction all have direct unit coverage now, and isSpeculatableDocument's denylist is tested against every acting query key. docs/pwa.md covers both triggers, the safety rules, and the worker message shapes. Good shape overall.

Two things worth a look on the new boot-replay half (session-saver.ts / sw.ts):

1. rememberRestoreTargets() isn't gated on the opt-in, unlike every other call site (src/boot/session-saver.ts:85-90)

rememberRestoreTargets(
    payload.windows
        .filter( ( w ) => ! w.native && w.url )
        .map( ( w ) => withChromelessParam( w.url ) || '' )
        .filter( Boolean ),
);

This fires on every session save, for every user with a controlling SW — no check against windowPrewarmEnabled. Compare speculateTabDocument (src/window/index.ts:157) and the dock's equivalent (src/dock.ts:2301), which both read wp.os.getOsSettings().windowPrewarmEnabled before doing anything. On the worker side, the os-remember-session handler (src/pwa/sw.ts:461-479) writes to SESSION_CACHE unconditionally too — only replayRestoreTargets() checks CONFIG.windowPrewarm before actually fetching anything, and only at boot.

Net effect: a user who has never touched the "hover prewarming" setting still pays a postMessage + Cache Storage write on every debounced session save. Nothing leaves the browser and the cost is small, but it contradicts the stated design ("Gated on the existing hover-prewarm opt-in... Off by default; zero behaviour change until a user opts in" — PR body and docs/pwa.md). Worth gating this call the same way the other two are gated, both for consistency and so "off by default" is actually true.

Fix this →

2. The unload path never updates the replay list (src/boot/session-saver.ts:134-168)

flushImmediately() — the pagehide / hidden-tab handler that fires when the user actually closes the window/tab — takes its own snapshot and sends it via sendBeacon, but never calls rememberRestoreTargets(). Only the debounced doSave() path does.

So the SW's restore-target cache reflects whichever debounced save last completed, not necessarily the state at the moment the tab closed. If a window closes and the tab exits before the 500ms debounce fires, the next boot's replay is working from a stale list (e.g. still speculating a document for a window the user just closed, or missing one opened right before exit). The actual session restore is unaffected (that goes through the accurate beacon), so this is a lost-optimization case rather than a correctness bug — but it's also exactly the moment ("close and immediately reopen") the feature is aimed at. Given rememberRestoreTargets() is already wrapped in its own try/catch and is best-effort by design, calling it from flushImmediately() too looks straightforward.

Minor

  • docs/pwa.md's new section says the list "is persisted from os-remember-session, which the session saver posts on every save" — worth tightening once/if ci: make npm run test:php actually work #2 is addressed, since today it's every debounced save, not the unload save.

Nothing else stood out — the Sec-Fetch safety argument still checks out against openstation_is_chromeless_request(), the denylist/TTL/cap/promise semantics all have direct tests now, and the throttle-vs-permanent-set distinction from the last review is solid.
· Branch: add/sw-speculative-documents

… path too

1. rememberRestoreTargets() fired on every session save regardless of
   the opt-in, unlike the two other speculation call sites which both
   read windowPrewarmEnabled first. A user who never touched the
   setting still paid a postMessage and a Cache Storage write on every
   debounced save - small, but it contradicted "off by default; zero
   behaviour change until a user opts in", which the PR body and
   docs/pwa.md both promise. Now gated the same way, in a shared
   noteRestoreTargets() helper, and gated again on the worker side so a
   stray message cannot make an opted-out browser start writing caches.

2. flushImmediately() - the pagehide beacon that fires when the tab
   actually closes - never updated the list, so the worker replayed
   whichever debounced save happened to land last. Close a window and
   exit before the 500ms debounce and the next boot speculates a
   document for a window that is gone, and misses one opened just
   before exit. Session restore itself was always accurate (that rides
   the beacon), so this was a lost optimisation rather than a
   correctness bug - but it is exactly the "close it and come straight
   back" case the feature exists for. Both paths now share the helper.

docs/pwa.md tightened to match: the list is posted from both save
paths, and the opt-in is checked on both sides.

Covered by a new test that drives the real session saver with the
toggle off and asserts no `os-remember-session` message is sent.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

Both fixed (e41f84a0)

1. The opt-in gate. You're right that this contradicted the stated design, and the contradiction was load-bearing — "off by default; zero behaviour change until a user opts in" appears in both the PR body and docs/pwa.md, and it simply wasn't true for this call. rememberRestoreTargets() now goes through a shared noteRestoreTargets() helper that reads windowPrewarmEnabled exactly as speculateTabDocument() and the dock's equivalent do.

I also gated the worker's os-remember-session handler on CONFIG.windowPrewarm, so an opted-out browser cannot be made to write caches by a stray message from anywhere. Belt and braces, but the claim is about what an opted-out user pays, and it should hold regardless of who is posting.

2. The unload path. Fixed, and I agree it's the case that matters most. flushImmediately() now calls the same helper before sending its beacon. Its snapshot is the most accurate one in the system — taken as the tab goes away, after the last window the user closed or opened — so replaying whichever debounced save happened to land last meant the next boot could speculate a document for a window that no longer exists and miss one opened seconds earlier. Exactly the "close it and come straight back" moment the feature is aimed at.

Both paths now share one helper, so they cannot drift apart again.

3. Docs tightened as you suggested, now that #2 is addressed: the list is posted from both save paths (debounced and pagehide beacon), with a note on why the unload one matters; and the opt-in line now says it is checked on both sides, with a user who never touches the setting not paying so much as a message.

Coverage: a new test drives the real session saver with the toggle off and asserts no os-remember-session is posted, so "off by default" can't silently regress the way the asked set did. Suites green: 4,988 JS, 2,495 PHP, typecheck, lint, phpcs, build. Deployed to openstation.blog.

@AllTerrainDeveloper
AllTerrainDeveloper merged commit 8090053 into trunk Aug 25, 2026
5 checks passed
@AllTerrainDeveloper
AllTerrainDeveloper deleted the add/sw-speculative-documents branch August 25, 2026 15:34
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.

1 participant