Skip to content

Perf: shared admin-asset cache + hover window prewarming (opt-in), and the fixes that make the SW run on WordPress.com - #676

Merged
AllTerrainDeveloper merged 10 commits into
trunkfrom
add/pwa-admin-asset-cache
Aug 25, 2026
Merged

AllTerrainDeveloper merged 10 commits into
trunkfrom
add/pwa-admin-asset-cache

Conversation

@AllTerrainDeveloper

@AllTerrainDeveloper AllTerrainDeveloper commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Two opt-in performance features (both default off, behind OpenStation Preferences → Features → Beta features) plus two service-worker bug fixes that ride along — one of which makes the SW run on WordPress.com hosting for the first time ever. Everything below was measured live on openstation.blog (WordPress.com production hosting, real network) with in-page instrumentation; the full protocol and raw run data live in the branch-side engineering report.

Scope of the numbers in this description. Every measurement here is feature-off vs feature-on within the same shell — i.e. what this PR changes. It is not a comparison against classic wp-admin. That separate comparison was run afterwards and is in this comment, including the part that flatters us least: the shell is ~2–2.8 s slower to cold-start than a classic admin page (it loads its own document and bundles, then a full wp-admin screen inside a window), and it wins from the first revisit onward (1.7 ms window focus vs 1,632–2,822 ms per classic navigation). An earlier comment stated that comparison without the boot cost in it and is superseded — read the correction, not the original. Nothing in that thread changes the deltas below, which are measured on top of whichever baseline you pick.

What ships

  1. Shared admin-asset cache (adminAssetCacheEnabled, Experimental). The root-scope SW serves versioned admin assets — Core CSS/JS, the load-scripts.php/load-styles.php concat blobs, plugin/theme assets carrying ?ver= — from one origin-wide Cache Storage bucket shared by the shell and every window's chromeless iframe. Core paths are exact-URL cache-first (the ver param embeds the WP version — the same immutability contract Core expresses by serving the loaders with a one-year Cache-Control); plugin/theme assets are stale-while-revalidate so unversioned file edits self-heal on the next load; uploads, HTML, REST, AJAX and unversioned URLs are never touched. Bucket capped at ~500 entries (FIFO), version-keyed, flushed on every SW release. Policy is pure + unit-tested (src/pwa/sw-policy.ts). The per-user toggle is the filter default; openstation_pwa_admin_asset_cache can force or veto site-wide.
  2. Hover-intent window prewarming (windowPrewarmEnabled, Experimental). A 180 ms mouse dwell on a dock tile builds that page's window hidden — the iframe loads while the user decides — and the real click adopts it: reveal, stack, focus, os-window-opened fired exactly then. The speculative window lives in a single slot outside the window stack, so sessions, taskbar, dock peek and Alt-Tab never see it; unclaimed prewarms self-destruct after 45 s with the close callback detached (no phantom events). Excluded by design: native windows, cross-origin URLs, native-remapped URLs.
  3. Bug fix — the SW never ran on WordPress.com. The platform's nginx short-circuits .js-looking paths to the filesystem, so the virtual /openstation/sw.js route 404'd before WordPress executed — silently, on every WP.com install. The same bytes are now also served at the extensionless /?openstation_sw=1 (path / grants root scope natively), and registration retries with PwaConfig.swFallbackUrl on failure. Verified live: openstation.blog registered through the fallback on its own, first SW execution ever on this host class.
  4. Bug fix — stale own SW blocked its successor forever. The foreign-SW guard compared full script URLs, so a browser holding a pre-portal-move registration (/desktop-mode/sw.js, which now serves HTML and can never self-update) was stuck on a dead worker, observed live. Own legacy script URLs are now recognized and replaced by registering the current URL at the same scope; genuinely foreign SWs still block.

Measurements (openstation.blog, production)

