Add installable PlotDirector PWA with network-authoritative lifecycle

This commit is contained in:
Nick Beckley 2026-10-28 20:35:30 +00:00
parent bfa6a73e3f
commit db7d3b340e
14 changed files with 256 additions and 16 deletions

View File

@ -0,0 +1,76 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { chromium } = require('playwright');
const root = path.resolve(__dirname, '../../PlotLine/wwwroot');
let workerRevision = 1;
const server = http.createServer((req, res) => {
res.setHeader('Cache-Control', 'no-cache');
if (req.url === '/fixture') {
res.setHeader('Content-Type', 'text/html');
res.end(`<html data-app-theme="modern-light"><head><meta name="theme-color" content="#fff"><link rel="manifest" href="/site.webmanifest"><link rel="stylesheet" href="/css/application-shell.css"></head><body><input id="editor"><div hidden data-pwa-install-item><button data-pwa-install>Install</button></div><span data-pwa-status></span><script src="/js/application-pwa.js"></script></body></html>`);
} else if (req.url === '/service-worker.js') {
res.setHeader('Content-Type', 'application/javascript');
res.end(fs.readFileSync(path.join(root, 'service-worker.js'), 'utf8') + `\n// test deployment ${workerRevision}`);
} else if (req.url === '/private-data') {
res.setHeader('Cache-Control', 'no-store');
res.end('private fixture content');
} else {
const file = path.join(root, req.url);
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404).end(); return; }
res.setHeader('Content-Type', file.endsWith('.js') ? 'application/javascript' : file.endsWith('.css') ? 'text/css' : file.endsWith('.webmanifest') ? 'application/manifest+json' : 'image/png');
res.end(fs.readFileSync(file));
}
});
(async () => {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({ headless: true });
try {
const context = await browser.newContext();
const page = await context.newPage();
const base = `http://127.0.0.1:${server.address().port}`;
await page.goto(base + '/fixture');
await page.evaluate(() => navigator.serviceWorker.ready);
await page.waitForFunction(() => navigator.serviceWorker.controller);
const manifest = await (await context.request.get(base + '/site.webmanifest')).json();
assert.equal(manifest.start_url, '/Projects');
assert.equal(manifest.scope, '/');
assert.equal(manifest.display, 'standalone');
assert.equal(manifest.id, '/Projects');
for (const icon of manifest.icons) {
const dimensions = await page.evaluate(async src => { const img = new Image(); img.src = src; await img.decode(); return `${img.naturalWidth}x${img.naturalHeight}`; }, icon.src);
assert.equal(dimensions, icon.sizes);
}
for (const [theme, color] of Object.entries({ 'modern-light': '#f0f1f3', 'modern-dark': '#24272c', 'warm-light': '#f2e9dc', 'warm-dark': '#251e18' })) {
await page.evaluate(theme => { document.documentElement.dataset.appTheme = theme; window.dispatchEvent(new Event('plotdirector:theme-changed')); }, theme);
assert.equal(await page.locator('meta[name="theme-color"]').getAttribute('content'), color);
}
// Real worker upgrade must neither reload the editor nor persist fetched private data.
await page.fill('#editor', 'Unsaved manuscript fixture');
await page.evaluate(() => fetch('/private-data').then(r => r.text()));
workerRevision++;
await page.evaluate(async () => {
const changed = new Promise(resolve => navigator.serviceWorker.addEventListener('controllerchange', resolve, { once: true }));
await (await navigator.serviceWorker.getRegistration()).update();
await changed;
});
assert.equal(await page.inputValue('#editor'), 'Unsaved manuscript fixture');
assert.deepEqual(await page.evaluate(() => caches.keys()), []);
await context.setOffline(true);
assert.equal(await page.evaluate(() => fetch('/private-data', { cache: 'no-store' }).then(() => false, () => true)), true);
await context.setOffline(false);
// Browser supplies this event only when installable; exercise one-shot UI handling.
await page.evaluate(() => {
const event = new Event('beforeinstallprompt', { cancelable: true });
event.prompt = async () => { window.prompted = true; };
event.userChoice = Promise.resolve({ outcome: 'dismissed' });
window.dispatchEvent(event);
});
assert.equal(await page.locator('[data-pwa-install-item]').isVisible(), true);
await page.click('[data-pwa-install]');
assert.equal(await page.evaluate(() => window.prompted), true);
assert.equal(await page.locator('[data-pwa-install-item]').isVisible(), false);
console.log('PASS PWA: manifest/icons, four theme metadata values, real worker activation/update without lost edits, no Cache Storage, private data unavailable offline, install action.');
} finally { await browser.close(); await new Promise(resolve => server.close(resolve)); }
})().catch(error => { console.error(error); process.exitCode = 1; });

