docs: tighten README quick start and stale comments
ci / check (push) Successful in 1m20s
ci / check (pull_request) Successful in 51s

- Lead with purpose and exact local/CI commands.
- Remove local absolute paths, stale auth notes and unverified claims.
- Keep comments to the reason or invariant they protect.
This commit is contained in:
Noel Sabia committed 2026-11-14 09:16:19 +01:00
1 parent dbb7a009a7
commit 66b80a62fb
14 files changed
+82 -84

No files matched your search

+59 -43
View File
@@ -1,10 +1,38 @@
# PulseCast web # PulseCast web
Nuxt 4 SSR frontend for **PulseCast** — a staffing copilot that turns inner-city Nuxt 4 SSR frontend for **PulseCast**, a staffing copilot that turns inner-city
footfall into a usable next-week shift plan for a Heilbronn retailer. footfall into a next-week shift plan for a Heilbronn retailer. `/plan` is the
decision surface; `/stage` and `/live` present that plan. The map, weather and
forecast are supporting evidence.
The hero screen is **`/plan`**. The map, weather and forecast are supporting ## Quick start
evidence; the decision is the weekly plan.
Node 22 is the CI and Docker version. Real data comes from the Go API on
`http://localhost:8080`; mock mode needs no API.
```bash
npm ci
npm run dev # http://localhost:3000
```
Without the Go API, use the checked-in mock data:
```bash
NUXT_PUBLIC_USE_MOCK=1 npm run dev
```
Build and test exactly as CI does:
```bash
make check # npm ci, npm run build, npm test
```
The built SSR server can also be started directly:
```bash
NUXT_API_INTERNAL_BASE=http://localhost:8080 \
PORT=3000 node .output/server/index.mjs
```
## Stack ## Stack
@@ -18,40 +46,24 @@ Onyx is used for the navigation/app shell, page layout, cards, tables, buttons,
badges, tags, selects, segmented control, slider, stepper, accordion and file badges, tags, selects, segmented control, slider, stepper, accordion and file
upload. The app does not ship a parallel component design system. upload. The app does not ship a parallel component design system.
## Run
```bash
npm ci
npm run dev # http://localhost:3000, expects Go at http://localhost:8080
npm run build # production SSR build in .output/
npm run preview # preview the built app
npm test # heuristic + Go parity tests
```
The built SSR server can also be started directly:
```bash
NUXT_API_INTERNAL_BASE=http://localhost:8080 \
PORT=3000 node .output/server/index.mjs
```
## Live demo: `/stage`, `/live`, `/control` ## Live demo: `/stage`, `/live`, `/control`
```text ```text
browser ──GET /api/stream──► Nuxt Nitro ──proxy──► Go /api/stream browser ──GET /api/stream──► Nuxt Nitro ──proxy──► Go /api/stream
◄── scenario/ping ── ◄────────── SSE hub ◄── scenario/ping ── ◄────────── SSE hub
presenter ──POST /api/scenario──► Nitro (Basic auth + control secret) ──► Go presenter ──POST /api/scenario──► Nitro (Basic auth + control credentials) ──► Go
``` ```
- `app/composables/useLiveScenario.ts` opens one `EventSource` per tab. On a - `app/composables/useLiveScenario.ts` opens one `EventSource` per tab. On a
`scenario` event it updates the shared state and tells the page to refetch; `scenario` event it updates the shared state and tells the page to refetch;
`ping` heartbeats keep the connection marked **Live**. `ping` heartbeats keep the connection marked **Live**.
- After two SSE errors, or when no heartbeat arrives for 32 s (a buffering - After two SSE errors, or when no heartbeat arrives for 32 s (a buffering
proxy), the client closes ranks and polls `GET /api/scenario` every 5 s. The proxy), the client starts polling `GET /api/scenario` every 5 s. The badge
badge shows **Live**, **Polling** or **Offline**, never a silent stale plan. shows **Connecting**, **Live**, **Polling** or **Offline**, never a silent
stale plan.
- `POST /api/scenario` goes through Nitro; the Go control credentials stay in - `POST /api/scenario` goes through Nitro; the Go control credentials stay in
the Node process. `/control` itself requires HTTP Basic auth the Node process. `/control` itself requires HTTP Basic auth
(`CONTROL_USER`/`CONTROL_PASS`); a signed cookie lets the page POST without (`CONTROL_USER`/`CONTROL_PASS`); an HMAC cookie lets the page POST without
re-prompting. `/stage`, `/live` and all public GETs stay open. re-prompting. `/stage`, `/live` and all public GETs stay open.
- `/stage` renders a local SVG QR code (`/api/qr`) pointing at `/live`; no - `/stage` renders a local SVG QR code (`/api/qr`) pointing at `/live`; no
third-party QR service is called. third-party QR service is called.
@@ -102,11 +114,11 @@ real API; mock JSON is an explicit dev fallback only.
| `GET /api/train/:job_id` | `GET /api/train/{job_id}` with server-side control auth | | `GET /api/train/:job_id` | `GET /api/train/{job_id}` with server-side control auth |
| `GET /api/scenarios` | Local UI metadata only (labels/descriptions) | | `GET /api/scenarios` | Local UI metadata only (labels/descriptions) |
`/plan` reads Go `/api/staffing` directly. The four local assumption controls `/plan` reads Go `/api/staffing` through Nitro. The four local assumption
(safety factor, minimum staff, shift length, labour cost) are not query inputs controls (safety factor, minimum staff, shift length, labour cost) are not query
of the Go contract, so changing them renders an explicit **local preview** from inputs of the Go contract, so changing them renders an explicit **local
the API’s forecast hours; “Use API plan” restores the server values. The shared preview** from the API plan’s hourly footfall; “Use API plan” restores the
heuristic is tested against a captured Go response in server values. The shared heuristic is tested against a captured Go response in
`test/fixtures/go-staffing.json`. `test/fixtures/go-staffing.json`.
### Environment ### Environment
@@ -120,14 +132,15 @@ heuristic is tested against a captured Go response in
| `NUXT_PUBLIC_USE_MOCK` / `NUXT_USE_MOCK` | unset | `1` enables the mock fallback | | `NUXT_PUBLIC_USE_MOCK` / `NUXT_USE_MOCK` | unset | `1` enables the mock fallback |
| `NUXT_DISABLE_SSE` | unset | `1` forces the polling fallback (SSE failure drill) | | `NUXT_DISABLE_SSE` | unset | `1` forces the polling fallback (SSE failure drill) |
| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/control` and `POST /api/scenario`; also attached to Go `/api/train` | | `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/control` and `POST /api/scenario`; also attached to Go `/api/train` |
| `CONTROL_TOKEN` | unset | Optional Bearer token for future control auth | | `CONTROL_TOKEN` | unset | Optional Bearer fallback when Basic is not configured; the Go control API requires Basic today |
| `NUXT_PUBLIC_DEMO_NOW` | `2026-11-14T08:12:00Z` | Replay clock used for labels | | `NUXT_PUBLIC_DEMO_NOW` | `2026-11-14T08:12:00Z` | Replay clock used for labels |
Control credentials are read only in the Nitro process. They are never placed Control credentials are read only in the Nitro process. They are never placed
in `runtimeConfig.public` and never reach the browser bundle. `/control` and in `runtimeConfig.public` and never reach the browser bundle. `/control` and
`POST /api/scenario` require Basic auth at Nitro, and Nitro then attaches the `POST /api/scenario` require Basic auth at Nitro, and Nitro then attaches the
same credentials to Go. If `CONTROL_USER`/`CONTROL_PASS` are unset, the control same credentials to Go. In API mode, if `CONTROL_USER`/`CONTROL_PASS` are
surface returns `503 control_auth_unconfigured`; public screens keep working. unset, the control surface returns `503 control_auth_unconfigured`; public
screens keep working.
The K8s web Deployment must mount the same `control-auth` secret as the API The K8s web Deployment must mount the same `control-auth` secret as the API
Deployment: Deployment:
@@ -163,8 +176,8 @@ deployed path are the real API.
| `/control` | Presenter preset buttons; authenticated POST through Nitro | | `/control` | Presenter preset buttons; authenticated POST through Nitro |
| `/about` | Method, metrics, limits, privacy, train form | | `/about` | Method, metrics, limits, privacy, train form |
The layout is checked at **390 px** (single column, mobile Onyx nav, day cards) The layout targets **390 px** (single column, mobile Onyx nav, day cards) and
and **1440 px** (Onyx horizontal nav, two-column plan with tables). **1440 px** (Onyx horizontal nav, two-column plan with tables).
## Plan logic ## Plan logic
@@ -178,9 +191,9 @@ required = max(required, min_staff)
Store hours are 10:00–20:00 Europe/Berlin; default blocks are 4 h; labour cost is Store hours are 10:00–20:00 Europe/Berlin; default blocks are 4 h; labour cost is
€16/h; the default service standard is 25 visitors per staff-hour. The flat €16/h; the default service standard is 25 visitors per staff-hour. The flat
schedule applies the global peak requirement to every store hour, matching Go schedule applies the global peak requirement to every store hour, matching Go
and CONTRACT.md §5. Coverage is at or above requirement by construction because and the contract (§5). Coverage is at or above requirement by construction
each block is sized to its local peak — the UI shows the resulting overstaffed because each block is sized to its local peak — the UI shows the resulting
hours instead of hiding them. overstaffed hours instead of hiding them.
## Checks and CI ## Checks and CI
@@ -200,19 +213,22 @@ staffing, local presets, and 404/400 propagation.
`scripts/smoke-live.mjs` proves the live path: unauthorised POST is rejected, `scripts/smoke-live.mjs` proves the live path: unauthorised POST is rejected,
`/control` authenticates, `/stage` and `/live` render server-side, `/api/qr` `/control` authenticates, `/stage` and `/live` render server-side, `/api/qr`
returns SVG, the SSE proxy emits `retry: 3000` and the initial scenario, a returns SVG, the SSE proxy emits `retry: 3000` and the initial scenario, a
presenter POST produces a `scenario` event (with matching `id` and version) in presenter POST produces a `scenario` event (with matching `id` and version)
well under 2 s, polling reads the same version, and the target staffing and within the 2 s contract target (the script warns if slower), polling reads the
forecast responses differ from base. It restores the base scenario at the end. same version, and the target staffing and forecast responses differ from base.
It restores the base scenario at the end.
## Docker ## Docker
```bash ```bash
docker build -t pulsecast-web . docker build -t pulsecast-web:local .
docker run --rm -p 3000:3000 \ docker run --rm -p 3000:3000 \
-e NUXT_API_INTERNAL_BASE=http://host.docker.internal:8080 \ -e NUXT_API_INTERNAL_BASE=http://host.docker.internal:8080 \
pulsecast-web pulsecast-web:local
``` ```
On Linux, add `--add-host=host.docker.internal:host-gateway` or use the host IP.
The multi-stage image copies only `.output/` into `node:22-alpine`. It creates The multi-stage image copies only `.output/` into `node:22-alpine`. It creates
numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs
`USER 10001:10001`. Kubernetes should set `runAsUser: 10001`, `USER 10001:10001`. Kubernetes should set `runAsUser: 10001`,
+1 -1
View File
@@ -121,7 +121,7 @@ const usingMock = computed(() => ['1', 'true'].includes(String(config.public.use
</div> </div>
<ul class="small" style="margin: 0; padding-left: 1.1rem; display: grid; gap: var(--onyx-density-xs)"> <ul class="small" style="margin: 0; padding-left: 1.1rem; display: grid; gap: var(--onyx-density-xs)">
<li>No PII, MAC addresses or geolocation permission.</li> <li>No PII, MAC addresses or geolocation permission.</li>
<li>Audience sessions use a random ID only.</li> <li>No analytics, tracking cookies or local storage on public screens.</li>
<li>Public read-only screens; control actions are authenticated separately.</li> <li>Public read-only screens; control actions are authenticated separately.</li>
<li>Raw challenge CSV and secrets stay out of this repository.</li> <li>Raw challenge CSV and secrets stay out of this repository.</li>
</ul> </ul>
+1 -1
View File
@@ -98,7 +98,7 @@ async function apply(preset: ScenarioPreset) {
<div> <div>
<OnyxHeadline is="h2">Scenario presets</OnyxHeadline> <OnyxHeadline is="h2">Scenario presets</OnyxHeadline>
<p class="small muted" style="margin: 0"> <p class="small muted" style="margin: 0">
The enum is fixed by CONTRACT.md. Weather and event values match the demo narrative. The enum is fixed by the API contract. Weather and event values match the demo narrative.
</p> </p>
</div> </div>
<OnyxBadge color="info" density="compact">server proxy</OnyxBadge> <OnyxBadge color="info" density="compact">server proxy</OnyxBadge>
+4 -3
View File
@@ -139,8 +139,9 @@ const latestPulse = computed(() => {
</div> </div>
<p class="small muted table-note"> <p class="small muted table-note">
The CSV is static. The replay clock is {{ formatDateTime(demoNow) }}; the last measured point is This is a replay snapshot, not a live sensor feed. The replay clock is
{{ lastPoint ? formatDateTime(lastPoint.t) : '—' }}. No live sensor feed is claimed. {{ formatDateTime(demoNow) }}; the last measured point is
{{ lastPoint ? formatDateTime(lastPoint.t) : '—' }}.
</p> </p>
</OnyxCard> </OnyxCard>
@@ -149,7 +150,7 @@ const latestPulse = computed(() => {
<div> <div>
<OnyxHeadline is="h2">Sensor cluster</OnyxHeadline> <OnyxHeadline is="h2">Sensor cluster</OnyxHeadline>
<p class="small muted" style="margin: 0"> <p class="small muted" style="margin: 0">
Select a sensor to update the reading. Bounds are relative; the basemap is the next map slice. Select a sensor to update the reading. Positions are relative; this is not a geographic map.
</p> </p>
</div> </div>
<OnyxBadge color="info" density="compact">580 m cluster</OnyxBadge> <OnyxBadge color="info" density="compact">580 m cluster</OnyxBadge>
+1
View File
@@ -36,6 +36,7 @@ const {
})), })),
}) })
// Same scenario id with a new version: refresh because the query string does not move.
let lastScenarioId = live.scenarioId let lastScenarioId = live.scenarioId
watch( watch(
() => live.revision, () => live.revision,
+1 -2
View File
@@ -109,8 +109,7 @@ const EMPTY_PLAN: StaffingResponse = {
context_version: '', context_version: '',
} }
// The hero plan comes from the Go API. Local assumption edits only render a // The Go plan is the source; assumption edits render a local preview only.
// preview from the API's own forecast hours; they never replace the API plan.
const { const {
data: apiPlanData, data: apiPlanData,
status, status,
+2 -6
View File
@@ -1,12 +1,8 @@
import { apiBaseUrl, isMockMode } from '../utils/api' import { apiBaseUrl, isMockMode } from '../utils/api'
/** /**
* Same-origin SSE proxy. The browser never talks to Go directly, so the * Same-origin SSE proxy: the browser talks only to Nitro, so CORS stays closed.
* Cloudflare/K8s CORS surface stays closed and the stream can be cached or * proxyRequest forwards chunks as they arrive, preserving heartbeats and retry hints.
* 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) => { export default defineEventHandler(async (event) => {
if (isMockMode() || process.env.NUXT_DISABLE_SSE === '1') { if (isMockMode() || process.env.NUXT_DISABLE_SSE === '1') {
+1 -2
View File
@@ -35,8 +35,7 @@ export default defineEventHandler(async (event) => {
} }
} }
// Stream the multipart CSV to Go unchanged. The control credentials are // Forward the raw multipart CSV to Go; control credentials stay in this process.
// attached by the Nitro process and never reach the browser bundle.
const contentType = getRequestHeader(event, 'content-type') ?? '' const contentType = getRequestHeader(event, 'content-type') ?? ''
if (!contentType) { if (!contentType) {
throw createError({ throw createError({
+2 -4
View File
@@ -39,10 +39,8 @@ function isProtected(event: import('h3').H3Event): boolean {
} }
/** /**
* Presenter-only control surface. Basic auth is checked in Nitro; on success * Presenter control: Basic auth at Nitro, then an HMAC cookie (signed with
* an HMAC cookie (signed with CONTROL_PASS) lets the page POST /api/scenario * CONTROL_PASS) lets /control POST without re-prompting. Public GETs stay open.
* without re-prompting. The browser never receives the Go credentials, and
* /stage, /live and all public GETs stay open.
*/ */
export default defineEventHandler((event) => { export default defineEventHandler((event) => {
if (!isProtected(event)) return if (!isProtected(event)) return
+5 -10
View File
@@ -1,6 +1,5 @@
// Server-side Go API client. Every Nitro route uses this module so the browser // Server-side Go API client. Nitro routes use it so the browser only talks to
// only ever talks to the Nuxt origin: the Go base URL and the control // this origin and control credentials stay in the Node process.
// credentials stay in the Node process.
interface ApiErrorEnvelope { interface ApiErrorEnvelope {
error?: { code?: string; message?: string } error?: { code?: string; message?: string }
@@ -39,7 +38,7 @@ export function apiBaseUrl(): string {
).replace(/\/+$/, '') ).replace(/\/+$/, '')
} }
/** True only when NUXT_USE_MOCK=1 / NUXT_PUBLIC_USE_MOCK=1 is set. */ /** Mock mode is opt-in via NUXT_USE_MOCK or NUXT_PUBLIC_USE_MOCK (1/true). */
export function isMockMode(): boolean { export function isMockMode(): boolean {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const raw = const raw =
@@ -54,8 +53,7 @@ function controlAuthorization(): string | undefined {
if (user && pass) return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}` if (user && pass) return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`
const token = envValue('CONTROL_TOKEN', 'NUXT_CONTROL_TOKEN') || String(config.controlToken ?? '') const token = envValue('CONTROL_TOKEN', 'NUXT_CONTROL_TOKEN') || String(config.controlToken ?? '')
// Go currently validates Basic auth; Bearer is accepted here for the future // Go requires Basic today; Bearer is a fallback for a future token-based API.
// token-based control surface without exposing the token to the browser.
if (token) return `Bearer ${token}` if (token) return `Bearer ${token}`
return undefined return undefined
} }
@@ -121,10 +119,7 @@ export async function apiRequest<T>(path: string, options: ApiRequestOptions = {
return response._data as T return response._data as T
} }
/** /** Forward a training upload and keep Go's status code for 202/4xx/5xx. */
* Forward a request body (training upload) and preserve Go's status code and
* JSON body, including 202/400/409/502 responses that are part of the flow.
*/
export async function apiForward<T>( export async function apiForward<T>(
event: import('h3').H3Event, event: import('h3').H3Event,
path: string, path: string,
+2 -3
View File
@@ -1,6 +1,5 @@
// Server-side mock dataset. Shapes follow /home/noel/Documents/Hackathon_2026/CONTRACT.md. // Server-side mock dataset. Shapes follow the Go API contract; files are imported
// The files are imported (not read from disk at runtime) so the Nitro build bundles them // so Nitro bundles them and mock mode renders without the Go API.
// into the SSR output and the app renders before the Go API exists.
import context from '../../mock/context.json' import context from '../../mock/context.json'
import demo from '../../mock/demo.json' import demo from '../../mock/demo.json'
import meta from '../../mock/meta.json' import meta from '../../mock/meta.json'
+1 -2
View File
@@ -18,8 +18,7 @@ export function createMockTrainJob(model: 'small' | 'forecast', filename: string
const now = new Date().toISOString() const now = new Date().toISOString()
const job: MockTrainJob = { const job: MockTrainJob = {
job_id: `mock-${Date.now().toString(36)}`, job_id: `mock-${Date.now().toString(36)}`,
// The mock completes immediately. Replace this with polling of GET /api/train/{job_id} // The mock completes immediately; the real path polls GET /api/train/{job_id}.
// once the Go/FastAPI service exists.
status: 'succeeded', status: 'succeeded',
model, model,
started_at: now, started_at: now,
+1 -5
View File
@@ -84,11 +84,7 @@ export function hhmm(hour: number): string {
return `${String(hour).padStart(2, '0')}:00` return `${String(hour).padStart(2, '0')}:00`
} }
/** /** Demo perturbations for the mock fallback; the Go API applies scenarios from ML output. */
* Mock scenario behaviour. The contract defines the scenario enum but not the
* size of each perturbation; these multipliers are demo assumptions and are
* shown in the UI. The Go/ML implementation must publish the same numbers.
*/
export function applyScenario(points: Point[], scenario: Scenario): Point[] { export function applyScenario(points: Point[], scenario: Scenario): Point[] {
if (scenario === 'base') return points if (scenario === 'base') return points
return points.map((point) => { return points.map((point) => {
+1 -2
View File
@@ -1,5 +1,4 @@
// Canonical shapes from /home/noel/Documents/Hackathon_2026/CONTRACT.md (v1 draft). // Canonical wire shapes for the Go API; keep them in sync with the contract.
// Keep these in sync with the Go API; the UI consumes exactly these fields.
export const HORIZONS = ['15m', '1h', '48h', '7d'] as const export const HORIZONS = ['15m', '1h', '48h', '7d'] as const
export type Horizon = (typeof HORIZONS)[number] export type Horizon = (typeof HORIZONS)[number]