Measurement Without With Factor
Asset network requests per window open (cache on, warm bucket) 117–143 0 —
Per-asset fetch, browser-cold 176–260 ms 0.8–2.3 ms ~100×
79 KB load-styles.php concat blob (PHP-generated per miss) 277 ms median (254–521 ms) 4.3 ms ~65×
load-scripts.php blobs 188–219 ms median (peaks 504 ms) 3–4.4 ms ~50×
Cold window open, asset network time (modeled from measured per-request costs, 117 assets / 6 connections) ~3.7 s < 0.5 s ~8×
Window open → content loaded, prewarm hit 2,000 ms 3.3 ms ~600×
Document TTFB per window (SW-exempt by design: nonces) 681–1,736 ms unchanged — this is what prewarming hides —
Boot cost with toggles off (bin/boot-cost.mjs, baseline vs branch) 190 requests / 518.4 KB document +0 requests / +0.01% / +0.05% gz assets —

Integrity: SW-served bodies were byte-identical to network fetches in every comparison run (core assets, plugin assets, and concat blobs). Cross-window sharing observed directly: a first-ever tools.php open started with 38/114 assets already bucketed by a different page's window, and plupload.min.js returned in 2 ms on a nominally cold fetch because another page had cached it.

Worst case: parity — and why that trade is worth it

For users who never opt in, the worst case is nothing: measured +0 requests and +0.01% document on boot, zero behavior change. For opted-in users, the worst case is parity, not regression: on a warm browser against well-configured hosting, steady-state reopens measured 1,589 ms (cache on) vs 1,657 ms (off) — inside run-to-run noise, because the browser's own HTTP/memory cache already absorbs a warm steady state and parse/execute dominates. No measured scenario got slower than baseline. The bounded costs that do exist: a one-time ~400 ms populate pass on the first open after enabling (1,979 vs 1,589 ms, then gone); one speculative server-side page render per hover-intent (single slot, 45 s TTL) — the explicit trade the prewarm toggle buys; and a plugin that edits files without bumping its version serves one stale load before stale-while-revalidate self-heals, which is no worse than any far-future-cache host already treats such plugins.

The upside side of that trade is every case where the browser cache doesn't help — first visit of the day, evicted disk cache, hard reload, high-latency links, offline — where the measured per-request delta is two orders of magnitude, and window opens go from seconds to milliseconds on a prewarm hit. Parity in the best-case scenario, large wins in every degraded scenario, zero cost when dark: that is the definition of a worthwhile opt-in.

One thing this PR explicitly does not fix, now that it is measured: the shell's ~6.3 s cold boot (vs 2.6–4.4 s for a classic admin page). Prewarming hides per-window document cost after boot; it does nothing for boot itself, and the asset cache is cold on a first-ever visit by definition. That number is the obvious next target and is called out in the report rather than left implied.

Testing

  • 14 new vitest cases: sw-policy classification matrix, SW-register fallback + legacy-recognition, window prewarm lifecycle (hidden mount, adoption, URL-mismatch discard, silent teardown, single slot, TTL). Full suite: 4,916 passed.
  • 11 new PHPUnit tests: filter/default/coercion for both settings, config preamble emission, fallback endpoint routing. Full suite green.
  • npm run lint, lint:php, typecheck, build all green; bin/boot-cost.mjs before/after diff attached above.
  • Deployed and exercised live on openstation.blog throughout development (both toggles, SW fallback registration, concat path via a temporary server-side shim since page-optimize normally replaces core concat).

Docs

docs/pwa.md (caching policy table, shared-cache section, WP.com hosting note, fallback URL), docs/hooks-reference.md (new filter + helpers), docs/javascript-reference.md (windowManager.prewarm()/discardPrewarmed(), both getOsSettings() keys) — all updated in the same commits as the code.

🤖 Generated with Claude Code

Open WordPress Playground Preview

AllTerrainDeveloper and others added 5 commits August 25, 2026 09:00
Part one deletes the three pre-1.0 migration notes (async
windowManager, AI comment-only, AI connectors), renumbers the docs
index, and rewords every remaining sub-1.0 version stamp -- the
architecture section loses its release-numbered title, and prose like
"pre-0.9.6 behavior" now describes the behavior instead of the
release.

