- The weather forecast from `/api/context` does not cover this plan window yet.
+ The weather forecast from /api/context does not cover this plan window yet.
{{ activeScenario?.description ?? 'Base scenario uses the API forecast weather.' }}
diff --git a/app/pages/simulate.vue b/app/pages/simulate.vue
index e3de88c..c6261a1 100644
--- a/app/pages/simulate.vue
+++ b/app/pages/simulate.vue
@@ -136,8 +136,9 @@ const days = computed(() =>
@@ -246,7 +247,7 @@ const days = computed(() =>
Scenario perturbations are produced by the Go/ML stack. This page reads the base and scenario plans from
- `/api/staffing`; it does not invent its own multipliers.
+ /api/staffing; it does not invent its own multipliers.
diff --git a/app/pages/stage.vue b/app/pages/stage.vue
new file mode 100644
index 0000000..e37ea00
--- /dev/null
+++ b/app/pages/stage.vue
@@ -0,0 +1,560 @@
+
+
+
+
+
+
+
+ PulseCast stage
+
+ cached forecast
+
+
{{ headline }}
+
+ {{ activeSensor?.name ?? 'Stadtgalerie' }} · {{ scenarioLabel(live.scenarioId) }} ·
+ {{ plan ? `${totalStaffHours} staff-hours` : 'waiting for the API' }} · updates live via SSE
+
+
+
+
+ Scenario version {{ live.version || '—' }}
+ · broadcast {{ formatDateTime(live.scenarioAt) }}
+
+
+
+
+
+
+
+
+
+
+ Scan for the phone view
+
+
{{ liveUrl }}
+
+
+
+
+
+
+ The plan is unavailable.
+ {{ planError.statusMessage ?? 'Check the Go API and ML service.' }}
+
+
+
+
+
+
+ Loading the current staffing plan…
+
+
+
+
+ No open hours are available for this sensor yet. Check the data window or pick another store.
+
+
+
+
+
Peak staff
+
{{ plan ? peakStaff : '—' }}
+
+ {{ formatWeekday(peakShift.date) }} {{ peakShift.start }}–{{ peakShift.end }}
+ Per shift block
+
+
+
+
Labour cost
+
{{ plan ? formatEuro(plan.summary.cost_eur) : '—' }}
+
{{ plan ? `€${plan.assumptions.labor_cost_eur_h}/h assumption` : '—' }}
+
+
+
Coverage
+
{{ plan ? formatPercent(plan.summary.coverage_pct, 1) : '—' }}
+
+ {{ plan ? `${plan.summary.understaffed_hours} h under` : '—' }}
+
+
+
+
Forecast peak
+
{{ forecastPeak ? Math.round(forecastPeak) : '—' }}
+
estimated devices/hour
+
+
+
vs flat schedule
+
−{{ plan ? formatEuro(saving) : '—' }}
+
same coverage, fewer hours
+
+
+
+
+
+
+ The decision on stage
+ {{ scenarioLabel(live.scenarioId) }}
+
+
+
+ Put {{ peakShift.staff }} staff on {{ formatWeekday(peakShift.date) }}
+ {{ formatShortDate(peakShift.date) }}, {{ peakShift.start }}–{{ peakShift.end }}.
+
+ Pick a store and scenario; the recommendation appears here.
+
+
+
+
+ {{ plan.summary.understaffed_hours === 0 ? 'Every open hour is covered by the block plan.' : `${plan.summary.understaffed_hours} hours are below requirement.` }}
+ {{ plan.summary.overstaffed_hours }} hours are intentionally over requirement.
+
+ Nothing to approve yet.
+
+
+
+
+
+
+
+ Forecast refresh failed: {{ forecastError.statusMessage }}
+
+
+
+
+
+ On every phone
+ no login
+
+
+
+
LIVE
+
{{ plan ? peakStaff : '—' }} staff
+
+ {{ formatWeekday(peakShift.date) }} · {{ peakShift.start }}–{{ peakShift.end }}
+ Waiting for the plan
+
+
{{ scenarioLabel(live.scenarioId) }} · v{{ live.version || '—' }}
+
+
+
+ The audience scans the QR code. The same scenario event refreshes the phone view and this screen within
+ the SSE round trip.
+
+
+
+
+
+
+
+
+
diff --git a/app/utils/api-error.ts b/app/utils/api-error.ts
new file mode 100644
index 0000000..be2b380
--- /dev/null
+++ b/app/utils/api-error.ts
@@ -0,0 +1,27 @@
+interface ApiErrorLike {
+ status?: number
+ statusCode?: number
+ statusMessage?: string
+ message?: string
+ data?: {
+ error?: { message?: string; code?: string }
+ message?: string
+ }
+}
+
+/** Human-readable message from a Nuxt/$fetch error, without leaking tokens. */
+export function apiErrorMessage(error: unknown, fallback: string): string {
+ const value = error as ApiErrorLike | undefined
+ return (
+ value?.data?.error?.message ??
+ value?.data?.message ??
+ value?.statusMessage ??
+ value?.message ??
+ fallback
+ )
+}
+
+export function apiErrorStatus(error: unknown): number | undefined {
+ const value = error as ApiErrorLike | undefined
+ return value?.status ?? value?.statusCode
+}
diff --git a/package-lock.json b/package-lock.json
index 70be9ad..8edd813 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,9 +13,11 @@
"chart.js": "4.6.1",
"maplibre-gl": "6.18.0",
"nuxt": "4.6.4",
+ "qrcode": "1.5.4",
"sit-onyx": "1.22.0"
},
"devDependencies": {
+ "@types/qrcode": "1.5.5",
"typescript": "5.9.3",
"vitest": "3.2.4"
}
@@ -2669,6 +2671,26 @@
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
+ "node_modules/@types/node": {
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+ "devOptional": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@types/qrcode": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.5.tgz",
+ "integrity": "sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/resolve": {
"version": "1.20.2",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
@@ -3835,6 +3857,15 @@
"node": ">=20.19.0"
}
},
+ "node_modules/camelcase": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
+ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/caniuse-api": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-4.0.0.tgz",
@@ -3983,6 +4014,24 @@
"node": ">=0.10.0"
}
},
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "license": "MIT"
+ },
"node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
@@ -4230,6 +4279,15 @@
}
}
},
+ "node_modules/decamelize": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
+ "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
@@ -4346,6 +4404,12 @@
"node": ">=0.3.1"
}
},
+ "node_modules/dijkstrajs": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
+ "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
+ "license": "MIT"
+ },
"node_modules/dot-prop": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-10.2.0.tgz",
@@ -4718,6 +4782,19 @@
"node": ">=8"
}
},
+ "node_modules/find-up": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/flru": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -5186,6 +5263,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
@@ -5795,6 +5881,18 @@
"url": "https://github.com/sponsors/antfu"
}
},
+ "node_modules/locate-path": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -6684,6 +6782,42 @@
}
}
},
+ "node_modules/p-limit": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
+ "license": "MIT",
+ "dependencies": {
+ "p-try": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-locate": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/p-try": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/package-manager-detector": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz",
@@ -6699,6 +6833,15 @@
"node": ">= 0.8"
}
},
+ "node_modules/path-exists": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
@@ -6802,6 +6945,15 @@
"pathe": "^2.0.3"
}
},
+ "node_modules/pngjs": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
+ "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6919,6 +7071,145 @@
"integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
"license": "MIT"
},
+ "node_modules/qrcode": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
+ "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
+ "license": "MIT",
+ "dependencies": {
+ "dijkstrajs": "^1.0.1",
+ "pngjs": "^5.0.0",
+ "yargs": "^15.3.1"
+ },
+ "bin": {
+ "qrcode": "bin/qrcode"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/qrcode/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/qrcode/node_modules/cliui": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
+ "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.0",
+ "wrap-ansi": "^6.2.0"
+ }
+ },
+ "node_modules/qrcode/node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "license": "MIT"
+ },
+ "node_modules/qrcode/node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/wrap-ansi": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
+ "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/y18n": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
+ "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
+ "license": "ISC"
+ },
+ "node_modules/qrcode/node_modules/yargs": {
+ "version": "15.4.1",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
+ "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
+ "license": "MIT",
+ "dependencies": {
+ "cliui": "^6.0.0",
+ "decamelize": "^1.2.0",
+ "find-up": "^4.1.0",
+ "get-caller-file": "^2.0.1",
+ "require-directory": "^2.1.1",
+ "require-main-filename": "^2.0.0",
+ "set-blocking": "^2.0.0",
+ "string-width": "^4.2.0",
+ "which-module": "^2.0.0",
+ "y18n": "^4.0.0",
+ "yargs-parser": "^18.1.2"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/qrcode/node_modules/yargs-parser": {
+ "version": "18.1.3",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
+ "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
+ "license": "ISC",
+ "dependencies": {
+ "camelcase": "^5.0.0",
+ "decamelize": "^1.2.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/quansync": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz",
@@ -7070,6 +7361,15 @@
"node": ">=4"
}
},
+ "node_modules/require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -7079,6 +7379,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/require-main-filename": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
+ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
+ "license": "ISC"
+ },
"node_modules/resolve": {
"version": "1.22.14",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz",
@@ -7429,6 +7735,12 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/set-blocking": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
+ "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
+ "license": "ISC"
+ },
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
@@ -8031,6 +8343,13 @@
"node": ">=22.19.0"
}
},
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "devOptional": true,
+ "license": "MIT"
+ },
"node_modules/unenv": {
"version": "2.0.0-rc.25",
"resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.25.tgz",
@@ -9170,6 +9489,12 @@
"node": "^20.17.0 || >=22.9.0"
}
},
+ "node_modules/which-module": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
+ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
+ "license": "ISC"
+ },
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
diff --git a/package.json b/package.json
index 411937f..f285bda 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,8 @@
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"test": "vitest run",
- "mock": "node scripts/generate-mock.mjs"
+ "mock": "node scripts/generate-mock.mjs",
+ "smoke:live": "node scripts/smoke-live.mjs"
},
"dependencies": {
"@sit-onyx/chartjs-plugin": "1.0.1",
@@ -17,9 +18,11 @@
"chart.js": "4.6.1",
"maplibre-gl": "6.18.0",
"nuxt": "4.6.4",
+ "qrcode": "1.5.4",
"sit-onyx": "1.22.0"
},
"devDependencies": {
+ "@types/qrcode": "1.5.5",
"typescript": "5.9.3",
"vitest": "3.2.4"
}
diff --git a/scripts/smoke-live.mjs b/scripts/smoke-live.mjs
new file mode 100644
index 0000000..2c8c1a9
--- /dev/null
+++ b/scripts/smoke-live.mjs
@@ -0,0 +1,387 @@
+#!/usr/bin/env node
+/**
+ * End-to-end live smoke test.
+ *
+ * Prerequisites (read-only use of the Go/ML worktrees):
+ * - Go API on http://127.0.0.1:18080 with CONTROL_USER/CONTROL_PASS
+ * - FastAPI ML on http://127.0.0.1:18000 (so Go can answer /api/readyz)
+ * - Built Nuxt server on http://127.0.0.1:13000 with
+ * NUXT_API_INTERNAL_BASE=http://127.0.0.1:18080
+ * CONTROL_USER=control CONTROL_PASS=secret
+ *
+ * What it proves: the presenter POST reaches Go through Nitro, a `scenario`
+ * SSE event arrives through the Nitro stream proxy, and the staffing/forecast
+ * APIs return the new scenario. It also checks /stage, /live, the QR route and
+ * the control-auth boundary.
+ */
+import assert from 'node:assert/strict'
+
+const WEB_URL = (process.env.WEB_URL ?? 'http://127.0.0.1:13000').replace(/\/+$/, '')
+const CONTROL_USER = process.env.CONTROL_USER ?? 'control'
+const CONTROL_PASS = process.env.CONTROL_PASS ?? 'secret'
+const SENSOR = process.env.SENSOR ?? 'hn-stadtgalerie-01'
+const SSE_TIMEOUT_MS = Number(process.env.SSE_TIMEOUT_MS ?? 8000)
+const EXPECT_HEARTBEAT = process.env.EXPECT_HEARTBEAT === '1'
+const verbose = process.env.VERBOSE === '1'
+
+const AUTHORIZATION = `Basic ${Buffer.from(`${CONTROL_USER}:${CONTROL_PASS}`).toString('base64')}`
+
+function url(path) {
+ return new URL(path, `${WEB_URL}/`).toString()
+}
+
+function log(message) {
+ console.log(` ${message}`)
+}
+
+function pass(message) {
+ console.log(`PASS ${message}`)
+}
+
+function fail(message) {
+ console.error(`FAIL ${message}`)
+}
+
+async function fetchText(path, options = {}) {
+ const response = await fetch(url(path), options)
+ const text = await response.text()
+ if (verbose) log(`${options.method ?? 'GET'} ${path} -> ${response.status}`)
+ return { response, text }
+}
+
+async function fetchJson(path, options = {}) {
+ const { response, text } = await fetchText(path, {
+ ...options,
+ headers: { accept: 'application/json', ...(options.headers ?? {}) },
+ })
+ let body
+ try {
+ body = JSON.parse(text)
+ } catch {
+ throw new Error(`${path} returned non-JSON (${response.status}): ${text.slice(0, 200)}`)
+ }
+ return { response, body }
+}
+
+async function expectJson(path, options, status = 200) {
+ const { response, body } = await fetchJson(path, options)
+ assert.equal(response.status, status, `${path} status ${response.status}, expected ${status}: ${JSON.stringify(body)}`)
+ return body
+}
+
+function parseFrame(frame) {
+ let name = 'message'
+ let id = ''
+ let retry = ''
+ const data = []
+ for (const line of frame.split('\n')) {
+ if (!line || line.startsWith(':')) continue
+ const separator = line.indexOf(':')
+ const field = separator < 0 ? line : line.slice(0, separator)
+ const value = separator < 0 ? '' : line.slice(separator + 1).replace(/^ /, '')
+ if (field === 'event') name = value
+ else if (field === 'id') id = value
+ else if (field === 'data') data.push(value)
+ else if (field === 'retry') retry = value
+ }
+ if (!data.length && name === 'message' && !retry) return null
+ return { name: data.length || name !== 'message' ? name : 'retry', id, retry, data: data.join('\n') }
+}
+
+/** Minimal incremental SSE reader over fetch (Node has no EventSource). */
+function openSse(path) {
+ const controller = new AbortController()
+ const events = []
+ const waiters = new Set()
+ let raw = ''
+ let buffer = ''
+ let finished = false
+
+ const notify = () => {
+ for (const waiter of [...waiters]) waiter()
+ }
+
+ const consume = () => {
+ while (true) {
+ const match = buffer.match(/\r?\n\r?\n/)
+ if (!match || match.index === undefined) break
+ const frame = buffer.slice(0, match.index)
+ buffer = buffer.slice(match.index + match[0].length)
+ const event = parseFrame(frame)
+ if (event) {
+ events.push(event)
+ notify()
+ }
+ }
+ }
+
+ const responsePromise = fetch(url(path), {
+ headers: { accept: 'text/event-stream' },
+ signal: controller.signal,
+ }).then(async (response) => {
+ assert.equal(response.status, 200, `SSE status ${response.status}`)
+ const contentType = response.headers.get('content-type') ?? ''
+ assert.match(contentType, /text\/event-stream/, `SSE content-type: ${contentType}`)
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ ;(async () => {
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ const chunk = decoder.decode(value, { stream: true })
+ raw += chunk
+ buffer += chunk.replace(/\r\n/g, '\n')
+ consume()
+ }
+ } catch (error) {
+ if (error?.name !== 'AbortError') throw error
+ } finally {
+ finished = true
+ notify()
+ }
+ })()
+ return response
+ })
+
+ function waitFor(predicate, timeoutMs, label) {
+ const existing = events.find(predicate)
+ if (existing) return Promise.resolve(existing)
+ if (finished) return Promise.reject(new Error(`SSE closed before ${label}`))
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ waiters.delete(check)
+ reject(new Error(`Timed out after ${timeoutMs} ms waiting for ${label}`))
+ }, timeoutMs)
+ const check = () => {
+ const match = events.find(predicate)
+ if (!match) return
+ clearTimeout(timer)
+ waiters.delete(check)
+ resolve(match)
+ }
+ waiters.add(check)
+ })
+ }
+
+ return {
+ responsePromise,
+ waitFor,
+ get raw() {
+ return raw
+ },
+ close() {
+ controller.abort()
+ },
+ }
+}
+
+function decisionShape(plan) {
+ return JSON.stringify({
+ scenario: plan.scenario,
+ summary: plan.summary,
+ footfall: plan.hours.map((hour) => [hour.t, hour.footfall, hour.required_staff, hour.scheduled_staff]),
+ })
+}
+
+async function main() {
+ console.log(`PulseCast live smoke test -> ${WEB_URL}`)
+
+ const health = await expectJson('/api/healthz')
+ assert.equal(health.ok, true, 'healthz.ok')
+ pass('Nitro health endpoint')
+
+ const ready = await expectJson('/api/readyz')
+ assert.equal(ready.ok, true, 'readyz.ok')
+ assert.equal(ready.data, true, 'readyz.data (Go bootstrap snapshot)')
+ assert.equal(ready.model, true, 'readyz.model (FastAPI)')
+ pass('Go API ready with ML snapshot')
+
+ const initial = await expectJson('/api/scenario')
+ assert.equal(typeof initial.version, 'number', 'scenario.version')
+ assert.ok(initial.scenario?.scenario, 'scenario.scenario')
+ pass(`scenario state v${initial.version} (${initial.scenario.scenario})`)
+
+ const basePlan = await expectJson(
+ `/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=base&standard=standard`,
+ )
+ assert.equal(basePlan.sensor, SENSOR)
+ assert.equal(basePlan.scenario, 'base')
+ assert.ok(basePlan.hours.length > 0, 'base plan has open hours')
+ assert.ok(basePlan.shifts.length > 0, 'base plan has shift blocks')
+ pass(`base plan: ${basePlan.hours.length} hours, ${basePlan.shifts.length} shifts`)
+
+ const baseForecast = await expectJson(
+ `/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=base`,
+ )
+ assert.ok(baseForecast.points.length > 0, 'base forecast has points')
+ pass(`base forecast: ${baseForecast.points.length} hourly points`)
+
+ const unauthenticated = await fetchJson('/api/scenario', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ scenario: 'rainy-saturday' }),
+ })
+ assert.equal(unauthenticated.response.status, 401, 'POST without presenter auth must be 401')
+ pass('unauthenticated scenario POST is rejected')
+
+ const controlPage = await fetchText('/control')
+ assert.equal(controlPage.response.status, 401, '/control without auth must be 401')
+ assert.match(controlPage.response.headers.get('www-authenticate') ?? '', /Basic/i)
+ pass('/control is presenter-protected')
+
+ const controlAuthed = await fetchText('/control', { headers: { authorization: AUTHORIZATION } })
+ assert.equal(controlAuthed.response.status, 200, '/control with auth')
+ assert.match(controlAuthed.text, /Presenter control/i)
+ pass('/control authenticates and renders')
+
+ for (const [path, needle] of [
+ ['/stage', 'Scan for the phone view'],
+ ['/live', 'The plan on your phone'],
+ ]) {
+ const page = await fetchText(path)
+ assert.equal(page.response.status, 200, `${path} status`)
+ assert.match(page.response.headers.get('content-type') ?? '', /text\/html/i, `${path} content-type`)
+ assert.ok(page.text.includes(needle), `${path} contains "${needle}"`)
+ assert.ok(page.text.includes('PulseCast'), `${path} contains the app shell`)
+ pass(`${path} renders server-side`)
+ }
+
+ const qr = await fetchText(`/api/qr?text=${encodeURIComponent(`${WEB_URL}/live`)}`)
+ assert.equal(qr.response.status, 200, 'QR status')
+ assert.match(qr.response.headers.get('content-type') ?? '', /image\/svg\+xml/i, 'QR content-type')
+ assert.match(qr.text, /
event.name === 'scenario' || event.name === 'retry',
+ 5000,
+ 'the initial SSE frame',
+ )
+ assert.ok(initialEvent, 'initial SSE frame')
+ if (EXPECT_HEARTBEAT) {
+ await sse.waitFor((event) => event.name === 'ping', SSE_TIMEOUT_MS, 'a heartbeat ping')
+ pass('SSE heartbeat observed')
+ }
+ assert.match(sse.raw, /retry:\s*3000/, 'SSE retry hint')
+
+ const initialScenarioEvent = await sse.waitFor(
+ (event) => event.name === 'scenario',
+ 5000,
+ 'the initial scenario event',
+ )
+ const initialPayload = JSON.parse(initialScenarioEvent.data)
+ assert.equal(typeof initialPayload.version, 'number', 'SSE initial version')
+ pass(`SSE connected: retry:3000, initial scenario v${initialPayload.version}`)
+
+ const target = initialPayload.scenario === 'rainy-saturday' ? 'sunny-saturday-market' : 'rainy-saturday'
+ const body =
+ target === 'sunny-saturday-market'
+ ? {
+ scenario: target,
+ weather: { temp_delta_c: 4, precip_mm: 0 },
+ event: { type: 'market', uplift: 0.2 },
+ }
+ : {
+ scenario: target,
+ weather: { temp_delta_c: -2, precip_mm: 3.2 },
+ }
+
+ const started = performance.now()
+ const posted = await expectJson('/api/scenario', {
+ method: 'POST',
+ headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ assert.equal(posted.scenario.scenario, target, 'POST response scenario')
+ const postMs = performance.now() - started
+
+ const event = await sse.waitFor(
+ (candidate) => {
+ if (candidate.name !== 'scenario') return false
+ try {
+ const payload = JSON.parse(candidate.data)
+ return payload.version >= posted.version && payload.scenario?.scenario === target
+ } catch {
+ return false
+ }
+ },
+ 5000,
+ `a scenario SSE event for ${target}`,
+ )
+ const elapsed = performance.now() - started
+ const payload = JSON.parse(event.data)
+ assert.equal(payload.scenario.scenario, target, 'SSE scenario id')
+ assert.equal(event.id, String(payload.version), 'SSE id equals the scenario version')
+ assert.ok(elapsed < 5000, `scenario event took ${elapsed.toFixed(0)} ms (max 5000)`)
+ if (elapsed >= 2000) {
+ console.warn(`WARN scenario propagated in ${elapsed.toFixed(0)} ms; contract target is <2000 ms`)
+ }
+ pass(`scenario POST -> SSE event in ${elapsed.toFixed(0)} ms (POST ${postMs.toFixed(0)} ms)`)
+
+ const polled = await expectJson('/api/scenario')
+ assert.equal(polled.version, posted.version, 'GET /api/scenario polling version')
+ assert.equal(polled.scenario.scenario, target, 'GET /api/scenario polling scenario')
+ pass(`polling fallback reads v${polled.version} (${target})`)
+
+ const targetPlan = await expectJson(
+ `/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=${target}&standard=standard`,
+ )
+ assert.equal(targetPlan.scenario, target, 'target plan scenario')
+ assert.ok(targetPlan.hours.length > 0, 'target plan has hours')
+ assert.notEqual(
+ decisionShape(targetPlan),
+ decisionShape(basePlan),
+ `${target} plan must differ from base`,
+ )
+ if (targetPlan.cached) {
+ console.warn('WARN Go served a cached plan; ML was not used for this request')
+ } else {
+ pass('target plan is live and differs from base')
+ }
+
+ const targetForecast = await expectJson(
+ `/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=${target}`,
+ )
+ assert.equal(targetForecast.scenario, target, 'target forecast scenario')
+ assert.ok(targetForecast.points.length > 0, 'target forecast has points')
+ assert.notEqual(
+ JSON.stringify(targetForecast.points),
+ JSON.stringify(baseForecast.points),
+ `${target} forecast must differ from base`,
+ )
+ pass('target forecast is live and differs from base')
+
+ const stageAfter = await fetchText('/stage')
+ assert.equal(stageAfter.response.status, 200, 'stage after scenario')
+ const expectedLabel = target === 'rainy-saturday' ? 'Rainy Saturday' : 'Sunny Saturday'
+ assert.ok(stageAfter.text.includes(expectedLabel), `stage renders ${expectedLabel}`)
+ pass(`/stage server-renders the new scenario (${expectedLabel})`)
+
+ const liveAfter = await fetchText('/live')
+ assert.equal(liveAfter.response.status, 200, 'live after scenario')
+ assert.ok(liveAfter.text.includes(expectedLabel), `live renders ${expectedLabel}`)
+ pass(`/live server-renders the new scenario (${expectedLabel})`)
+
+ // Leave the demo in the base state so the next run is deterministic.
+ const restored = await expectJson('/api/scenario', {
+ method: 'POST',
+ headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' },
+ body: JSON.stringify({ scenario: 'base', weather: { temp_delta_c: 0, precip_mm: 0 } }),
+ })
+ assert.equal(restored.scenario.scenario, 'base')
+ pass(`restored base (v${restored.version})`)
+ } finally {
+ sse.close()
+ }
+
+ console.log('\nAll live smoke checks passed.')
+}
+
+main().catch((error) => {
+ fail(error?.stack ?? String(error))
+ process.exitCode = 1
+})
diff --git a/server/api/qr.get.ts b/server/api/qr.get.ts
new file mode 100644
index 0000000..69c98a1
--- /dev/null
+++ b/server/api/qr.get.ts
@@ -0,0 +1,35 @@
+import QRCode from 'qrcode'
+
+/**
+ * Generate the /stage QR code locally. No third-party QR image service is
+ * called at runtime, so the big screen keeps working without internet access.
+ */
+export default defineEventHandler(async (event) => {
+ const query = getQuery(event)
+ const text = typeof query.text === 'string' ? query.text.trim() : ''
+ if (!text) {
+ throw createError({ statusCode: 400, statusMessage: 'text is required' })
+ }
+ if (text.length > 1024) {
+ throw createError({ statusCode: 400, statusMessage: 'text is too long for a QR code' })
+ }
+
+ let svg: string
+ try {
+ svg = await QRCode.toString(text, {
+ type: 'svg',
+ margin: 1,
+ width: 320,
+ errorCorrectionLevel: 'M',
+ color: { dark: '#0f172a', light: '#ffffff' },
+ })
+ } catch {
+ throw createError({ statusCode: 400, statusMessage: 'could not encode text as a QR code' })
+ }
+
+ setResponseHeaders(event, {
+ 'content-type': 'image/svg+xml; charset=utf-8',
+ 'cache-control': 'public, max-age=300',
+ })
+ return svg
+})
diff --git a/server/api/scenario.get.ts b/server/api/scenario.get.ts
index 1b53483..97d89b1 100644
--- a/server/api/scenario.get.ts
+++ b/server/api/scenario.get.ts
@@ -1,8 +1,8 @@
import type { ScenarioState } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
-import { mockScenario } from '../utils/mock-data'
+import { getMockScenario } from '../utils/mock-scenario'
export default defineEventHandler(async () => {
- if (isMockMode()) return mockScenario
+ if (isMockMode()) return getMockScenario()
return apiRequest('/api/scenario')
})
diff --git a/server/api/scenario.post.ts b/server/api/scenario.post.ts
index d6b3b7e..296b2ee 100644
--- a/server/api/scenario.post.ts
+++ b/server/api/scenario.post.ts
@@ -1,9 +1,7 @@
import { SCENARIOS } from '../../shared/types'
import type { Scenario, ScenarioDefinition, ScenarioState } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
-import { mockScenario } from '../utils/mock-data'
-
-let version = mockScenario.version
+import { setMockScenario } from '../utils/mock-scenario'
export default defineEventHandler(async (event) => {
const body = await readBody(event)
@@ -16,12 +14,7 @@ export default defineEventHandler(async (event) => {
}
if (isMockMode()) {
- version += 1
- return {
- version,
- scenario: body,
- at: new Date().toISOString(),
- }
+ return setMockScenario(body)
}
// Control credentials are attached in the server process, never in the
diff --git a/server/api/stream.get.ts b/server/api/stream.get.ts
new file mode 100644
index 0000000..ab4dc80
--- /dev/null
+++ b/server/api/stream.get.ts
@@ -0,0 +1,24 @@
+import { apiBaseUrl, isMockMode } from '../utils/api'
+
+/**
+ * Same-origin SSE proxy. The browser never talks to Go directly, so the
+ * Cloudflare/K8s CORS surface stays closed and the stream can be cached or
+ * authenticated at one edge only.
+ *
+ * h3's proxyRequest pipes response chunks as they arrive (it does not await
+ * the full body), which preserves the 15 s heartbeat and `retry: 3000`.
+ */
+export default defineEventHandler(async (event) => {
+ if (isMockMode() || process.env.NUXT_DISABLE_SSE === '1') {
+ // Failure drill: make the client prove the 5 s polling fallback. Mock mode
+ // has no upstream stream either, so both paths fail fast and visibly.
+ throw createError({
+ statusCode: 503,
+ statusMessage: 'SSE is disabled; the scenario polling fallback is active.',
+ })
+ }
+
+ return proxyRequest(event, `${apiBaseUrl()}/api/stream`, {
+ headers: { accept: 'text/event-stream' },
+ })
+})
diff --git a/server/middleware/control-auth.ts b/server/middleware/control-auth.ts
new file mode 100644
index 0000000..2160b51
--- /dev/null
+++ b/server/middleware/control-auth.ts
@@ -0,0 +1,101 @@
+import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
+import { isMockMode } from '../utils/api'
+
+const COOKIE_NAME = 'pulsecast_control'
+const COOKIE_CONTEXT = 'pulsecast-control-v1'
+
+function digest(value: string): Buffer {
+ return createHash('sha256').update(value).digest()
+}
+
+/** Constant-time compare that works for unequal-length strings. */
+function safeEqual(a: string, b: string): boolean {
+ return timingSafeEqual(digest(a), digest(b))
+}
+
+function expectedCookie(pass: string): string {
+ return createHmac('sha256', pass).update(COOKIE_CONTEXT).digest('base64url')
+}
+
+function basicCredentials(event: import('h3').H3Event): { user: string; pass: string } | null {
+ const header = getHeader(event, 'authorization') ?? ''
+ if (!header.startsWith('Basic ')) return null
+ let decoded: string
+ try {
+ decoded = Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8')
+ } catch {
+ return null
+ }
+ const separator = decoded.indexOf(':')
+ if (separator < 0) return null
+ return { user: decoded.slice(0, separator), pass: decoded.slice(separator + 1) }
+}
+
+function isProtected(event: import('h3').H3Event): boolean {
+ const path = getRequestURL(event).pathname.replace(/\/+$/, '') || '/'
+ if (path === '/control') return true
+ if (path === '/api/scenario' && getMethod(event) === 'POST') return true
+ return false
+}
+
+/**
+ * Presenter-only control surface. Basic auth is checked in Nitro; on success
+ * an HMAC cookie (signed with CONTROL_PASS) lets the page POST /api/scenario
+ * without re-prompting. The browser never receives the Go credentials, and
+ * /stage, /live and all public GETs stay open.
+ */
+export default defineEventHandler((event) => {
+ if (!isProtected(event)) return
+ if (isMockMode()) return
+
+ const user = process.env.CONTROL_USER ?? process.env.NUXT_CONTROL_USER ?? ''
+ const pass = process.env.CONTROL_PASS ?? process.env.NUXT_CONTROL_PASS ?? ''
+ const isApi = getRequestURL(event).pathname.startsWith('/api/')
+ setResponseHeader(event, 'cache-control', 'no-store')
+
+ if (!user || !pass) {
+ setResponseStatus(event, 503)
+ if (isApi) {
+ setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
+ return {
+ error: {
+ code: 'control_auth_unconfigured',
+ message: 'CONTROL_USER and CONTROL_PASS are not configured in the web server.',
+ },
+ }
+ }
+ setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
+ return 'Control credentials are not configured. Set CONTROL_USER and CONTROL_PASS on the web server.'
+ }
+
+ const expected = expectedCookie(pass)
+ const cookie = getCookie(event, COOKIE_NAME)
+ const cookieValid = Boolean(cookie && safeEqual(cookie, expected))
+
+ let basicValid = false
+ const basic = basicCredentials(event)
+ if (basic && safeEqual(basic.user, user) && safeEqual(basic.pass, pass)) {
+ basicValid = true
+ const forwardedProto = (getHeader(event, 'x-forwarded-proto') ?? '').split(',')[0]?.trim()
+ setCookie(event, COOKIE_NAME, expected, {
+ httpOnly: true,
+ sameSite: 'lax',
+ path: '/',
+ maxAge: 60 * 60 * 8,
+ secure: (forwardedProto || getRequestProtocol(event)) === 'https',
+ })
+ }
+
+ if (cookieValid || basicValid) return
+
+ setResponseStatus(event, 401)
+ setResponseHeader(event, 'www-authenticate', 'Basic realm="PulseCast presenter"')
+ if (isApi) {
+ setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
+ return {
+ error: { code: 'unauthorized', message: 'Presenter credentials are required to change the scenario.' },
+ }
+ }
+ setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
+ return 'Authentication required.'
+})
diff --git a/server/utils/mock-scenario.ts b/server/utils/mock-scenario.ts
new file mode 100644
index 0000000..2dd632d
--- /dev/null
+++ b/server/utils/mock-scenario.ts
@@ -0,0 +1,24 @@
+import type { ScenarioDefinition, ScenarioState } from '../../shared/types'
+import { mockScenario } from './mock-data'
+
+// Mock mode has no Go process, but the presenter controls and the 5 s polling
+// fallback should still observe a version change. Nitro keeps this per-process
+// state, exactly like the single Go pod keeps its in-memory scenario.
+let current: ScenarioState = clone(mockScenario)
+
+function clone(value: T): T {
+ return JSON.parse(JSON.stringify(value)) as T
+}
+
+export function getMockScenario(): ScenarioState {
+ return clone(current)
+}
+
+export function setMockScenario(input: ScenarioDefinition): ScenarioState {
+ current = {
+ version: current.version + 1,
+ scenario: clone(input),
+ at: new Date().toISOString(),
+ }
+ return clone(current)
+}
diff --git a/shared/live.ts b/shared/live.ts
new file mode 100644
index 0000000..ddc76b7
--- /dev/null
+++ b/shared/live.ts
@@ -0,0 +1,101 @@
+import { SCENARIOS } from './types'
+import type { Scenario, ScenarioState } from './types'
+
+/** Client connection modes shown on /stage, /live and /plan. */
+export type LiveConnection = 'connecting' | 'live' | 'polling' | 'offline'
+
+/** Poll the public scenario endpoint every 5 s while SSE is unavailable. */
+export const SCENARIO_POLL_MS = 5000
+/** Two consecutive SSE errors are enough to start the polling fallback. */
+export const SSE_FAILURES_BEFORE_POLLING = 2
+/** The Go hub pings every 15 s; two missed pings mean the stream is buffered. */
+export const SSE_STALE_MS = 32000
+
+export const LIVE_LABELS: Record = {
+ connecting: 'Connecting',
+ live: 'Live',
+ polling: 'Polling',
+ offline: 'Offline',
+}
+
+export const LIVE_COLORS: Record = {
+ connecting: 'neutral',
+ live: 'success',
+ polling: 'warning',
+ offline: 'danger',
+}
+
+export interface LiveStatusInput {
+ online: boolean
+ sseOpen: boolean
+ sseFailures: number
+ polling: boolean
+ pollFailures: number
+}
+
+/**
+ * Resolve the visible connection state. Live means an open SSE stream,
+ * Polling means the 5 s fallback is working, Offline means neither path works.
+ */
+export function liveStatus(input: LiveStatusInput): LiveConnection {
+ if (!input.online) return 'offline'
+ if (input.sseOpen) return 'live'
+ if (input.polling) return input.pollFailures > 0 ? 'offline' : 'polling'
+ if (input.sseFailures >= SSE_FAILURES_BEFORE_POLLING) {
+ return input.pollFailures > 0 ? 'offline' : 'polling'
+ }
+ return 'connecting'
+}
+
+/** Parse and validate one `event: scenario` payload from Go /api/stream. */
+export function parseScenarioEvent(raw: string): ScenarioState | null {
+ let value: unknown
+ try {
+ value = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ if (!value || typeof value !== 'object') return null
+ const candidate = value as Partial
+ if (typeof candidate.version !== 'number' || !Number.isFinite(candidate.version)) return null
+ if (typeof candidate.at !== 'string' || !candidate.at) return null
+ if (!candidate.scenario || typeof candidate.scenario !== 'object') return null
+ const scenario = candidate.scenario as { scenario?: unknown }
+ if (typeof scenario.scenario !== 'string') return null
+ if (!SCENARIOS.includes(scenario.scenario as Scenario)) return null
+ return candidate as ScenarioState
+}
+
+/** A new server version, or a changed scenario id, is a reason to refetch. */
+export function scenarioChanged(
+ previous: ScenarioState | null | undefined,
+ next: ScenarioState,
+): boolean {
+ if (!previous) return true
+ return previous.version !== next.version || previous.scenario.scenario !== next.scenario.scenario
+}
+
+export function scenarioLabel(scenario: Scenario | string | undefined): string {
+ switch (scenario) {
+ case 'sunny-saturday-market':
+ return 'Sunny Saturday + market'
+ case 'rainy-saturday':
+ return 'Rainy Saturday'
+ case 'weekday-event':
+ return 'Wednesday evening event'
+ default:
+ return 'Base week'
+ }
+}
+
+/** Small, dependency-free age label for the last SSE/poll event. */
+export function liveAge(lastEventAt: string, now = Date.now()): string {
+ if (!lastEventAt) return 'no event yet'
+ const time = Date.parse(lastEventAt)
+ if (Number.isNaN(time)) return 'no event yet'
+ const seconds = Math.max(0, Math.round((now - time) / 1000))
+ if (seconds < 5) return 'just now'
+ if (seconds < 60) return `${seconds}s ago`
+ const minutes = Math.round(seconds / 60)
+ return `${minutes} min ago`
+}
diff --git a/test/live.test.ts b/test/live.test.ts
new file mode 100644
index 0000000..03c88e8
--- /dev/null
+++ b/test/live.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest'
+import {
+ liveAge,
+ liveStatus,
+ parseScenarioEvent,
+ scenarioChanged,
+ scenarioLabel,
+ SSE_FAILURES_BEFORE_POLLING,
+} from '../shared/live'
+import type { ScenarioState } from '../shared/types'
+
+const state = (version: number, scenario: ScenarioState['scenario']['scenario'] = 'base'): ScenarioState => ({
+ version,
+ scenario: { scenario },
+ at: '2026-11-14T09:12:00Z',
+})
+
+describe('parseScenarioEvent', () => {
+ it('accepts the Go /api/stream scenario shape', () => {
+ expect(parseScenarioEvent(JSON.stringify(state(7, 'rainy-saturday')))).toEqual(
+ state(7, 'rainy-saturday'),
+ )
+ })
+
+ it('rejects malformed JSON, missing versions and unknown scenarios', () => {
+ expect(parseScenarioEvent('{')).toBeNull()
+ expect(parseScenarioEvent(JSON.stringify({ scenario: { scenario: 'base' }, at: 'x' }))).toBeNull()
+ expect(
+ parseScenarioEvent(JSON.stringify({ version: 1, at: 'x', scenario: { scenario: 'party' } })),
+ ).toBeNull()
+ })
+})
+
+describe('scenarioChanged', () => {
+ it('refreshes on a new version or a new scenario id', () => {
+ expect(scenarioChanged(null, state(1))).toBe(true)
+ expect(scenarioChanged(state(1), state(1))).toBe(false)
+ expect(scenarioChanged(state(1), state(2))).toBe(true)
+ expect(scenarioChanged(state(1, 'base'), state(1, 'rainy-saturday'))).toBe(true)
+ })
+})
+
+describe('liveStatus', () => {
+ const base = {
+ online: true,
+ sseOpen: false,
+ sseFailures: 0,
+ polling: false,
+ pollFailures: 0,
+ }
+
+ it('shows connecting before the first event and live once SSE opens', () => {
+ expect(liveStatus(base)).toBe('connecting')
+ expect(liveStatus({ ...base, sseOpen: true })).toBe('live')
+ })
+
+ it('switches to polling after repeated SSE failures', () => {
+ expect(
+ liveStatus({
+ ...base,
+ sseFailures: SSE_FAILURES_BEFORE_POLLING,
+ polling: true,
+ }),
+ ).toBe('polling')
+ })
+
+ it('reports offline when the browser or both transports are down', () => {
+ expect(liveStatus({ ...base, online: false, sseOpen: true })).toBe('offline')
+ expect(
+ liveStatus({
+ ...base,
+ sseFailures: SSE_FAILURES_BEFORE_POLLING,
+ polling: true,
+ pollFailures: 1,
+ }),
+ ).toBe('offline')
+ })
+})
+
+describe('scenarioLabel and liveAge', () => {
+ it('labels every contract enum', () => {
+ expect(scenarioLabel('sunny-saturday-market')).toBe('Sunny Saturday + market')
+ expect(scenarioLabel('rainy-saturday')).toBe('Rainy Saturday')
+ expect(scenarioLabel('weekday-event')).toBe('Wednesday evening event')
+ expect(scenarioLabel('base')).toBe('Base week')
+ expect(scenarioLabel('unknown')).toBe('Base week')
+ })
+
+ it('renders a short age without a date library', () => {
+ const now = Date.parse('2026-11-14T09:12:10Z')
+ expect(liveAge('', now)).toBe('no event yet')
+ expect(liveAge('2026-11-14T09:12:08Z', now)).toBe('just now')
+ expect(liveAge('2026-11-14T09:11:40Z', now)).toBe('30s ago')
+ expect(liveAge('2026-11-14T09:07:10Z', now)).toBe('5 min ago')
+ })
+})