View File

@ -4,7 +4,8 @@
"test": "node timeline-metric-layout.cjs",
"test:locations": "node location-reparent.cjs",
"test:characters": "node character-enrichment-detail.cjs",
"test:toolbar": "node application-toolbar.cjs"
"test:toolbar": "node application-toolbar.cjs",
"test:pwa": "node application-pwa.cjs"
},
"devDependencies": {
"chart.js": "4.4.9",

View File

@ -294,6 +294,19 @@ public class Program
}
app.UseHttpsRedirection();
// Keep PWA metadata/worker revalidating even when served by static-asset endpoints.
app.Use(async (context, next) =>
{
if (context.Request.Path == "/service-worker.js" || context.Request.Path == "/site.webmanifest")
{
context.Response.OnStarting(() =>
{
context.Response.Headers.CacheControl = "no-cache";
return Task.CompletedTask;
});
}
await next();
});
app.UseStaticFiles();
var uploadStorage = app.Services.GetRequiredService<IUploadStorageService>();
app.UseStaticFiles(new StaticFileOptions

View File

@ -74,6 +74,8 @@
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="accountMenuButton">
<li><h2 class="dropdown-header">@User.Identity?.Name</h2></li>
<li hidden data-pwa-install-item><button type="button" class="dropdown-item" data-pwa-install>Install PlotDirector…</button></li>
<li><span class="visually-hidden" role="status" data-pwa-status></span></li>
<li><a class="dropdown-item" asp-controller="ManageAccount" asp-action="Index">Manage Account</a></li>
<li><a class="dropdown-item" asp-controller="Onboarding" asp-action="Index">Setup preferences</a></li>
@if (!(ViewData["ShellClass"] as string ?? "").Contains("marketing-shell", StringComparison.OrdinalIgnoreCase))

View File

@ -138,7 +138,10 @@
<link rel="icon" type="image/png" sizes="32x32" href="~/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="~/favicon-16x16.png" />
<link rel="apple-touch-icon" sizes="180x180" href="~/apple-touch-icon.png" />
<link rel="manifest" href="~/site.webmanifest" />
@if (isApplication || string.Equals(ViewContext.RouteData.Values["controller"]?.ToString(), "Account", StringComparison.OrdinalIgnoreCase))
{
<link rel="manifest" href="~/site.webmanifest" />
}
<meta name="msapplication-config" content="/browserconfig.xml" />
<meta name="msapplication-TileColor" content="#1F2A44" />
<meta name="theme-color" content="#1F2A44" />
@ -146,6 +149,7 @@
@if (isApplication)
{
<link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true" />
<script src="~/js/application-pwa.js" asp-append-version="true" defer></script>
}
</head>
<body class="@(User.Identity?.IsAuthenticated == true && !isMarketingPage ? "app-layout" : null)">

View File

@ -0,0 +1,61 @@
(() => {
const root = document.documentElement;
const installItem = document.querySelector('[data-pwa-install-item]');
const installButton = document.querySelector('[data-pwa-install]');
const status = document.querySelector('[data-pwa-status]');
const standalone = window.matchMedia('(display-mode: standalone)');
let installPrompt = null;
function updateMode() {
const installed = standalone.matches || navigator.standalone === true;
root.dataset.standalone = String(installed);
if (installItem) installItem.hidden = installed || !installPrompt;
}
function updateTheme() {
// The shell's tokens remain the only palette; theme changes include save rollback.
const color = getComputedStyle(root).getPropertyValue('--pd-chrome').trim();
if (color) document.querySelector('meta[name="theme-color"]')?.setAttribute('content', color);
}
window.addEventListener('plotdirector:theme-changed', updateTheme);
standalone.addEventListener('change', updateMode);
window.addEventListener('beforeinstallprompt', event => {
if (!installButton) return;
event.preventDefault();
installPrompt = event;
updateMode();
});
window.addEventListener('appinstalled', () => {
installPrompt = null;
updateMode();
if (status) status.textContent = 'PlotDirector installed';
});
installButton?.addEventListener('click', async () => {
if (!installPrompt) return;
const prompt = installPrompt;
installPrompt = null;
updateMode();
try {
await prompt.prompt();
await prompt.userChoice;
} catch {
if (status) status.textContent = 'Installation could not be opened. Use your browser’s app installation menu.';
}
});
updateMode();
updateTheme();
if ('serviceWorker' in navigator && window.isSecureContext) {
navigator.serviceWorker.register('/service-worker.js', { scope: '/', updateViaCache: 'none' })
.then(registration => {
// Each full navigation checks for updates; long-lived editors check on return.
// No controllerchange reload: unsaved work must remain undisturbed.
let checkedAt = Date.now();
registration.update().catch(() => {});
document.addEventListener('visibilitychange', () => {
if (!document.hidden && Date.now() - checkedAt > 60 * 60 * 1000) {
checkedAt = Date.now();
registration.update().catch(() => {});
}
});
})
.catch(() => { /* Installation enhancement must never block authoring. */ });
}
})();

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,12 @@
/* PlotDirector PWA foundation v1.
* Deliberately no fetch handler, Cache Storage, offline page, or background sync.
* All requests retain normal browser/network and authentication semantics.
* Shell assets use Razor content-version URLs; worker changes never reload editors.
*/
self.addEventListener('install', event => {
// Immediate activation is safe ONLY while this worker does not intercept requests.
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});

View File

@ -1,19 +1,19 @@
{
"id": "/Projects",
"name": "PlotDirector",
"short_name": "PlotDirector",
"description": "Your authoring workspace for books, characters and story planning.",
"start_url": "/Projects",
"scope": "/",
"display": "standalone",
"orientation": "any",
"lang": "en",
"background_color": "#f6f1e8",
"theme_color": "#f2e9dc",
"prefer_related_applications": false,
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#1F2A44",
"background_color": "#FAF8F5",
"display": "standalone"
{ "src": "/pwa/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "src": "/pwa/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "/pwa/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}

View File

@ -71,3 +71,5 @@ On smaller screens, title/context rows adapt, Quick Access scrolls horizontally,
The loopback fixture host renders the real compiled shell, editor, Calendar surface and Series Dashboard with in-memory preferences. It starts no application workers and accesses no live database. Browser coverage includes existing Quick Access behaviour, save failures/empty configuration, independent users/sessions, project/book links, asynchronous book changes, CSRF, category switching/keyboard access, collapse persistence, four themes, Dashboard values and narrow layouts. Screenshots go to `/tmp` and are not committed. Migration 202 is also tested twice in a disposable database, including preservation of Quick Access and explicit themes; the database is removed afterwards.
Phase 2: migrate individual feature-page components systematically to the new tokens after visual approval. Existing legacy feature-specific CSS remains intentionally outside this reference-page refresh. Audit the pre-existing Pkcs dependency advisories separately from visual work.
For installation, service-worker policy and OS integration, see [Installable application](installable-application.md).

View File

@ -0,0 +1,43 @@
# Installable PlotDirector application
PlotDirector uses the existing MVC application, cookie authentication and shared shell in both browser tabs and installed windows. No separate frontend, account system or database migration is required.
## Manifest and scope
`PlotLine/wwwroot/site.webmanifest` identifies the app as `/Projects`, launches `/Projects`, requests `standalone` display, and permits any orientation. Projects is an existing authenticated route: an expired session follows the normal Account/Login return-URL flow, including existing two-factor requirements. Logout remains the existing antiforgery-protected POST.
Scope is `/` because Projects, Books, Timeline, Account and the other MVC controllers occupy different root paths. Scope controls which navigations stay inside the app window; it is not a caching or authorisation boundary. External origins retain browser handling. No project-specific shortcuts or resume-page state are introduced.
The manifest is linked from authenticated application pages and Account pages so login remains part of the app identity. Public marketing pages do not advertise the manifest or load the PWA bootstrap. An already-registered worker can control same-origin public pages, but cannot intercept or cache them.
## Icons
`wwwroot/pwa/icon-192.png` and `icon-512.png` are rendered directly from the existing `favicon.svg` book artwork. `icon-maskable-512.png` has an opaque navy background and extra padding keeping the book within the maskable safe circle. Existing public favicons are unchanged. Regenerate from the repository root with `node tools/generate-pwa-icons.cjs` after installing the browser-test dependencies/Chromium. Only the final PNGs and reproducible generator are committed.
## Worker, caching and updates
`wwwroot/service-worker.js` is deliberately a lifecycle-only worker. It has **no fetch handler, Cache Storage, offline fallback, local manuscript store, background sync or push subscription**. Authenticated HTML, manuscript data, API responses, uploads and login/logout requests are never copied into a service-worker cache. Network and normal browser HTTP-cache semantics remain authoritative. There is no offline editing or offline promise: loss of connectivity can produce the browser's network error page.
`wwwroot/js/application-pwa.js` registers the worker from authenticated application pages only, at root scope with `updateViaCache: 'none'`. Program.cs gives the worker and manifest `Cache-Control: no-cache`, including when static-asset endpoints serve them. The browser checks registration on each full page load; the client also checks on return to a long-lived visible window after one hour. Updates are byte-compared by the browser. Change the worker's version comment when its responsibilities change.
The worker calls `skipWaiting` and `clients.claim` without forcing any page reload. This is safe because it does not intercept requests or impose an asset version on an existing document. Existing Razor `asp-append-version` content hashes select updated shell CSS/JS on the next navigation; there is no worker asset cache to invalidate or deployment identifier to synchronise. An already-open editor retains its current loaded code until normal navigation. Any future caching/fetch interception requires revisiting activation and an explicit user-safe update design.
## Installation and themes
Chromium's native install UI remains available. The account menu's small “Install PlotDirector…” button appears only after a real `beforeinstallprompt` event and outside standalone mode. The event is consumed once; dismissal does not trigger repeated prompts. `appinstalled` and `(display-mode: standalone)` changes hide the command. Unsupported browsers get no inactive installation control. Installation failure does not block authoring.
The same shell renders in standalone mode, with no added browser controls or fixed window dimensions. `data-standalone` records detection for future modest integration needs. iOS's `navigator.standalone` is also recognised.
The document's `theme-color` follows the existing `--pd-chrome` semantic token on initial load and every `plotdirector:theme-changed` event, including preference-save rollback. All four palettes therefore share one source of truth. The static manifest uses Warm Light defaults; the OS/browser may use those defaults for a launch splash before the authenticated document loads and may retain its own title-bar styling. No theme identifiers or account details are placed in public metadata.
## Testing and troubleshooting
Run the normal .NET build and executable regression harness, then `npm run test:pwa` in `PlotLine.Tests/Browser`. The focused browser test checks manifest/icon dimensions, all four theme colours, an actual service-worker upgrade preserving unsaved input, empty Cache Storage, private data failing offline, and install-event handling.
On HTTPS dev, sign in using Chrome/Edge, inspect Application > Manifest and Service Workers, and install using the address-bar action or account menu. Launch the installed app; confirm standalone display, project navigation, ribbon, Quick Access, modal, four themes, logout and login. Resize the window. Verify manifest/worker responses revalidate and Application > Cache Storage has no PlotDirector data caches. Windows Start/taskbar integration should additionally be visually reviewed on Windows; Linux Chromium automation cannot prove platform-specific icon placement.
For stale visuals, navigate/reload after saving work and inspect the CSS/JS content-version query strings and HTTP response. Inspect worker registration/update errors and ensure nginx preserves no-cache metadata headers. DevTools can update or unregister this origin's worker for diagnosis; do not clear cookies/site data unnecessarily, since that signs the author out and can remove unrelated browser preferences. This worker never requires a manual cache purge after ordinary deployments.
Reference: [Chromium installation debugging](https://developer.chrome.com/docs/devtools/progressive-web-apps) and [DevTools PWA automation](https://chromedevtools.github.io/devtools-protocol/tot/PWA/).
Future candidates include opt-in notifications, badging and context-free shortcuts. File handlers, share targets and especially offline editing need separate security, lifecycle and product designs.

View File

@ -0,0 +1,26 @@
// Run from the repository root after npm ci in PlotLine.Tests/Browser.
// Rasterise the established vector identity, never upscale the small favicon.
const { chromium } = require('../PlotLine.Tests/Browser/node_modules/playwright');
const fs = require('node:fs');
(async () => {
const browser = await chromium.launch({ headless: true });
try {
const page = await browser.newPage();
const svg = fs.readFileSync('PlotLine/wwwroot/favicon.svg', 'utf8');
for (const [name, size, maskable] of [['icon-192', 192, false], ['icon-512', 512, false], ['icon-maskable-512', 512, true]]) {
const data = await page.evaluate(async ({ svg, size, maskable }) => {
const icon = new Image();
icon.src = 'data:image/svg+xml;base64,' + btoa(svg);
await icon.decode();
const canvas = document.createElement('canvas');
canvas.width = canvas.height = size;
const ctx = canvas.getContext('2d');
if (maskable) { ctx.fillStyle = '#1F2A44'; ctx.fillRect(0, 0, size, size); }
const padding = maskable ? size * .125 : 0;
ctx.drawImage(icon, padding, padding, size - 2 * padding, size - 2 * padding);
return canvas.toDataURL('image/png').split(',')[1];
}, { svg, size, maskable });
fs.writeFileSync(`PlotLine/wwwroot/pwa/${name}.png`, Buffer.from(data, 'base64'));
}
} finally { await browser.close(); }
})();