Part two is a point-by-point accuracy audit of all 101 doc pages
against the source, fixing 133 confirmed discrepancies. The majors:
hooks-reference had two script-registration claims and one
permission-filter effect inverted; javascript-reference carried five
localStorage keys under never-shipped os-* spellings, renamed
os.os-theme.* hook strings, and an activity-channel catalog for
channels that don't exist; files-on-desktop's nginx hardening snippet
pointed at uploads/os-files/ while bytes live under the frozen
uploads/desktop-mode-files/; native-windows-proposal named the legacy
global wrongly in both directions; several examples could not work as
pasted (a windowId comparison against the DOM-element prefix, a filter
subscription under a renamed hook, imports from package subpaths that
don't exist, a settings-tab id the validator rejects). Counts,
defaults, tab orders, status labels, and anchors are trued up
throughout, undocumented WindowManager methods joined the catalog, and
scope notes now cover extension hooks and internal hook names.

The wiki mirror re-syncs from docs/ on merge; conversion verified
clean at 101 pages with zero unresolved links.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The root-scope SW now (opt-in) serves versioned admin static assets from
one origin-wide Cache Storage bucket shared by the shell and every
chromeless iframe window. Core-path assets and the load-scripts.php /
load-styles.php concat responses are exact-URL cache-first (their ver=
embeds the WP version); plugin/theme assets are stale-while-revalidate;
uploads, unversioned URLs, HTML, REST and AJAX are never touched.

Policy decisions live in src/pwa/sw-policy.ts (pure, unit-tested). The
per-user opt-in is the "Shared asset cache (experimental)" toggle in
OpenStation Preferences -> Features -> Beta features, persisted as
adminAssetCacheEnabled; the openstation_pwa_admin_asset_cache filter
takes that preference as its default and can force or veto site-wide.
The value reaches the SW as a self.__OS_SW_CONFIG preamble injected by
the PHP serve endpoint, so flipping it triggers a normal SW update with
no URL change. The preamble also carries the real plugin URL, replacing
the hardcoded pluginAssetBase() fallback for non-default layouts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…s paths

WordPress.com's nginx short-circuits paths with a static-file extension
straight to the filesystem, so the virtual /openstation/sw.js route
404s before WordPress runs and the service worker has never been
servable there (the extensionless manifest route was unaffected). Serve
the same bytes at /?openstation_sw=1 — no extension, always reaches
WordPress, and the script URL's / path grants root scope natively.
Registration tries the pretty URL first and retries once with
PwaConfig.swFallbackUrl; the foreign-SW guard recognizes both script
URLs as OpenStation's own so a fallback-registered worker is not
mistaken for a foreign SW on the next boot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…e the click

A sustained mouse hover on a dock tile is a strong predictor of the
next click, and the document TTFB of an admin page (measured at
0.7-1.7s on production hosting) is the dominant cost of a window open.
When the new "Prewarm windows on hover" Beta toggle is on, the dock
asks the window manager to build that page's window hidden after a
180ms hover dwell; a later open() for the same page adopts it -
reveal, stack, focus, os-window-opened - so the window appears with
its document already loading or loaded.

The speculative window lives in a single-slot cache OUTSIDE the stack,
so session snapshots, the taskbar, dock peek and Alt-Tab never see it
and no os-window-* event fires until adoption; discarding (TTL 45s,
eviction by a newer prediction, URL mismatch at open) detaches the
close callback first so teardown announces nothing. Boot cost is
unchanged (+0 requests, +0.01% document, +0.05% gzipped assets vs
baseline via bin/boot-cost.mjs) and the toggle defaults off.

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

The foreign-SW guard compared full script URLs, so a browser that
installed the PWA before the portal-path move held a registration
pointing at the old /desktop-mode/sw.js endpoint - which now serves an
HTML page and can never self-update - and the guard mistook our own
stale worker for another plugin's, refused to register, and stranded
the user on a dead SW forever (observed live on a dev profile: a
pwa-5 worker from the legacy path blocking every boot).

Own script URLs are now matched as the current pretty URL, the
extensionless fallback, or a legacy endpoint suffix (subdirectory
installs included); a match means "ours but stale", and registering
the current URL at the same scope replaces it - the exact recovery a
dead worker needs. Genuinely foreign SWs still block with the same
console warning.

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

Copy link
Copy Markdown
Collaborator Author

Follow-up measurement: OpenStation vs classic wp-admin, head to head

Measured on openstation.blog after the PR was opened — same host, same browser session, warm cache on both sides. Classic admin reached via the plugin's own ?desktop_mode_classic=1 escape hatch (vanilla wp-admin, shell suppressed), so this is like-for-like on identical hosting.

Action Classic wp-admin OpenStation
Load Settings (options-general.php) TTFB 843 ms · DCL 1,742 ms · load 2,822 ms · 146 subresources first open ~1,589–1,979 ms; 3.3 ms on a prewarm hit
Load Tools (tools.php) TTFB 965 ms · DCL 1,323 ms · load 1,632 ms · 147 subresources as above
Return to a screen already visited full navigation again — 1,632–2,822 ms, every time 1.7 ms median, 5.6 ms max (window focus)

The last row needs no feature flags and is the structural argument for the shell itself: classic wp-admin discards the document on every click, so revisiting a screen costs what visiting it cost the first time (server re-render + ~146 subresources re-evaluated). OpenStation keeps windows alive, so a revisit is a focus call — a ~1,000× difference on the most common interaction in the admin, true today with both toggles off.

This PR's two features attack what remains, i.e. first opens of new screens: the shared asset cache takes the network out of the asset bill (~3.7 s → <0.5 s cold), hover prewarming takes the document wait out of the click (2,000 ms → 3.3 ms). Full protocol and raw data in the branch-side engineering report (Part 4).

@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

Correction to the head-to-head numbers above: the shell's cold start belongs in the comparison

The previous comment compared classic cold document loads against OpenStation window opens measured inside an already-booted shell — an asymmetry, since the shell's own boot cost sat outside the table. Measured properly on openstation.blog, fresh navigations both sides:

Action Classic wp-admin OpenStation
Cold start — admin from nothing (dashboard) TTFB 1,221–2,230 ms · load 2,619–4,364 ms · 209–216 subresources shell + bundles + dashboard window · load 6,253–6,279 ms · 228–229 subresources
Return to a screen already visited 1,632–2,822 ms, every time 1.7 ms median (5.6 ms max)

OpenStation is ~2–2.8 s slower to first usable screen. That is structural, not a regression in this PR: the shell loads its own document and bundles and then loads a full wp-admin screen inside a window — two documents where classic loads one.

Break-even on that boot, using measured inputs (classic ≈3.5 s cold dashboard / 2.8 s Settings / 1.6 s Tools; OpenStation 6.3 s boot, ~1.6 s new-screen open, 1.7 ms revisit):

Interaction Classic cum. OpenStation cum. Ahead
open the admin 3.5 s 6.3 s classic by 2.8 s
+ Settings 6.3 s 7.9 s classic by 1.6 s
+ Tools 8.0 s 9.5 s classic by 1.5 s
+ back to Settings 10.8 s 9.5 s OpenStation by 1.3 s (crossover)
+ back to Dashboard 14.3 s 9.5 s OpenStation by 4.8 s
+ Settings again 17.1 s 9.5 s OpenStation by 7.6 s

Crossover is the first revisit; prewarming pulls it one interaction earlier. Honest scope: the shell wins any session with at least one revisit, and loses a single-screen visit-and-leave. None of this changes what this PR does — the two features and the two SW fixes are all measured deltas on top of whichever baseline you pick — but the comparison should not have been stated without the boot cost in it. Report Part 4 and the blog draft have both been corrected, and reducing that boot is the obvious next target.

AllTerrainDeveloper and others added 2 commits August 25, 2026 13:32
A window renders a real admin page with the admin bar suppressed -
show_admin_bar returns false and wp_admin_bar_render is removed from
in_admin_header - so #wpadminbar never reaches the DOM. WordPress and
the host still enqueued the bar's scripts and styles, which loaded,
parsed and executed against markup that does not exist, once per
window, every window.

Measured on a live WordPress.com install, one Settings window: 48.8 KB
across eight assets plus three cross-origin round trips, none of which
could do anything. The largest single one was our own os-admin-bar
toggle bundle at 17.7 KB, now guarded at its enqueue site.

The trim dequeues the whole admin-bar family (core's admin-bar, ours,
and the masterbar extras) because leaving one queued drags core's
handle back in as its dependency. Handles are dequeued, never
deregistered: a script that genuinely declares one as a dependency
still resolves it and keeps working. Filters
openstation_chromeless_trimmed_{scripts,styles} and the
openstation_chromeless_trimmed_assets action let sites extend or opt
out. No-op outside chromeless - the shell draws a real admin bar.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The dequeue pass alone left half the admin-bar family standing on a
live install: WordPress.com's wpcom-notes-* handles enqueue after
admin_enqueue_scripts has run, and core's admin-bar stylesheet rode
back in as their dependency (WP_Dependencies::all_deps pulls a
dequeued-but-registered handle back when something queued still needs
it). print_scripts_array / print_styles_array run inside do_items()
after every enqueue, dequeue and dependency walk, so they are the last
word. Same handle list, so removing one member never strands another
that depended on it.

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

Copy link
Copy Markdown
Collaborator Author

Added: windows no longer load the admin bar they never draw

A window suppresses the admin bar entirely (show_admin_bar false + the wp_admin_bar_render removal), so #wpadminbar never reaches the DOM — but WordPress and the host kept enqueueing its scripts and styles, which loaded, parsed and executed against markup that does not exist. Once per window, every window.

Measured on openstation.blog, one Settings window, before:

Asset Size
admin-bar.min.css 20.9 KB
os-admin-bar.js (ours) 17.7 KB
admin-bar.min.js 3.4 KB
notes admin-bar-v2.js 3.1 KB (cross-origin)
notes admin-bar-v2.css 2.4 KB (cross-origin)
wpcom-admin-bar.js 0.6 KB
notes-common-lite.min.js 0.5 KB (cross-origin)
a8c-faux-inline-help.js 0.2 KB
Total 48.8 KB + 3 cross-origin round trips

After: all eight gone (verified live — adminBarAssetsStillLoading: []), scripts 109 → 101, stylesheets 19 → 18, s0.wp.com requests 5 → 2, page renders and its form works, zero console errors. The shell is untouched: it still has #wpadminbar, both scripts, the stylesheet and the OpenStation toggle node.

Two passes were needed, and the second one is the interesting part. Dequeuing at admin_enqueue_scripts removed only half the family: WordPress.com's wpcom-notes-* handles enqueue after that hook, and core's admin-bar stylesheet then rode back in as their dependency — WP_Dependencies::all_deps() pulls a dequeued-but-registered handle back when something still queued declares it. print_scripts_array / print_styles_array run inside do_items() after every enqueue, dequeue and dependency walk, so they are the last word.

Handles are dequeued, never deregistered, so a script that genuinely declares one as a dependency still resolves it. The whole family ships in the defaults because leaving one member queued undoes the trim. Extensible via openstation_chromeless_trimmed_scripts / ..._styles and the openstation_chromeless_trimmed_assets action.

Honest sizing: 48.8 KB out of ~5 MB of JavaScript that this (Gutenberg-plugin-heavy) site loads per window, so the wall-clock effect is inside this host's run-to-run noise — the win is the bytes, the parse/execute work, and the three cross-origin round trips, on every window a user ever opens. 10 new PHPUnit tests cover the defaults, both passes, the shell no-op, registration survival, and the filters.

…n the editor

WordPress's emoji detection script tests the browser against the newest
Unicode emoji set and, when anything is missing, pulls in
wp-emoji-release.min.js (Twemoji, 22 KB) to swap those characters for
images. It is a real polyfill rather than dead code - measured loading
on current Chrome inside a window, because browsers routinely lag the
newest emoji.

Dropping it in a window is still right, and Core sets the precedent
itself: wp-admin/edit-form-blocks.php removes this exact action on the
block-editor screen. The only loss is that a very new emoji in admin
content renders with the OS glyph instead of a Twemoji image, and the
shell hosting these windows already requires service workers, custom
elements, ES2020 and :has() - a browser clearing that bar does not need
help drawing emoji.

Removal runs on admin_init because wp_enqueue_emoji_styles rides
admin_enqueue_scripts at the default priority and has already fired by
the time the handle trim runs at PHP_INT_MAX. Filterable via
openstation_chromeless_trim_emoji.

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

Copy link
Copy Markdown
Collaborator Author

Emoji polyfill dropped in windows too — plus a correction

Correction first. My earlier note labelled the emoji script "never used in admin". That was wrong, and our own measurement disproves it: wp-emoji-release.min.js (22 KB) genuinely loaded inside a window on current Chrome. The inline detection script tests the browser against the newest Unicode emoji set and pulls in Twemoji whenever anything is missing — browsers routinely lag the newest emoji, so it fires in practice. It is a real polyfill, not dead code.

Dropping it in a window is still right, and Core sets the precedent itself: wp-admin/edit-form-blocks.php:42 runs remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ) on the block-editor screen. The only loss inside a window is that a very new emoji in admin content renders with the OS glyph instead of a Twemoji image — and the shell hosting these windows already requires service workers, custom elements, ES2020 and :has(). A browser clearing that bar does not need help drawing emoji.

