Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): add PWA app shell with service worker
joshistoast388637205775
diff --git a/invokeai/frontend/webv2/index.html b/invokeai/frontend/webv2/index.htmlindex a5720ff578..c786e1a025 100644--- a/invokeai/frontend/webv2/index.html+++ b/invokeai/frontend/webv2/index.html@@ -3,7 +3,10 @@<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="theme-color" content="#16181d" /><title>Invoke V7 Workbench</title>+ <link rel="icon" href="./invoke-icon.svg" type="image/svg+xml" />+ <link rel="manifest" href="./manifest.webmanifest" /><script>// Apply the saved theme before first paint so non-default themes don't// flash the default dark surfaces. ThemeController re-applies it on mount.diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 9ac7b9e6dc..87eb8faca4 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,15 +2,15 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 832217,+ "brotliBytes": 832275,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 832184,+ "gzipBytes": 832279,"imageRawBytes": 156376,- "initialRawBytes": 1934317,+ "initialRawBytes": 1934798,"largestAssetRawBytes": 746305,"otherAssetRawBytes": 0,- "ownedRawBytes": 66817,+ "ownedRawBytes": 67298,"requestCount": 41,"scriptRequestCount": 25,"sourceOwners": [@@ -174,6 +174,7 @@"source:src/platform/i18n/client.ts","source:src/platform/i18n/languages.ts","source:src/platform/performance/semanticReady.ts",+ "source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/useMountEffect.ts","source:src/platform/react/useZodForm.ts",@@ -280,15 +281,15 @@]},"limits": {- "brotliBytes": 840540,+ "brotliBytes": 840598,"cssRawBytes": 2181,"fontRawBytes": 221675,- "gzipBytes": 840506,+ "gzipBytes": 840602,"imageRawBytes": 157940,- "initialRawBytes": 1953661,+ "initialRawBytes": 1954146,"largestAssetRawBytes": 753769,"otherAssetRawBytes": 0,- "ownedRawBytes": 66817,+ "ownedRawBytes": 67298,"requestCount": 41,"scriptRequestCount": 25},@@ -298,15 +299,15 @@},"editor": {"baseline": {- "brotliBytes": 1031650,+ "brotliBytes": 1032129,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1029036,+ "gzipBytes": 1029460,"imageRawBytes": 156376,- "initialRawBytes": 2530634,+ "initialRawBytes": 2531682,"largestAssetRawBytes": 746305,"otherAssetRawBytes": 0,- "ownedRawBytes": 111432,+ "ownedRawBytes": 112318,"requestCount": 89,"scriptRequestCount": 73,"sourceOwners": [@@ -419,6 +420,7 @@"package:use-sync-external-store","package:zod","package:zustand",+ "source:src/app/BootWidgetHintController.tsx","source:src/app/GalleryUiAdapter.tsx","source:src/app/GenerateWidgetSyncRuntime.tsx","source:src/app/GenerationUiAdapter.tsx",@@ -662,6 +664,7 @@"source:src/workbench/WorkbenchWidgetRegistryContext.tsx","source:src/workbench/activeInvocationSubmission.ts","source:src/workbench/autoRoutePolicy.ts",+ "source:src/workbench/bootWidgetPreload.ts","source:src/workbench/canvas-engine/api.ts","source:src/workbench/canvas-engine/capabilities.ts","source:src/workbench/canvas-engine/document/sources.ts",@@ -833,15 +836,15 @@]},"limits": {- "brotliBytes": 1041967,+ "brotliBytes": 1042451,"cssRawBytes": 2181,"fontRawBytes": 221675,- "gzipBytes": 1039327,+ "gzipBytes": 1039755,"imageRawBytes": 157940,- "initialRawBytes": 2555941,+ "initialRawBytes": 2556999,"largestAssetRawBytes": 753769,"otherAssetRawBytes": 0,- "ownedRawBytes": 111432,+ "ownedRawBytes": 112318,"requestCount": 89,"scriptRequestCount": 73},diff --git a/invokeai/frontend/webv2/public/invoke-icon.svg b/invokeai/frontend/webv2/public/invoke-icon.svgnew file mode 100755index 0000000000..bedc563dde--- /dev/null+++ b/invokeai/frontend/webv2/public/invoke-icon.svg@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">+<svg width="100%" height="100%" viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;">+ <path d="M16,2C16,0.896 15.104,0 14,0L2,0C0.896,0 0,0.896 0,2L0,14C0,15.104 0.896,16 2,16L14,16C15.104,16 16,15.104 16,14L16,2Z" style="fill:rgb(96,184,227);"/>+ <path d="M9.619,5.45L12.5,5.45L12.5,3.5L3.5,3.5L3.5,5.45L6.381,5.45L9.619,10.55L12.5,10.55L12.5,12.5L3.5,12.5L3.5,10.55L6.381,10.55" style="fill:none;fill-rule:nonzero;stroke:black;stroke-width:1px;"/>+</svg>diff --git a/invokeai/frontend/webv2/public/manifest.webmanifest b/invokeai/frontend/webv2/public/manifest.webmanifestnew file mode 100644index 0000000000..1d9c0e196f--- /dev/null+++ b/invokeai/frontend/webv2/public/manifest.webmanifest@@ -0,0 +1,20 @@+{+ "name": "Invoke Workbench",+ "short_name": "Invoke",+ "description": "Professional creative engine for generating and editing visual media.",+ "id": "./",+ "start_url": "./",+ "scope": "./",+ "display": "standalone",+ "orientation": "landscape",+ "background_color": "#16181d",+ "theme_color": "#16181d",+ "icons": [+ {+ "src": "./invoke-icon.svg",+ "sizes": "any",+ "type": "image/svg+xml",+ "purpose": "any"+ }+ ]+}diff --git a/invokeai/frontend/webv2/scripts/service-worker-plugin.mjs b/invokeai/frontend/webv2/scripts/service-worker-plugin.mjsnew file mode 100644index 0000000000..1f06a03943--- /dev/null+++ b/invokeai/frontend/webv2/scripts/service-worker-plugin.mjs@@ -0,0 +1,37 @@+import { createHash } from 'node:crypto';+import { readFile } from 'node:fs/promises';+import { resolve } from 'node:path';++const MANIFEST_PLACEHOLDER = 'self.__SW_MANIFEST__';++/**+ * Emits `sw.js` at the bundle root from the source worker in+ * `src/platform/pwa/sw.js`, injecting the build's asset manifest: the emitted+ * `assets/*` file names plus a version hash derived from them. The worker uses+ * the list for cache-first serving and stale-entry pruning; deriving the+ * version from the same list keeps rebuilds of identical output byte-stable.+ */+export const serviceWorkerPlugin = ({ projectRoot }) => ({+ apply: 'build',+ name: 'invokeai-service-worker',+ async generateBundle(_outputOptions, bundle) {+ const assets = Object.keys(bundle)+ .filter((fileName) => fileName.startsWith('assets/'))+ .sort();+ const version = createHash('sha256').update(assets.join('\n')).digest('hex').slice(0, 12);+ const source = await readFile(resolve(projectRoot, 'src/platform/pwa/sw.js'), 'utf8');+ const occurrences = source.split(MANIFEST_PLACEHOLDER).length - 1;++ // Exactly one: zero means the placeholder was renamed away, more than one+ // means a stray mention (e.g. in a comment) would swallow the injection.+ if (occurrences !== 1) {+ throw new Error(`Service worker source must contain ${MANIFEST_PLACEHOLDER} exactly once, found ${occurrences}.`);+ }++ this.emitFile({+ fileName: 'sw.js',+ source: source.replace(MANIFEST_PLACEHOLDER, JSON.stringify({ assets, version })),+ type: 'asset',+ });+ },+});diff --git a/invokeai/frontend/webv2/src/app/main.tsx b/invokeai/frontend/webv2/src/app/main.tsxindex 42b0b2a644..6f1bd5317e 100644--- a/invokeai/frontend/webv2/src/app/main.tsx+++ b/invokeai/frontend/webv2/src/app/main.tsx@@ -1,6 +1,7 @@import '@fontsource/inter/index.css';import '@platform/i18n/client';import { identityTransportAuthAdapter } from '@features/identity';+import { registerServiceWorker } from '@platform/pwa/registerServiceWorker';import { configureHttpAuth } from '@platform/transport/http';import { StrictMode } from 'react';import { createRoot } from 'react-dom/client';@@ -11,6 +12,7 @@ import { App } from './App';// Identity and HTTP ownership must be configured before any route starts work.configureAppAccountLifecycle();configureHttpAuth(identityTransportAuthAdapter);+registerServiceWorker();const rootElement = document.getElementById('root');diff --git a/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.ts b/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.tsnew file mode 100644index 0000000000..824402c92e--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.ts@@ -0,0 +1,23 @@+/**+ * Registers the app-shell service worker (`sw.js`, emitted by+ * `scripts/service-worker-plugin.mjs`). Hashed assets become cache-first so+ * repeat boots skip the network; navigations stay network-first so a plain+ * reload always picks up a new deploy; the shell keeps working offline.+ *+ * Production only: the dev server never emits `sw.js`, and a worker caching+ * unbundled dev modules would only get in the way. Registration waits for+ * `load` so it cannot compete with boot-critical fetches, and+ * `updateViaCache: 'none'` makes every navigation check for a new build.+ */+export const registerServiceWorker = (): void => {+ if (!import.meta.env.PROD || typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {+ return;+ }++ window.addEventListener('load', () => {+ navigator.serviceWorker.register('./sw.js', { updateViaCache: 'none' }).catch(() => {+ // Registration failing (private mode, unsupported scheme) just means+ // the app keeps loading straight from the network.+ });+ });+};diff --git a/invokeai/frontend/webv2/src/platform/pwa/sw.js b/invokeai/frontend/webv2/src/platform/pwa/sw.jsnew file mode 100644index 0000000000..d641313e61--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/pwa/sw.js@@ -0,0 +1,148 @@+/**+ * App-shell service worker. The manifest read below is a placeholder that+ * `scripts/service-worker-plugin.mjs` replaces at build time with+ * `{ version, assets }` — the build's content hash and its emitted asset file+ * names. The placeholder must appear exactly once; the plugin enforces this.+ *+ * Strategy:+ * - Navigations are network-first with the cached shell as offline fallback,+ * so a plain reload always picks up a new deploy — no update UI needed.+ * - Hashed `assets/*` files are cache-first: their names change when their+ * content does, so a cache hit is always correct and repeat boots skip the+ * network entirely.+ * - Locale files are stale-while-revalidate: instant from cache, refreshed in+ * the background.+ * - Everything else (API, sockets) is untouched.+ *+ * Deliberately no `skipWaiting()`: a new worker prunes assets its manifest no+ * longer lists, and a still-open old tab may yet lazy-load one of them. The+ * new worker activates once the old tabs are gone.+ */++const MANIFEST = self.__SW_MANIFEST__;++const SHELL_CACHE = `invokeai-shell-${MANIFEST.version}`;+const ASSET_CACHE = 'invokeai-assets';+const RUNTIME_CACHE = 'invokeai-runtime';++const INDEX_URL = new URL('index.html', self.registration.scope).href;+const ASSETS_PREFIX = new URL('assets/', self.registration.scope).href;+const LOCALES_PREFIX = new URL('locales/', self.registration.scope).href;+const ASSET_URLS = new Set(MANIFEST.assets.map((fileName) => new URL(fileName, self.registration.scope).href));++self.addEventListener('install', (event) => {+ event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.add(new Request(INDEX_URL, { cache: 'no-cache' }))));+});++self.addEventListener('activate', (event) => {+ event.waitUntil(+ (async () => {+ const names = await caches.keys();++ await Promise.all(+ names+ .filter((name) => name.startsWith('invokeai-shell-') && name !== SHELL_CACHE)+ .map((name) => caches.delete(name))+ );++ const assetCache = await caches.open(ASSET_CACHE);+ const cachedRequests = await assetCache.keys();++ await Promise.all(+ cachedRequests.filter((request) => !ASSET_URLS.has(request.url)).map((request) => assetCache.delete(request))+ );++ await self.clients.claim();+ })()+ );+});++const respondToNavigation = async (request) => {+ try {+ const response = await fetch(request);++ if (response.ok) {+ const cache = await caches.open(SHELL_CACHE);++ void cache.put(INDEX_URL, response.clone());+ }++ return response;+ } catch (error) {+ const cached = await caches.match(INDEX_URL);++ if (cached) {+ return cached;+ }++ throw error;+ }+};++const respondCacheFirst = async (request) => {+ const cached = await caches.match(request, { cacheName: ASSET_CACHE });++ if (cached) {+ return cached;+ }++ const response = await fetch(request);++ // Only current-manifest assets are written back, which keeps the cache+ // bounded; the activate handler prunes the previous build's entries.+ if (response.ok && ASSET_URLS.has(request.url)) {+ const cache = await caches.open(ASSET_CACHE);++ void cache.put(request, response.clone());+ }++ return response;+};++const respondStaleWhileRevalidate = async (request) => {+ const cache = await caches.open(RUNTIME_CACHE);+ const cached = await cache.match(request);+ const refresh = fetch(request)+ .then((response) => {+ if (response.ok) {+ void cache.put(request, response.clone());+ }++ return response;+ })+ .catch(() => undefined);++ if (cached) {+ return cached;+ }++ const response = await refresh;++ if (!response) {+ throw new TypeError(`Offline and not cached: ${request.url}`);+ }++ return response;+};++self.addEventListener('fetch', (event) => {+ const { request } = event;++ if (request.method !== 'GET' || !request.url.startsWith(self.location.origin)) {+ return;+ }++ if (request.mode === 'navigate') {+ event.respondWith(respondToNavigation(request));+ return;+ }++ if (request.url.startsWith(ASSETS_PREFIX)) {+ event.respondWith(respondCacheFirst(request));+ return;+ }++ if (request.url.startsWith(LOCALES_PREFIX)) {+ event.respondWith(respondStaleWhileRevalidate(request));+ }+});diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex e9643e0bde..af9548bed9 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -4,6 +4,7 @@ import { fileURLToPath, URL } from 'node:url';import { defineConfig } from 'vite';import { chunkSourceManifest } from './scripts/chunk-source-manifest.mjs';+import { serviceWorkerPlugin } from './scripts/service-worker-plugin.mjs';// Override with e.g. INVOKEAI_DEV_BACKEND=http://127.0.0.1:9091 when the// backend dev server runs on a non-default port.@@ -179,6 +180,7 @@ export default defineConfig({presets: [reactCompilerPreset()],}),chunkSourceManifest({ projectRoot: PROJECT_ROOT }),+ serviceWorkerPlugin({ projectRoot: PROJECT_ROOT }),],resolve: {alias: {