Removal runs on admin_init, because wp_enqueue_emoji_styles rides admin_enqueue_scripts at the default priority and has already fired by the time the handle trim runs at PHP_INT_MAX — the same hook and reasoning as the admin-bar suppression in helpers.php. Filterable via openstation_chromeless_trim_emoji (default true).

Verified live on openstation.blog — window vs shell, same page load:

Window Shell
wp-emoji-release.min.js gone still loads ✅
_wpemojiSettings (inline detection) undefined defined ✅
admin-bar assets none all present ✅
#wpadminbar not rendered present ✅

Page renders, its form works, zero console errors.

Cumulative effect of this trim work, per window: scripts 109 → 100, stylesheets 19 → 18, JavaScript 5,063 KB → 4,892 KB, s0.wp.com round trips 5 → 2. That is ~71 KB and nine assets that no longer download, parse or execute in every window a user opens — while the shell keeps everything it actually draws. 13 PHPUnit tests now cover the module.

…er window

The bridge lived in a PHP nowdoc and was printed inline into every
chromeless window: ~125 KB of unminified JavaScript, comments and all,
landing in the HTML document. A document is the one asset no cache can
help with, so that cost was paid in full on every window open, forever.

The code moves verbatim to src/chromeless-bridge.js and builds to
assets/js/chromeless-bridge[.min].js (34.5 KB minified, 10.5 KB
gzipped) - fetched once, then served from the browser and the shared
service-worker cache for every later window. The four values that
genuinely vary per request (menu payload, menu signature, content
identity, soft-reload rules) are attached as a small inline `before`
block on window.__osChromelessData, replacing the str_replace pass over
placeholder comments.

in_footer plus a `before` inline block reproduces the old emission
exactly: data defined, then the bridge running, at the same point in
the document, with no defer/async that would move it after the page's
own footer scripts.

Also hardens the enqueue: WP_Dependencies::enqueue() silently no-ops on
an unregistered handle, and plugins that rebuild WP_Scripts wholesale
are a documented shape (see asset-guard.php). The bridge is the one
script a window cannot do without, so it re-registers if the handle has
gone missing.

Tests that assert on bridge behaviour now read the source that builds
into the bundle rather than slicing it out of the nowdoc.

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

Copy link
Copy Markdown
Collaborator Author

The chromeless bridge is a bundle now — the window document halved

Investigating "what else can we trim from a window?" turned up the biggest item in the page, and it was ours.

includes/render/chromeless-bridge.php held the bridge in a PHP nowdoc and printed it inline into every chromeless window: ~125 KB of unminified JavaScript, comments and all, the largest single block in the document. A document is the one asset no cache can touch, so that cost was paid in full on every window open, forever.

The code moves verbatim to src/chromeless-bridge.js and builds like every other bundle (34.5 KB minified, 10.5 KB gzipped). The four values that genuinely vary per request — menu payload, menu signature, content identity, soft-reload rules — are attached as a small inline before block on window.__osChromelessData, replacing the str_replace pass over placeholder comments. in_footer + before reproduces the old emission exactly: data defined, then the bridge running, same point in the document, no defer/async that would move it after the page's own footer scripts.

Measured live on openstation.blog, same Settings window:

Before After
Window document, transferred 76.4 KB 37.2 KB
Window document, uncompressed 339 KB 213.9 KB
Inline scripts in the document 285 KB 160 KB
Largest inline block 125 KB (ours) 66 KB (Jetpack's)
PHP file 3,990 lines 460 lines

Bridge verified functioning live: bundle served from cache (fromNetwork: false), window.__osChromelessData present with all four keys, fetch and XMLHttpRequest wrapped, tab strip built (11 tabs), window title reported, zero console errors.

Re-ran the Settings → Writing → Reading × 3 journey (the one that previously came out a tie): total 20.7 s → 19.4 s, median per screen 2.77 s → 2.30 s (−17%). It is now level with classic wp-admin's 19.4 s rather than behind it. Honest framing: halving the document moved the total by ~6%, because the bytes were never the expensive part — waiting for the server is. Every screen is simply delivered in half the bytes now.

One hardening that came out of the test suite: WP_Dependencies::enqueue() silently no-ops on an unregistered handle, and plugins that rebuild WP_Scripts wholesale are a documented shape (that is what asset-guard.php exists for). The bridge is the one script a window cannot do without, so it re-registers if the handle has gone missing. This was a genuine latent fragility, surfaced by a full-suite run where another suite's fixtures had rebuilt WP_Scripts.

Tests that assert on bridge behaviour now read the source that builds into the bundle rather than slicing it out of the nowdoc — 5 test classes updated. Full suites green: 4,916 JS / 2,435 PHP, phpcs, typecheck, lint, build.

@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

@claude can you review this?

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

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


Reviewing this PR

  • Read trigger comment and gather PR context
  • Check out branch and inspect diff vs origin/trunk
  • Review SW policy / caching logic (src/pwa/sw-policy.ts, src/pwa/sw.ts, src/pwa/sw-register.ts)
  • Review PHP additions (includes/pwa.php, includes/render/chromeless-trim.php, includes/admin-bar.php, includes/os-settings.php)
  • Review window prewarming (src/window-manager/index.ts, src/dock.ts)
  • Review chromeless bridge bundle extraction (includes/render/chromeless-bridge.php, src/chromeless-bridge.js)
  • Check docs updates match code changes
  • Post final review feedback

Note on process: this branch is a shallow checkout with no merge-base against origin/trunk in this sandbox, so I reviewed by reading the files directly on the checked-out branch (cross-referenced against the file list/stats in the PR body) rather than via git diff origin/trunk...HEAD. I did not run the build/lint/test suite (not wired into my --allowedTools here) — the PR body's reported results (4,916 JS / 2,435 PHP passing) are taken at face value.


Overall

This is a well-engineered PR — the policy/effect split (sw-policy.ts pure + unit-tested vs. sw.ts owning Cache Storage side effects), the prewarm single-slot design with TTL + adoption/discard semantics, and the two-pass chromeless-asset trim (dequeue + print_*_array filter to catch late-enqueue/dependency pull-back) are all careful, well-commented, and backed by real regression narratives. Docs (hooks-reference.md, javascript-reference.md, pwa.md) are updated in lockstep with the code. A few small things worth a look:

1. Dead condition in src/dock.ts:2270

if ( ! item.url || ( item.windowId && ! item.url ) ) {

The second clause (item.windowId && ! item.url) can never independently make this true — if ! item.url were true, the || short-circuits before reaching it; if item.url is truthy, ! item.url is false and kills the clause anyway. This reduces to if ( ! item.url ). Harmless today, but worth cleaning up so a future reader doesn't spend time reverse-engineering intent that isn't there.
Fix this →

2. src/chromeless-bridge.js ships as plain JS, not TS
The bridge (3,555 lines) is the single largest client asset in the repo and now builds via its own Vite target (vite.config.js:287), but tsconfig.json's include is src/**/*.ts and the lint scope per AGENTS.md is also src/**/*.ts — so this file gets zero typechecking and zero ESLint coverage, same as the PHP nowdoc it replaced. That's not a regression (the old nowdoc had the same blind spot, arguably worse since PHPCS also couldn't see inside a JS-in-PHP string), and a verbatim move minimizes risk for this PR. But AGENTS.md's stated reason for the "TS source only" rule — "no TS-checked types, a silent class of bug" — applies exactly to this file now that it's a first-class bundle. Worth a follow-up to convert it to .ts so it gets the same safety net as every other bundle.

3. Stale top-of-file comment in tests/vitest/chromeless-bridge-links.test.ts:1-26
The file-level docblock still opens with "The interceptor is JavaScript emitted from a PHP heredoc" — accurate before this PR, but the function-level comment at line 40 (correctly updated) now says the bridge "lives in src/chromeless-bridge.js". Minor doc drift within the same file; worth aligning the top block with the corrected one below it.

4. Extensionless SW fallback endpoint matches on query alone (includes/pwa.php:239-245)
openstation_pwa_endpoint_kind() treats any path with ?openstation_sw=1 as the SW endpoint, not just /. Not a security issue (it always serves the same static bundle read from disk, never reflects request-controlled content), and the JS side only ever requests it at home_url('/'), but it's slightly more permissive than the docblock implies ("serves the same bytes at /?openstation_sw=1"). Purely cosmetic — not blocking.

Things done well, worth calling out

  • readSwConfig() fails closed (feature off, conventional path) on any malformed/missing preamble — right default for a cache-poisoning-adjacent surface.
  • isOwnSwScriptUrl() correctly distinguishes "our own stale registration" from "foreign SW" by suffix-matching legacy endpoints, with a clear extension point (OWN_LEGACY_SW_PATH_SUFFIXES) for future endpoint moves.
  • The admin-asset cache correctly excludes range requests, opaque/redirected/no-store responses, and uploads — the failure modes that would have been silent and nasty (corrupted byte-range responses, stale nonce-adjacent bodies) are explicitly guarded and unit-tested.
  • Prewarm correctly narrows to same-origin, non-native, non-remapped URLs, and the single-slot + 45s TTL + detached-close-callback discard avoids the two obvious leaks (unbounded speculative windows, phantom close events).
  • Both new toggles default off and are gated behind Beta features, consistent with the "worst case is parity, not regression" framing in the PR description.

Nothing here blocks merging — these are polish-level notes on an otherwise solid, well-tested change.

…stale docblock

Four review findings, three of them small:

1. dock.ts hover-prewarm guard: `! item.url || ( item.windowId && ! item.url )`
   reduced to `! item.url`. The second clause could never
   independently be true - the `||` short-circuits when `! item.url`
   holds, and the clause is false otherwise. A native-window tile is
   exactly the `! item.url` case, so the check is unchanged in effect;
   the comment now says that instead of the code implying it.

2. chromeless-bridge.js now has ESLint coverage via an override
   (espree, no type-aware rules), and `npm run lint` includes it. The
   ES5-style rules are off for this file: it deliberately runs as ES5
   inside a real wp-admin document, and auto-fixing 3,500 lines of a
   verbatim lift would rewrite working code for taste - `no-var` in
   particular changes binding semantics around closures. Enabling the
   rest surfaced no undefined names and no unused bindings; the four
   real findings are fixed here (a shadowed `ev`, a shadowed loop
   index, a `var` shared across two mutually-exclusive branches, and a
   useless `return`). The TypeScript conversion stays a follow-up, and
   the file header now says so rather than leaving the gap implicit.

3. The extensionless SW endpoint matched `?openstation_sw=1` on any
   path. It is now pinned to the site root - the one URL
   openstation_pwa_sw_fallback_url() builds and the only one
   registration requests. Harmless before (the handler streams a
   static file and reflects nothing), but wider than the documented
   contract, and a worker's scope comes from the path it is served
   from.

4. The bridge-links test's top docblock still described the interceptor
   as "emitted from a PHP heredoc", contradicting the corrected
   comment below it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@AllTerrainDeveloper
AllTerrainDeveloper merged commit f801660 into trunk Aug 25, 2026
5 checks passed
@AllTerrainDeveloper
AllTerrainDeveloper deleted the add/pwa-admin-asset-cache branch August 25, 2026 13:28
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