From c24cb726401e81cd16d5eb100b7b0a8295be4831 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sat, 14 Nov 2026 17:29:18 +0200 Subject: [PATCH] feat(terminal): pairing, sign-in per mode, device app router and live states (platform-v2 3.1c) - Pairing screen: requests a code, shows it big, polls with the secret, new code on expiry, keeps the device token; "removed from the venue" notice after a revoke. - Sign-in per device mode: PIN (name + PinPad), tap your name, password (name + password), none (straight into the app). Names = holders of .access, refreshed every 30 s and on reconnect. Slim bar with screen, user and Sign out; idle sign-out after the device's auto_sign_out_minutes; hourly token refresh (same session). - DeviceProvider: GET /api/devices/me (retried while unreachable), session, the live connection with credentials in the first frame (device.updated -> reload, app moved -> sign out, device.revoked -> forget, session.ended -> sign out), offline banner; useLiveEvent for apps. Screen choice is pure (device/flow.js, unit-tested). - Blocked screen: app turned off / not licensed / device refused, recovers by itself. - @xenia/access AccessProvider: autoRetryMs (retry bootstrap while unreachable). - Tests: terminal unit tests (screen choice, live actions, idle, pairing polls), new tests/e2e/terminal.mjs (18 checks), manager.mjs owner flow now pairs and signs in on the real terminal screen; run-all runs terminal.mjs. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- packages/access/src/AccessProvider.jsx | 11 +- packages/i18n/locales/el/terminal.json | 30 ++++- packages/i18n/locales/en/terminal.json | 30 ++++- terminal/eslint.config.js | 3 + terminal/src/App.jsx | 44 +++---- terminal/src/api/client.js | 38 ++++-- terminal/src/device/DeviceProvider.jsx | 148 +++++++++++++++++++++++ terminal/src/device/context.js | 18 +++ terminal/src/device/flow.js | 64 ++++++++++ terminal/src/screens/AppScreen.jsx | 57 +++++++++ terminal/src/screens/BlockedScreen.jsx | 28 +++++ terminal/src/screens/PairingScreen.jsx | 83 +++++++++++++ terminal/src/screens/SignInScreen.jsx | 127 ++++++++++++++++++++ terminal/src/screens/StartScreen.jsx | 20 ---- terminal/src/screens/Terminal.jsx | 39 +++++++ terminal/tests/terminal.test.mjs | 48 +++++++- tests/e2e/README.md | 5 +- tests/e2e/lib/proc.mjs | 12 ++ tests/e2e/manager.mjs | 47 ++++---- tests/e2e/run-all.mjs | 1 + tests/e2e/terminal.mjs | 156 +++++++++++++++++++++++++ 22 files changed, 928 insertions(+), 83 deletions(-) create mode 100644 terminal/src/device/DeviceProvider.jsx create mode 100644 terminal/src/device/context.js create mode 100644 terminal/src/device/flow.js create mode 100644 terminal/src/screens/AppScreen.jsx create mode 100644 terminal/src/screens/BlockedScreen.jsx create mode 100644 terminal/src/screens/PairingScreen.jsx create mode 100644 terminal/src/screens/SignInScreen.jsx delete mode 100644 terminal/src/screens/StartScreen.jsx create mode 100644 terminal/src/screens/Terminal.jsx create mode 100644 tests/e2e/terminal.mjs diff --git a/docs/README.md b/docs/README.md index 8c63228..cd70af9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,7 +50,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `install.sh` | Site installer. **Writes its own copy of the proxy config.** | | `docker-compose.yml` / `docker-compose.dev.yml` | Prod (pull images) / dev override (build + expose ports) | | `package.json`, `package-lock.json`, `packages/` | **npm workspace** for the frontends (D-15): `waiter_pwa`, `manager_dashboard`, `terminal` and the shared `packages/{ui,i18n,api,access}` (imported from source, no build step). One lockfile at this root; the apps have none of their own. | -| `terminal/` | The terminal app (phase 3): `src/apps/registry.js` (which apps a screen runs, lazy chunks), `src/device/storage.js` (device + session tokens), `src/api/client.js` (`X-Xenia-Device` on every request). Lint covers all of `src` | +| `terminal/` | The terminal app (phase 3): `src/device/DeviceProvider.jsx` (the device's `/me`, who is signed in, the live connection with credentials in the first frame, offline; apps listen with `useLiveEvent`), `src/device/flow.js` (which screen shows when: pairing → sign-in → app / blocked; pure, unit-tested), `src/screens/` (pairing, sign-in per mode, blocked, app + bar), `src/apps/registry.js` (which apps a screen runs, lazy chunks), `src/device/storage.js` (device + session tokens), `src/api/client.js` (`X-Xenia-Device` on every request; 401 / unreachable listeners). The screen follows the device, not the URL. Lint covers all of `src` | | `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` | | `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) | | `packages/access/` | `` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, ``, `` (CS-18) | diff --git a/packages/access/src/AccessProvider.jsx b/packages/access/src/AccessProvider.jsx index 3405501..3984054 100644 --- a/packages/access/src/AccessProvider.jsx +++ b/packages/access/src/AccessProvider.jsx @@ -20,9 +20,11 @@ import { OverrideHost } from './OverrideHost.jsx' * for `client` (OverrideHost), unless override={false} * Until the bootstrap for the current token has loaded it renders `loading` (a spinner by * default); if it fails, an error screen with Retry. Nothing below ever sees a half-loaded state. + * autoRetryMs (unattended screens, e.g. the terminal): when the server can't be reached + * (offline or 5xx), retry by itself every autoRetryMs as well. */ export function AccessProvider({ - client, token = null, i18n, deviceLanguage, override = true, loading, children, + client, token = null, i18n, deviceLanguage, override = true, loading, autoRetryMs = 0, children, }) { const [state, setState] = useState({ data: null, forToken: undefined, error: null }) @@ -40,6 +42,13 @@ export function AccessProvider({ useEffect(() => { load() }, [load]) + const unreachable = !!state.error && (state.error.offline || state.error.status >= 500) + useEffect(() => { + if (!autoRetryMs || !unreachable) return undefined + const id = setTimeout(load, autoRetryMs) + return () => clearTimeout(id) + }, [autoRetryMs, unreachable, state.error, load]) + const value = useMemo(() => { const d = state.data if (!d) return null diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index 2d19afd..aaff36f 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -1,7 +1,33 @@ { "start": { - "title": "Τερματικό Xenia", - "notPaired": "Αυτή η οθόνη δεν έχει συζευχθεί ακόμη με το κατάστημα." + "title": "Τερματικό Xenia" + }, + "pairing": { + "intro": "Συζεύξτε αυτή την οθόνη με το κατάστημα:", + "howTo": "Στη διαχείριση, ανοίξτε Συσκευές → Σύζευξη συσκευής και πληκτρολογήστε αυτόν τον κωδικό.", + "removed": "Αυτή η οθόνη αφαιρέθηκε από το κατάστημα. Κάντε ξανά σύζευξη για να τη χρησιμοποιήσετε." + }, + "signIn": { + "title": "Ποιος συνδέεται;", + "enterPin": "Πληκτρολογήστε το PIN σας", + "password": "Κωδικός", + "submit": "Σύνδεση", + "back": "Πίσω", + "empty": "Κανείς δεν μπορεί να συνδεθεί εδώ ακόμη", + "emptyBody": "Δώστε σε κάποιον το δικαίωμα {{app}} στο Προσωπικό, στη διαχείριση." + }, + "blocked": { + "off": "Η εφαρμογή {{app}} είναι απενεργοποιημένη", + "offBody": "Ένας διαχειριστής μπορεί να την ενεργοποιήσει στις Εφαρμογές. Τότε η οθόνη ξεκινά μόνη της.", + "notLicensed": "Η εφαρμογή {{app}} δεν περιλαμβάνεται στην άδεια του καταστήματος", + "notLicensedBody": "Ζητήστε να προστεθεί στην άδεια. Τότε η οθόνη ξεκινά μόνη της.", + "refused": "Αυτή η οθόνη δεν μπορεί να χρησιμοποιηθεί αυτή τη στιγμή" + }, + "bar": { + "signOut": "Αποσύνδεση" + }, + "offline": { + "banner": "Δεν υπάρχει σύνδεση με τον διακομιστή του καταστήματος. Νέα προσπάθεια…" }, "apps": { "placeholder": "Αυτή η οθόνη τρέχει: {{app}}. Οι οθόνες της ετοιμάζονται.", diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 75b8f93..8521ed0 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -1,7 +1,33 @@ { "start": { - "title": "Xenia terminal", - "notPaired": "This screen isn't paired with the venue yet." + "title": "Xenia terminal" + }, + "pairing": { + "intro": "Pair this screen with the venue:", + "howTo": "In the manager, open Devices → Pair a device and type this code.", + "removed": "This screen was removed from the venue. Pair it again to use it." + }, + "signIn": { + "title": "Who's signing in?", + "enterPin": "Enter your PIN", + "password": "Password", + "submit": "Sign in", + "back": "Back", + "empty": "Nobody can sign in here yet", + "emptyBody": "Give someone the {{app}} permission under Staff in the manager." + }, + "blocked": { + "off": "{{app}} is turned off", + "offBody": "A manager can turn it on under Apps. This screen starts by itself then.", + "notLicensed": "{{app}} isn't in the venue's license", + "notLicensedBody": "Ask for it to be added to the license. This screen starts by itself then.", + "refused": "This screen can't be used right now" + }, + "bar": { + "signOut": "Sign out" + }, + "offline": { + "banner": "Can't reach the venue server. Trying again…" }, "apps": { "placeholder": "This screen runs {{app}}. Its screens are being built.", diff --git a/terminal/eslint.config.js b/terminal/eslint.config.js index 4da5a91..8f4d803 100644 --- a/terminal/eslint.config.js +++ b/terminal/eslint.config.js @@ -26,6 +26,9 @@ export default defineConfig([ }, rules: { 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }], + // Loading data in an effect (`useEffect(() => { load() }, [load])`, setState after the + // await) is flagged too; it's what the screens do, so a warning, as in the manager. + 'react-hooks/set-state-in-effect': 'warn', }, }, { diff --git a/terminal/src/App.jsx b/terminal/src/App.jsx index 8be8d00..8b5fe5c 100644 --- a/terminal/src/App.jsx +++ b/terminal/src/App.jsx @@ -1,17 +1,20 @@ -// The terminal app's root (plan step 3.1b, APPS_PLATFORM D-2, §9): one web app for every -// paired screen, served on :8082 (LAN only). loads the platform bootstrap -// (venue, language, modules) with the screen's session, if any. -// Routes in 3.1b: "/" the start screen, "/app/:appKey" an app by key (its lazy chunk). -// 3.1c replaces them with pairing → sign-in → the device's own app (by GET /api/devices/me). -import { lazy, Suspense, useState } from 'react' -import { BrowserRouter, Route, Routes, useParams } from 'react-router-dom' +// The terminal app's root (plan steps 3.1b, 3.1c; APPS_PLATFORM D-2, D-8, §9): one web app +// for every paired screen, served on :8082 (LAN only). +// DeviceProvider the device (pairing, GET /api/devices/me), who is signed in, the live +// connection, offline +// AccessProvider platform bootstrap (venue, language, modules, keys) for that session; +// retries by itself while the server can't be reached (unattended screens) +// Terminal pairing → sign-in → the device's own app, or a "can't run" screen +// The screen follows the device, not the URL; only the dev pages have routes. +import { lazy, Suspense } from 'react' +import { BrowserRouter, Route, Routes } from 'react-router-dom' import { AccessProvider } from '@xenia/access' import { createI18n } from '@xenia/i18n' import { Spinner } from '@xenia/ui' import client from './api/client' -import AppHost from './apps/AppHost' -import { deviceStore } from './device/storage' -import StartScreen from './screens/StartScreen' +import DeviceProvider from './device/DeviceProvider' +import { useDevice } from './device/context' +import Terminal from './screens/Terminal' const i18n = createI18n({ defaultNS: 'terminal' }) @@ -20,27 +23,24 @@ const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null const loading =
+const AUTO_RETRY_MS = 5_000 -function AppRoute() { - const { appKey } = useParams() - return +function Root() { + const { sessionKey } = useDevice() + return ( + + + + ) } export default function App() { - const [token] = useState(() => deviceStore.sessionToken()) return ( {UiGallery && } />} {I18nSample && } />} - - - } /> - } /> - -
- } /> + } /> ) diff --git a/terminal/src/api/client.js b/terminal/src/api/client.js index 048e6dc..6389224 100644 --- a/terminal/src/api/client.js +++ b/terminal/src/api/client.js @@ -5,26 +5,42 @@ import { deviceStore } from '../device/storage' // The shared client (@xenia/api, CS-18). Same origin: the image's nginx (or Vite in dev) // forwards /api to the backend. Every request carries the screen's device token // (X-Xenia-Device) and, when someone is signed in, their session token. -// A 401 = the session ended (signed out elsewhere, idle, device reassigned): drop the session -// token; the screen goes back to its sign-in (3.1c). Pairing/sign-in forms pass -// { xenia: { ignoreUnauthorized: true } } for their own 401s. -const listeners = new Set() +// - A 401 = the session ended (signed out elsewhere, idle, device reassigned) or the device +// was removed: DeviceProvider listens (onUnauthorized) and signs out / forgets the device. +// Pairing and sign-in forms pass { xenia: { ignoreUnauthorized: true } } for their own 401s. +// - No answer at all = the venue server is unreachable: DeviceProvider shows a banner until +// a request gets an answer again (onReachable). +const unauthorized = new Set() +const reachability = new Set() const client = createApiClient({ axios, baseURL: '', getToken: () => deviceStore.sessionToken(), getDeviceToken: () => deviceStore.deviceToken(), - onUnauthorized: x => { - deviceStore.setSessionToken(null) - listeners.forEach(fn => fn(x)) - }, + onUnauthorized: x => unauthorized.forEach(fn => fn(x)), + onOffline: () => reachability.forEach(fn => fn(false)), }) -/** Called with err.xenia whenever a request comes back 401 (see above). */ +// Any answer, even an error, means the server is there +client.interceptors.response.use( + res => { reachability.forEach(fn => fn(true)); return res }, + err => { if (err?.response) reachability.forEach(fn => fn(true)); throw err }, +) + +/** fn(err.xenia) whenever a request comes back 401. Returns an unsubscribe function. */ export function onUnauthorized(fn) { - listeners.add(fn) - return () => listeners.delete(fn) + unauthorized.add(fn) + return () => unauthorized.delete(fn) } +/** fn(true | false) whenever the server answers / can't be reached. */ +export function onReachable(fn) { + reachability.add(fn) + return () => reachability.delete(fn) +} + +// Dev builds only: lets the e2e suite (tests/e2e/terminal.mjs) drive requests through this client +if (import.meta.env?.DEV) window.__xeniaClient = client + export default client diff --git a/terminal/src/device/DeviceProvider.jsx b/terminal/src/device/DeviceProvider.jsx new file mode 100644 index 0000000..1ff4f88 --- /dev/null +++ b/terminal/src/device/DeviceProvider.jsx @@ -0,0 +1,148 @@ +// The screen's own state (plan step 3.1c): which device it is (GET /api/devices/me), who +// is signed in on it, its live connection, and whether the venue server answers. +// +// - Device token: from pairing (PairingScreen → paired(token)); forgotten when the device is +// removed (device.revoked / device.not_paired, from any request, the live connection or +// GET /me) → the pairing screen, with a notice. +// - Session: signIn(token) after POST /api/auth/login {client: "terminal"}; signOut() ends it. +// `sessionKey` changes only on sign-in/out (not on the hourly token refresh), so +// reloads bootstrap exactly then. +// - Live: one connection per device + session, credentials in the first frame (3.1a): +// device.updated → re-read /me (app moved → sign out), device.revoked → forget, +// session.ended → sign out; `ready` (every reconnect) → re-read /me. Apps listen with +// useLiveEvent(type, fn). +// - Offline: any request without an answer sets `offline` (banner); any answer clears it. +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { createLiveClient, wsUrlFor } from '@xenia/api' +import client, { onReachable, onUnauthorized } from '../api/client' +import { DeviceContext } from './context' +import { deviceGone, liveAction, refusedAction } from './flow' +import { deviceStore } from './storage' + +const ME_RETRY_MS = 5_000 +const REFRESH_EVERY_MS = 60 * 60_000 // session tokens last 8 h; the session itself stays the same + +let keySeq = 0 +const newKey = () => `s${Date.now()}-${++keySeq}` + +export default function DeviceProvider({ children }) { + const [deviceToken, setDeviceToken] = useState(() => deviceStore.deviceToken()) + const [sessionKey, setSessionKey] = useState(() => (deviceStore.sessionToken() ? newKey() : null)) + const [me, setMe] = useState(null) + const [meError, setMeError] = useState(null) + const [offline, setOffline] = useState(false) + const [notice, setNotice] = useState(null) // e.g. 'removed' on the pairing screen + const listeners = useRef(new Map()) // live event type -> Set(fn) + const liveRef = useRef(null) + + const dropSession = useCallback(() => { + if (!deviceStore.sessionToken()) return + deviceStore.setSessionToken(null) + setSessionKey(null) + }, []) + + const forget = useCallback(reason => { + deviceStore.forget() + setDeviceToken(null) + setSessionKey(null) + setMe(null) + setMeError(null) + if (reason) setNotice(reason) + }, []) + + const loadMe = useCallback(async () => { + if (!deviceStore.deviceToken()) return + try { + const { data } = await client.get('/api/devices/me', { xenia: { ignoreUnauthorized: true, noOverride: true } }) + setMe(data) + setMeError(null) + } catch (err) { + const x = err.xenia || {} + if (deviceGone(x.code)) forget('removed') + else setMeError(x) + } + }, [forget]) + + // GET /me whenever the device changes; again every few seconds while it can't be loaded + useEffect(() => { loadMe() }, [deviceToken, loadMe]) + useEffect(() => { + if (!deviceToken || me || !meError) return undefined + const id = setTimeout(loadMe, ME_RETRY_MS) + return () => clearTimeout(id) + }, [deviceToken, me, meError, loadMe]) + + // 401s from any request; server reachability + useEffect(() => onUnauthorized(x => { + if (deviceGone(x.code)) forget('removed') + else dropSession() + }), [forget, dropSession]) + useEffect(() => onReachable(up => setOffline(!up)), []) + + // The live connection + useEffect(() => { + if (!deviceToken) return undefined + let seq = 0 + const emit = (type, data) => listeners.current.get(type)?.forEach(fn => { try { fn(data) } catch { /* one listener must not stop the others */ } }) + const act = action => { + if (action === 'forget') forget('removed') + else if (action === 'sign_out') dropSession() + else if (action === 'reload') loadMe() + else if (action === 'reload_and_sign_out') { dropSession(); loadMe() } + } + const live = createLiveClient({ + url: () => wsUrlFor('/api/ws/connect'), + credentials: () => ({ device: deviceStore.deviceToken(), token: deviceStore.sessionToken() }), + cursor: { load: () => seq, save: s => { seq = s } }, + onEvent: (type, data) => { act(liveAction(type, data)); emit(type, data) }, + onReady: () => { setOffline(false); loadMe(); emit('ready', null) }, + onRefused: code => act(refusedAction(code)), + }) + liveRef.current = live + live.start() + return () => { live.stop(); liveRef.current = null } + }, [deviceToken, sessionKey, forget, dropSession, loadMe]) + + // Keep a long shift signed in: a fresh token for the same session every hour + useEffect(() => { + if (!sessionKey) return undefined + const id = setInterval(async () => { + try { + const { data } = await client.post('/api/auth/refresh') + if (deviceStore.sessionToken()) deviceStore.setSessionToken(data.access_token) + } catch { /* a 401 signs out through onUnauthorized; offline: next hour */ } + }, REFRESH_EVERY_MS) + return () => clearInterval(id) + }, [sessionKey]) + + const subscribe = useCallback((type, fn) => { + if (!listeners.current.has(type)) listeners.current.set(type, new Set()) + listeners.current.get(type).add(fn) + return () => listeners.current.get(type)?.delete(fn) + }, []) + + const value = useMemo(() => ({ + deviceToken, me, meError, offline, notice, sessionKey, + session: sessionKey ? deviceStore.sessionToken() : null, + paired(token) { + deviceStore.setDeviceToken(token) + setNotice(null) + setMe(null) + setDeviceToken(token) + }, + signIn(token) { + deviceStore.setSessionToken(token) + setSessionKey(newKey()) + }, + async signOut() { + try { await client.post('/api/auth/logout', null, { xenia: { ignoreUnauthorized: true, noOverride: true } }) } catch { /* ended anyway */ } + dropSession() + }, + retry() { + loadMe() + liveRef.current?.reconnect() + }, + subscribe, + }), [deviceToken, me, meError, offline, notice, sessionKey, dropSession, loadMe, subscribe]) + + return {children} +} diff --git a/terminal/src/device/context.js b/terminal/src/device/context.js new file mode 100644 index 0000000..7c14c94 --- /dev/null +++ b/terminal/src/device/context.js @@ -0,0 +1,18 @@ +import { createContext, useContext, useEffect, useRef } from 'react' + +/** DeviceProvider's value: device, session, live connection, offline (see DeviceProvider.jsx). */ +export const DeviceContext = createContext(null) + +export function useDevice() { + const v = useContext(DeviceContext) + if (!v) throw new Error('useDevice() needs ') + return v +} + +/** Run handler(data) for every live event of `type` ('ready' after each reconnect: refetch). */ +export function useLiveEvent(type, handler) { + const { subscribe } = useDevice() + const ref = useRef(handler) + useEffect(() => { ref.current = handler }) + useEffect(() => subscribe(type, data => ref.current(data)), [subscribe, type]) +} diff --git a/terminal/src/device/flow.js b/terminal/src/device/flow.js new file mode 100644 index 0000000..a9d2119 --- /dev/null +++ b/terminal/src/device/flow.js @@ -0,0 +1,64 @@ +// What a paired screen shows, as pure functions (plan step 3.1c). Unit-tested in +// terminal/tests; the React side is DeviceProvider + the screens. +// +// pairing no device token (never paired, or removed: forgotten) +// loading paired, GET /api/devices/me not answered yet +// blocked the server refuses the device for a reason a manager must fix (license limit) +// app_off its app is turned off or not licensed (me.app_status) +// sign_in its app signs people in and nobody is signed in +// app the app itself + +export const DEVICE_GONE = ['device.revoked', 'device.not_paired'] + +export function screenFor({ deviceToken, me, meError, session }) { + if (!deviceToken) return 'pairing' + if (!me) return meError && !meError.offline ? 'blocked' : 'loading' + if (me.app_status && me.app_status !== 'ok') return 'app_off' + if (me.login_mode === 'none') return 'app' + return session ? 'app' : 'sign_in' +} + +/** The device was removed or its token is unknown: forget it and pair again. */ +export function deviceGone(code) { + return DEVICE_GONE.includes(code) +} + +/** Shared screens sign people out after `minutes` without a touch (device config; 0 = never). */ +export function idleExpired(lastActivityMs, minutes, nowMs) { + return Number(minutes) > 0 && nowMs - lastActivityMs >= Number(minutes) * 60_000 +} + +/** "K7M2QX" → "K7M 2QX": easier to read across a kitchen and to type. */ +export function formatCode(code) { + const c = String(code || '') + return c.length === 6 ? `${c.slice(0, 3)} ${c.slice(3)}` : c +} + +/** + * What to do after a pairing poll: { next: 'wait' | 'paired' | 'new_code' | 'retry', token? }. + * `result` = the poll's JSON, or `error` = err.xenia when it failed. + */ +export function pollOutcome({ result, error, expiresAt, now = Date.now() }) { + if (error) { + if (error.code === 'device.pair_code_invalid') return { next: 'new_code' } + return { next: 'retry' } // offline, server error: keep the same code, try again + } + if (result?.status === 'paired' && result.device_token) return { next: 'paired', token: result.device_token } + if (expiresAt && Date.parse(expiresAt) <= now) return { next: 'new_code' } + return { next: 'wait' } +} + +/** Live events that change what the screen shows, by type. */ +export function liveAction(type, data) { + if (type === 'device.revoked') return 'forget' + if (type === 'session.ended') return 'sign_out' + if (type === 'device.updated') return data?.app_key ? 'reload_and_sign_out' : 'reload' // app_key: moved to another app + return null +} + +/** A refused live connection: what it means for the screen. */ +export function refusedAction(code) { + if (deviceGone(code)) return 'forget' + if (code === 'auth.session_ended' || code === 'device.required') return 'sign_out' + return null +} diff --git a/terminal/src/screens/AppScreen.jsx b/terminal/src/screens/AppScreen.jsx new file mode 100644 index 0000000..60e367e --- /dev/null +++ b/terminal/src/screens/AppScreen.jsx @@ -0,0 +1,57 @@ +// The device's own app (plan step 3.1c), by me.app_key (AppHost loads its chunk). Apps that +// sign people in get a slim bar: screen name, who is signed in, Sign out. Shared screens sign +// out after `auto_sign_out_minutes` without a touch (device config, 3.1a; 0 = never). +import { useEffect, useRef } from 'react' +import { LogOut } from 'lucide-react' +import { useAccess } from '@xenia/access' +import { useTranslation } from '@xenia/i18n' +import { Button } from '@xenia/ui' +import AppHost from '../apps/AppHost' +import { useDevice } from '../device/context' +import { idleExpired } from '../device/flow' + +const IDLE_CHECK_MS = 15_000 + +export default function AppScreen() { + const { me, signOut } = useDevice() + const withUser = me.login_mode !== 'none' + useIdleSignOut(withUser ? me.config?.auto_sign_out_minutes : 0, signOut) + return ( +
+ {withUser && } +
+
+ ) +} + +function TerminalBar({ onSignOut }) { + const { t } = useTranslation('terminal') + const { user } = useAccess() + const { me } = useDevice() + return ( +
+ {me.name} + + {user?.nickname || user?.full_name} + +
+ ) +} + +function useIdleSignOut(minutes, signOut) { + const last = useRef(0) + const signOutRef = useRef(signOut) + useEffect(() => { signOutRef.current = signOut }) + useEffect(() => { + if (!(Number(minutes) > 0)) return undefined + last.current = Date.now() + const touch = () => { last.current = Date.now() } + const events = ['pointerdown', 'keydown', 'wheel'] + events.forEach(e => window.addEventListener(e, touch, { passive: true })) + const id = setInterval(() => { if (idleExpired(last.current, minutes, Date.now())) signOutRef.current() }, IDLE_CHECK_MS) + return () => { + clearInterval(id) + events.forEach(e => window.removeEventListener(e, touch)) + } + }, [minutes]) +} diff --git a/terminal/src/screens/BlockedScreen.jsx b/terminal/src/screens/BlockedScreen.jsx new file mode 100644 index 0000000..30ae9f6 --- /dev/null +++ b/terminal/src/screens/BlockedScreen.jsx @@ -0,0 +1,28 @@ +// A paired screen that can't run its app (plan step 3.1c): the app is turned off or not in +// the license (me.app_status), or the server refuses the device itself (e.g. more screens +// than the license allows). It changes by itself: module on/off sends device.updated live, +// and GET /me is retried every few seconds while refused. +import { PowerOff } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { EmptyState } from '@xenia/ui' +import { useDevice } from '../device/context' + +export default function BlockedScreen() { + const { t } = useTranslation('terminal') + const { me, meError } = useDevice() + let title, body + if (me) { + const app = t(`modules:${me.app_key}.name`) + title = me.app_status === 'module.not_licensed' ? t('blocked.notLicensed', { app }) : t('blocked.off', { app }) + body = me.app_status === 'module.not_licensed' ? t('blocked.notLicensedBody') : t('blocked.offBody') + } else { + title = t('blocked.refused') + body = errorMessage({ xenia: meError }, t) + } + return ( +
+ } title={title} description={body} /> +
+ ) +} diff --git a/terminal/src/screens/PairingScreen.jsx b/terminal/src/screens/PairingScreen.jsx new file mode 100644 index 0000000..ce6867e --- /dev/null +++ b/terminal/src/screens/PairingScreen.jsx @@ -0,0 +1,83 @@ +// Pairing (plan step 3.1c, D-8): the screen asks for a code (POST /api/devices/pair-request), +// shows it big, and polls GET /pair-request/{code} with its secret until a manager enters +// the code under Devices. Expired or refused codes are replaced by a new one; while the +// server can't be reached it keeps trying with the same code. +import { useEffect, useRef, useState } from 'react' +import { MonitorSmartphone } from 'lucide-react' +import { useAccess } from '@xenia/access' +import { errorMessage, parseError } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Spinner } from '@xenia/ui' +import client from '../api/client' +import { useDevice } from '../device/context' +import { formatCode, pollOutcome } from '../device/flow' + +const RETRY_MS = 5_000 +const RATE_LIMITED_MS = 60_000 +const quiet = { xenia: { ignoreUnauthorized: true, noOverride: true } } +const wait = ms => new Promise(r => setTimeout(r, ms)) + +export default function PairingScreen() { + const { t } = useTranslation('terminal') + const { venue } = useAccess() + const { paired, notice } = useDevice() + const [req, setReq] = useState(null) // { code, expires_at } + const [problem, setProblem] = useState(null) + const pairedRef = useRef(paired) // the loop below must not restart (new code) on re-renders + useEffect(() => { pairedRef.current = paired }) + + useEffect(() => { + let alive = true + async function run() { + while (alive) { + let r + try { + r = (await client.post('/api/devices/pair-request', null, quiet)).data + } catch (err) { + if (!alive) return + setReq(null) + setProblem(errorMessage(err, t)) + await wait(err.xenia?.code === 'device.pair_rate_limited' ? RATE_LIMITED_MS : RETRY_MS) + continue + } + if (!alive) return + setReq(r) + setProblem(null) + for (;;) { + await wait((r.poll_after_s || 3) * 1000) + if (!alive) return + let result = null + let error = null + try { + result = (await client.get(`/api/devices/pair-request/${r.code}`, { ...quiet, headers: { 'X-Xenia-Pair-Secret': r.secret } })).data + } catch (err) { + error = parseError(err) + } + if (!alive) return + const o = pollOutcome({ result, error, expiresAt: r.expires_at }) + if (o.next === 'paired') { pairedRef.current(o.token); return } + if (o.next === 'new_code') break + setProblem(o.next === 'retry' ? errorMessage({ xenia: error }, t) : null) + } + } + } + run() + return () => { alive = false } + }, [t]) + + return ( +
+
+
+
+ ) +} diff --git a/terminal/src/screens/SignInScreen.jsx b/terminal/src/screens/SignInScreen.jsx new file mode 100644 index 0000000..63bef3c --- /dev/null +++ b/terminal/src/screens/SignInScreen.jsx @@ -0,0 +1,127 @@ +// Signing in on a shared screen (plan step 3.1c, D-8): the people who may use this app +// (GET /api/devices/me/users = holders of ".access"), then the device's login mode: +// tap tapping your name signs you in +// pin your name, then your PIN on the pad +// password your name, then your password +// POST /api/auth/login {client: "terminal", user_id, pin|password} with the device header; +// the session belongs to this screen only. +import { useCallback, useEffect, useState } from 'react' +import { ArrowLeft } from 'lucide-react' +import { useAccess } from '@xenia/access' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, EmptyState, Field, Input, PinPad, Spinner } from '@xenia/ui' +import client from '../api/client' +import { useDevice, useLiveEvent } from '../device/context' + +const quiet = { xenia: { ignoreUnauthorized: true, noOverride: true } } +const USERS_REFRESH_MS = 30_000 // someone given the permission shows up without touching the screen + +export default function SignInScreen() { + const { t } = useTranslation('terminal') + const { venue } = useAccess() + const { me, signIn } = useDevice() + const [users, setUsers] = useState(null) + const [loadError, setLoadError] = useState(null) + const [picked, setPicked] = useState(null) + const [error, setError] = useState('') + const [busy, setBusy] = useState(false) + const mode = me.login_mode + + const loadUsers = useCallback(() => { + client.get('/api/devices/me/users', quiet) + .then(r => { setUsers(r.data); setLoadError(null) }) + .catch(err => setLoadError(errorMessage(err, t))) + }, [t]) + useEffect(() => { loadUsers() }, [loadUsers, me.login_mode]) + useEffect(() => { + const id = setInterval(loadUsers, USERS_REFRESH_MS) + return () => clearInterval(id) + }, [loadUsers]) + useLiveEvent('ready', loadUsers) + + const login = async secret => { + const { data } = await client.post('/api/auth/login', { client: 'terminal', user_id: picked?.id ?? secret.user_id, ...secret }, quiet) + signIn(data.access_token) + } + + const tap = async u => { + setError('') + if (mode !== 'tap') { setPicked(u); return } + setBusy(true) + try { await login({ user_id: u.id }) } catch (err) { setError(errorMessage(err, t)) } finally { setBusy(false) } + } + + const back = () => { setPicked(null); setError('') } + + return ( +
+
+

{picked ? displayName(picked) : t('signIn.title')}

+

{me.name}{venue?.name ? ` · ${venue.name}` : ''}

+
+ + {!picked && ( + loadError ? {t('common:actions.retry')}} /> + : !users ? + : users.length === 0 + ? + : ( +
+ {users.map(u => ( + + ))} +
+ ) + )} + + {picked && mode === 'pin' && ( +
+

{t('signIn.enterPin')}

+ { + try { await login({ pin }); setError('') } catch (err) { setError(errorMessage(err, t)); throw err } + }} /> +
+ )} + + {picked && mode === 'password' && ( + { + try { await login({ password }); setError('') } catch (err) { setError(errorMessage(err, t)) } + }} error={error} /> + )} + + {picked && } + {!picked && error &&

{error}

} +
+ ) +} + +function PasswordForm({ onSubmit, error }) { + const { t } = useTranslation('terminal') + const [password, setPassword] = useState('') + const [busy, setBusy] = useState(false) + const submit = async e => { + e.preventDefault() + if (!password || busy) return + setBusy(true) + await onSubmit(password) + setBusy(false) + setPassword('') + } + return ( +
+ + setPassword(e.target.value)} autoFocus autoComplete="off" /> + + +
+ ) +} + +function displayName(u) { + return u.nickname || u.full_name +} diff --git a/terminal/src/screens/StartScreen.jsx b/terminal/src/screens/StartScreen.jsx deleted file mode 100644 index 851b41c..0000000 --- a/terminal/src/screens/StartScreen.jsx +++ /dev/null @@ -1,20 +0,0 @@ -// What a screen shows before it is set up (plan step 3.1b): the venue's name and that it -// isn't paired yet. Step 3.1c turns it into the pairing screen (code + "Pair it in the -// manager under Devices"). -import { MonitorSmartphone } from 'lucide-react' -import { useAccess } from '@xenia/access' -import { useTranslation } from '@xenia/i18n' - -export default function StartScreen() { - const { t } = useTranslation('terminal') - const { venue } = useAccess() - return ( -
-
-
-
- ) -} diff --git a/terminal/src/screens/Terminal.jsx b/terminal/src/screens/Terminal.jsx new file mode 100644 index 0000000..8301992 --- /dev/null +++ b/terminal/src/screens/Terminal.jsx @@ -0,0 +1,39 @@ +// Which screen a paired device shows (device/flow.js screenFor), plus the "server +// unreachable" banner on top of any of them (local-first: the LAN server is all a screen +// needs; it keeps retrying by itself). +import { WifiOff } from 'lucide-react' +import { useTranslation } from '@xenia/i18n' +import { Button, Spinner } from '@xenia/ui' +import { useDevice } from '../device/context' +import { screenFor } from '../device/flow' +import AppScreen from './AppScreen' +import BlockedScreen from './BlockedScreen' +import PairingScreen from './PairingScreen' +import SignInScreen from './SignInScreen' + +export default function Terminal() { + const device = useDevice() + const screen = screenFor(device) + return ( + <> + {device.offline && } + {screen === 'pairing' && } + {screen === 'loading' &&
} + {(screen === 'blocked' || screen === 'app_off') && } + {screen === 'sign_in' && } + {screen === 'app' && } + + ) +} + +function OfflineBanner({ onRetry }) { + const { t } = useTranslation('terminal') + return ( +
+
+ ) +} diff --git a/terminal/tests/terminal.test.mjs b/terminal/tests/terminal.test.mjs index dff26ad..746da02 100644 --- a/terminal/tests/terminal.test.mjs +++ b/terminal/tests/terminal.test.mjs @@ -1,8 +1,9 @@ -// Pure parts of the terminal shell (plan step 3.1b). +// Pure parts of the terminal shell (plan steps 3.1b, 3.1c). import assert from 'node:assert/strict' import { test } from 'node:test' import { APPS, appLoader } from '../src/apps/registry.js' import { DEVICE_KEY, SESSION_KEY, createDeviceStore } from '../src/device/storage.js' +import { deviceGone, formatCode, idleExpired, liveAction, pollOutcome, refusedAction, screenFor } from '../src/device/flow.js' test('the apps a screen can run: KDS, counter POS, customer display (signage + menu tablet in phase 5)', () => { assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'pos_counter']) @@ -39,3 +40,48 @@ test('device store survives a storage that throws (private mode)', () => { assert.equal(d.deviceToken(), null) assert.equal(createDeviceStore(null).sessionToken(), null) }) + +// ── what a screen shows (3.1c) ────────────────────────────────────────────── + +test('screenFor: pairing → loading/blocked → app off → sign in → app', () => { + const me = (extra = {}) => ({ app_key: 'kds', app_status: 'ok', login_mode: 'pin', ...extra }) + assert.equal(screenFor({ deviceToken: null }), 'pairing') + assert.equal(screenFor({ deviceToken: 'd' }), 'loading') + assert.equal(screenFor({ deviceToken: 'd', meError: { offline: true } }), 'loading') // keeps trying + assert.equal(screenFor({ deviceToken: 'd', meError: { code: 'license.limit_reached' } }), 'blocked') + assert.equal(screenFor({ deviceToken: 'd', me: me({ app_status: 'module.disabled' }), session: 'x' }), 'app_off') + assert.equal(screenFor({ deviceToken: 'd', me: me() }), 'sign_in') + assert.equal(screenFor({ deviceToken: 'd', me: me(), session: 'jwt' }), 'app') + assert.equal(screenFor({ deviceToken: 'd', me: me({ login_mode: 'none' }) }), 'app') // customer display +}) + +test('device gone, live events and refusals', () => { + assert.ok(deviceGone('device.revoked') && deviceGone('device.not_paired') && !deviceGone('auth.session_ended')) + assert.equal(liveAction('device.revoked'), 'forget') + assert.equal(liveAction('session.ended', { reason: 'logout' }), 'sign_out') + assert.equal(liveAction('device.updated', { device_id: 1 }), 'reload') + assert.equal(liveAction('device.updated', { device_id: 1, app_key: 'pos_counter' }), 'reload_and_sign_out') + assert.equal(liveAction('order_updated', {}), null) + assert.equal(refusedAction('device.revoked'), 'forget') + assert.equal(refusedAction('device.required'), 'sign_out') + assert.equal(refusedAction('auth.session_ended'), 'sign_out') + assert.equal(refusedAction('license.limit_reached'), null) +}) + +test('idle sign-out after N minutes; 0 = never', () => { + const t0 = 1_000_000 + assert.equal(idleExpired(t0, 5, t0 + 4 * 60_000), false) + assert.equal(idleExpired(t0, 5, t0 + 5 * 60_000), true) + assert.equal(idleExpired(t0, 0, t0 + 999 * 60_000), false) +}) + +test('pairing: code shown in two groups; poll outcomes', () => { + assert.equal(formatCode('K7M2QX'), 'K7M 2QX') + const now = Date.parse('2026-11-14T12:00:00Z') + const later = '2026-11-14T12:05:00Z' + assert.deepEqual(pollOutcome({ result: { status: 'pending' }, expiresAt: later, now }), { next: 'wait' }) + assert.deepEqual(pollOutcome({ result: { status: 'paired', device_token: 'tok' }, now }), { next: 'paired', token: 'tok' }) + assert.deepEqual(pollOutcome({ result: { status: 'pending' }, expiresAt: '2026-11-14T11:59:00Z', now }), { next: 'new_code' }) + assert.deepEqual(pollOutcome({ error: { code: 'device.pair_code_invalid' }, now }), { next: 'new_code' }) + assert.deepEqual(pollOutcome({ error: { code: 'network.offline', offline: true }, now }), { next: 'retry' }) +}) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index ff45f03..59c9614 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -22,7 +22,7 @@ npm test -w @xenia/api # live client = the waiter's old WebSoc npm test -w @xenia/access # can(): one key, any/all npm test -w manager-dashboard # platform pages' logic: module states, what stops with a module, device status/usage/limits npm run lint -w manager-dashboard # ESLint (waiter rules) on the manager's v2 code; the file list is the `lint` script -npm test -w terminal # terminal shell: which apps a screen can run, the device/session token store +npm test -w terminal # terminal: which apps a screen can run, token store, which screen shows when, live events/refusals, idle sign-out, pairing polls npm run lint -w terminal # ESLint on all of terminal/src (same rules) ``` @@ -44,7 +44,8 @@ Or run one suite at a time: | `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min | | `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min | | `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes; `@xenia/i18n` on `/i18n-sample` with the browser in New York: venue time, live language switch, el/en money and numbers, price input, translated component labels | Edge | ~40 s | -| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited; Apps, Integrations, License, Devices (pairing played through the API, a device setting chosen when pairing and edited, the screen's live connection told of the edit and closed on app change and removal); the approvals log, "Signed in now" + end session, the staff permission editor (give, reset to role, a staff manager can't give what they lack); the notification bell (live, read, read all), sign-in/venue/print settings, log download; the **owner flow** (sign in → turn on KDS → pair a screen → give a chef the kitchen permissions → the chef signs in on that screen) | Edge | ~1 min | +| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited; Apps, Integrations, License, Devices (pairing played through the API, a device setting chosen when pairing and edited, the screen's live connection told of the edit and closed on app change and removal); the approvals log, "Signed in now" + end session, the staff permission editor (give, reset to role, a staff manager can't give what they lack); the notification bell (live, read, read all), sign-in/venue/print settings, log download; the **owner flow** (sign in → turn on KDS → pair the real terminal screen (its Vite on :5188) → give a chef the kitchen permissions → the chef picks their name and types their PIN on that screen) | Edge | ~2 min | +| `node terminal.mjs` | The terminal app for paired screens (backend :8059, terminal Vite :5187): pairing through the screen's code, sign-in by PIN (wrong PIN first), tap and password, sign out, reload stays signed in, mode changed in the manager → the screen follows live, session ended by a manager, app off → "turned off" → on, moved to another app → signed out, a customer display without sign-in, server unreachable banner, removed → pairing again with a notice | Edge | ~1 min | | `node stack.mjs` | The release images + the real `docker-compose.yml` and proxy config on one stack (:19080/:19081/:19082): the terminal on :8082 (app, deep links, assets, `/api`, WebSocket through both nginx hops); :8082 and :8081 refuse a non-LAN address (a second docker network, 100.64.50.0/24) and answer a LAN one; the proxy still starts without a terminal container | Docker | ~3 min (first build longer) | | `node browser.mjs` | Waiter web modes (same-origin, plain HTTP by LAN IP, venue mode), install dialog + drawer entry (Android / iPhone / desktop / no APK) | Docker, Edge | ~2 min | | `node android.mjs basics` | Pairing, wrong address / other venue's QR, login + live WS, back button, restart, two venues, camera permission | Android emulator | ~5 min | diff --git a/tests/e2e/lib/proc.mjs b/tests/e2e/lib/proc.mjs index e3c8bcf..ca49de8 100644 --- a/tests/e2e/lib/proc.mjs +++ b/tests/e2e/lib/proc.mjs @@ -168,3 +168,15 @@ ${terminal ? ` - "${terminal}:8082" }, } } + +/** The terminal app's Vite dev server (plan phase 3) on `port`, proxied to `backendUrl`. */ +export async function startTerminalVite({ port = 5187, backendUrl }) { + const log = openSync(path.join(OUT, `vite-${port}.log`), 'w') + const child = spawn('npx', ['vite', '--port', String(port), '--strictPort'], { + cwd: path.join(CS, 'terminal'), shell: process.platform === 'win32', detached: process.platform !== 'win32', + stdio: ['ignore', log, log], env: { ...process.env, XENIA_BACKEND: backendUrl }, + }) + await waitHttp(`http://localhost:${port}/`) + await fetch(`http://localhost:${port}/src/main.jsx`).catch(() => {}) // warm the first compile + return { url: `http://localhost:${port}`, stop: () => killTree(child) } +} diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 28504ff..1951cd7 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -10,7 +10,7 @@ import { openSync, readFileSync } from 'node:fs' import path from 'node:path' import { chromium } from 'playwright' import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs' -import { killTree, startBackend, waitHttp } from './lib/proc.mjs' +import { killTree, startBackend, startTerminalVite, waitHttp } from './lib/proc.mjs' import { SUPPORT_MASTER, codeFor, siteSecret, supportLogin } from './lib/support.mjs' const PORT = 5186 @@ -21,6 +21,7 @@ const vite = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], { cwd: path.join(CS, 'manager_dashboard'), shell: process.platform === 'win32', detached: process.platform !== 'win32', stdio: ['ignore', log, log], env: { ...process.env, XENIA_BACKEND: backend.url }, }) +const term = await startTerminalVite({ port: 5188, backendUrl: backend.url }) // the owner flow's kitchen screen (3.1c) const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) const r = reporter('manager: login + bootstrap on @xenia/api / @xenia/access') @@ -567,7 +568,7 @@ try { // ── 2.6g: the owner flow (plan step 2.6 "done when") ─────────────────────── // log in → enable KDS → pair a device → give a chef kds.access → the chef logs in on it. - // The device's side is played through the API until the terminal app exists (phase 3). + // The device's side is the real terminal app (3.1c), on its own Vite (:5188). const ownerFlow = 'owner flow:' await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: false } }) // start with KDS off const chef = await api('POST', '/api/waiters/', { token: boss, body: { username: 'e2e_chef', full_name: 'Kostas Chef', pin: '4747', role: 'custom', is_active: true } }) @@ -585,29 +586,28 @@ try { await kdsCard.getByRole('switch').click() await o.waitForFunction(() => document.querySelector('[data-testid="module-kds"]')?.getAttribute('data-state') === 'on', null, { timeout: 8000 }).catch(() => {}) r.check(`${ownerFlow} 2. KDS turned on from its card`, offBefore === 'off' && await kdsCard.getAttribute('data-state') === 'on') - // 3. the screen shows a code; the owner pairs it on the Devices page - const kitchenReq = await deviceRequestsPairing() + // 3. the screen (the real terminal app, 3.1c) shows a code; the owner pairs it on the Devices page + const k = await (await browser.newContext({ viewport: { width: 1280, height: 800 } })).newPage() + k.on('pageerror', e => errors.push(e.message)) + await k.goto(term.url) + await k.getByTestId('pairing-code').waitFor({ timeout: 20_000 }) + const kitchenCode = await k.getByTestId('pairing-code').getAttribute('data-code') await o.goto(`${APP}/devices`) await o.getByTestId('device-usage').waitFor({ timeout: 10_000 }) await o.getByRole('button', { name: 'Pair a device' }).first().click() const odlg = o.getByRole('dialog') - await odlg.getByLabel('Code shown on the device').fill(kitchenReq.code) + await odlg.getByLabel('Code shown on the device').fill(kitchenCode) await odlg.getByLabel('App to run').selectOption('kds') await odlg.getByLabel('Name').fill('Kitchen pass') await odlg.getByLabel('How staff sign in').selectOption('pin') await odlg.getByRole('button', { name: 'Pair a device' }).click() await odlg.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {}) - const kitchenToken = await devicePicksUpToken(kitchenReq) - const kitchenMe = await asDevice(kitchenToken, '/api/devices/me').then(x => x.json()) - r.check(`${ownerFlow} 3. the screen is paired as "Kitchen pass", a kitchen display with PIN sign-in`, - kitchenMe.app_key === 'kds' && kitchenMe.name === 'Kitchen pass' && kitchenMe.login_mode === 'pin', JSON.stringify(kitchenMe)) - const chefOnDevice = () => fetch(`${backend.url}/api/auth/login`, { - method: 'POST', headers: { 'content-type': 'application/json', 'X-Xenia-Device': kitchenToken }, - body: JSON.stringify({ client: 'terminal', user_id: chef.id, pin: '4747' }), - }) - const refused = await chefOnDevice() - r.check(`${ownerFlow} …before the permission, the chef is refused on that screen`, - refused.status === 403 && (await refused.json()).error.code === 'auth.client_not_allowed') + const onSignIn = await k.getByTestId('sign-in-screen').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) + r.check(`${ownerFlow} 3. the kitchen screen shows a code, the owner pairs it as "Kitchen pass" (PIN) and the screen asks who signs in`, + onSignIn && await k.getByTestId('sign-in-screen').getAttribute('data-mode') === 'pin' && (await k.getByTestId('sign-in-screen').textContent()).includes('Kitchen pass')) + await k.getByTestId('user-grid').waitFor({ timeout: 8000 }).catch(() => {}) + r.check(`${ownerFlow} …before the permission, the chef isn't offered on that screen`, + await k.locator(`[data-user="${chef.id}"]`).count() === 0) // 4. give the chef the kitchen permissions in the editor await o.goto(`${APP}/management/staff`) await o.getByTestId(`staff-perms-${chef.id}`).getByRole('button').click() @@ -618,11 +618,15 @@ try { await o.getByTestId('perm-editor').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {}) const chefKeys = (await api('GET', `/api/waiters/${chef.id}/permissions`, { token: boss })).keys r.check(`${ownerFlow} 4. the chef now has kds.access and kds.bump`, chefKeys.includes('kds.access') && chefKeys.includes('kds.bump'), JSON.stringify(chefKeys)) - // 5. the chef signs in on the kitchen screen with their PIN - const chefLogin = await chefOnDevice() - const chefSession = chefLogin.status === 200 ? (await chefLogin.json()).access_token : null - const kdsOrders = chefSession && await fetch(`${backend.url}/api/kds/orders`, { headers: { authorization: `Bearer ${chefSession}`, 'X-Xenia-Device': kitchenToken } }) - r.check(`${ownerFlow} 5. the chef signs in on that screen and sees the kitchen orders`, !!chefSession && kdsOrders.status === 200, String(chefLogin.status)) + // 5. the chef signs in on the kitchen screen with their PIN (the name list refreshes every 30 s; reload = now) + await k.reload() + await k.locator(`[data-user="${chef.id}"]`).click({ timeout: 15_000 }) + await k.keyboard.type('4747') + await k.keyboard.press('Enter') + const inKds = await k.getByTestId('app-kds').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) + r.check(`${ownerFlow} 5. the chef signs in on that screen with their PIN and lands in the kitchen display`, + inKds && (await k.getByTestId('signed-in-user').textContent()).includes('Kostas')) + await k.screenshot({ path: path.join(OUT, 'manager-owner-flow-kitchen.png') }) await o.goto(`${APP}/management/sessions`) const chefRow = o.locator(`[data-user="${chef.id}"][data-client="terminal"]`) await chefRow.waitFor({ timeout: 10_000 }).catch(() => {}) @@ -634,6 +638,7 @@ try { } finally { await browser.close() killTree(vite) + term.stop() await backend.stop() } process.exit(r.done() ? 1 : 0) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index 0c5e949..54a31bf 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -21,6 +21,7 @@ const suites = [ ['browser', 'node', ['browser.mjs'], E2E], ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], + ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], ['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E], ] if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E]) diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs new file mode 100644 index 0000000..3ed4b7c --- /dev/null +++ b/tests/e2e/terminal.mjs @@ -0,0 +1,156 @@ +// Terminal suite (Playwright + Edge, plan step 3.1c): the terminal app for paired screens, +// driven like a person at the screen; the manager's side through the API. +// Backend :8059 (demo DB, licensing off), terminal Vite :5187 proxied to it. +// - pairing through the real screen (code shown → paired from the manager's side) +// - sign-in modes: PIN (wrong PIN first), tap your name, password; sign out +// - app turned off → "turned off" screen → on again, live +// - device moved to another app → its user is signed out +// - a customer display (no sign-in) goes straight into its app +// - server unreachable → banner → back by itself +// - removed from the manager → back to pairing with a notice and a new code +// node terminal.mjs +import path from 'node:path' +import { chromium } from 'playwright' +import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs' +import { startBackend, startTerminalVite } from './lib/proc.mjs' +import { supportLogin } from './lib/support.mjs' + +const backend = await startBackend({ port: 8059, siteId: 'test-site-1' }) +const term = await startTerminalVite({ port: 5187, backendUrl: backend.url }) +const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) +const r = reporter('terminal: pairing, sign-in, app states (paired screens)') +const errors = [] + +async function api(method, url, { token, body } = {}) { + const res = await fetch(backend.url + url, { + method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const text = await res.text() + let data = null + try { data = JSON.parse(text) } catch { data = text } + if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`) + return data +} + +async function screen(page) { + await page.goto(term.url) + page.on('pageerror', e => errors.push(e.message)) + return page +} +const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).waitFor({ timeout }).then(() => true).catch(() => false) + +/** The code the screen shows, then the manager pairs it. */ +async function pairFromManager(page, boss, body) { + await shown(page, 'pairing-code', 15_000) + const code = await page.getByTestId('pairing-code').getAttribute('data-code') + const dev = await api('POST', '/api/devices', { token: boss, body: { code, ...body } }) + return { code, dev } +} + +try { + const boss = await supportLogin(backend.url) + const chef = await api('POST', '/api/waiters/', { token: boss, body: { username: 'term_chef', full_name: 'Maria Chef', pin: '4747', role: 'chef', is_active: true } }) + await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: true } }) + // Staff get no password from the Staff page yet (phase 6): the demo's store manager has one + const mgr = (await api('GET', '/api/waiters/', { token: boss })).find(u => u.username === 'manager') + + // ── pairing ────────────────────────────────────────────────────────────── + const page = await screen(await (await browser.newContext({ viewport: { width: 1280, height: 800 } })).newPage()) + r.check('pairing: a new screen shows a 6-character code', await shown(page, 'pairing-code', 15_000) + && (await page.getByTestId('pairing-code').getAttribute('data-code')).length === 6) + await page.screenshot({ path: path.join(OUT, 'terminal-pairing.png') }) + const { dev: kitchen } = await pairFromManager(page, boss, { app_key: 'kds', name: 'Kitchen', login_mode: 'pin' }) + r.check('pairing: paired from the manager → the screen asks who is signing in', await shown(page, 'sign-in-screen', 15_000) + && await page.getByTestId('sign-in-screen').getAttribute('data-mode') === 'pin') + + // ── PIN ────────────────────────────────────────────────────────────────── + const chefTile = page.locator(`[data-user="${chef.id}"]`) + r.check('sign-in: the chef is listed (holds kds.access)', await chefTile.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await chefTile.click() + await page.keyboard.type('9999') + await page.keyboard.press('Enter') + await sleep(1200) + r.check('sign-in PIN: a wrong PIN stays on the pad with a message', + await page.getByTestId('sign-in-screen').count() === 1 && (await page.getByRole('alert').allTextContents()).join(' ').length > 0) + await page.keyboard.type('4747') + await page.keyboard.press('Enter') + r.check('sign-in PIN: the right PIN opens the kitchen display', await shown(page, 'app-kds') + && (await page.getByTestId('signed-in-user').textContent()).includes('Maria')) + await page.screenshot({ path: path.join(OUT, 'terminal-kds.png') }) + const sessions = await api('GET', '/api/auth/sessions', { token: boss }) + r.check('sign-in PIN: the session is a terminal session on "Kitchen"', + sessions.some(s => s.user_id === chef.id && s.client === 'terminal' && s.device_id === kitchen.id), JSON.stringify(sessions.map(s => [s.user_id, s.client, s.device_id]))) + await page.reload() + r.check('reload keeps the screen paired and the chef signed in', await shown(page, 'app-kds')) + await page.getByRole('button', { name: 'Sign out' }).click() + r.check('sign out → back to the names', await shown(page, 'user-grid')) + + // ── tap, password (the manager changes the mode; the screen follows live) ── + await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { login_mode: 'tap' } }) + await page.waitForFunction(() => document.querySelector('[data-testid="sign-in-screen"]')?.dataset.mode === 'tap', null, { timeout: 8000 }).catch(() => {}) + r.check('mode changed in the manager → the screen switches to "tap your name" at once', + await page.getByTestId('sign-in-screen').getAttribute('data-mode') === 'tap') + await page.locator(`[data-user="${chef.id}"]`).click() + r.check('sign-in tap: tapping the name signs in', await shown(page, 'app-kds')) + await page.getByRole('button', { name: 'Sign out' }).click() + await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { login_mode: 'password' } }) + await page.waitForFunction(() => document.querySelector('[data-testid="sign-in-screen"]')?.dataset.mode === 'password', null, { timeout: 8000 }).catch(() => {}) + await page.locator(`[data-user="${mgr.id}"]`).click() + await page.getByLabel('Password').fill('password') + await page.getByRole('button', { name: 'Sign in' }).click() + r.check('sign-in password: name + password signs in', await shown(page, 'app-kds')) + + // ── ended elsewhere: the manager ends the session ───────────────────────── + const sid = (await api('GET', '/api/auth/sessions', { token: boss })).find(s => s.device_id === kitchen.id).id + await api('POST', `/api/auth/sessions/${sid}/end`, { token: boss }) + r.check('session ended by a manager → the screen is back at sign-in at once', await shown(page, 'sign-in-screen', 8000)) + + // ── app off / on ────────────────────────────────────────────────────────── + await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: false } }) + r.check('KDS turned off → "turned off" screen, live', await shown(page, 'blocked-screen', 8000) + && await page.getByTestId('blocked-screen').getAttribute('data-reason') === 'module.disabled') + await page.screenshot({ path: path.join(OUT, 'terminal-app-off.png') }) + await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: true } }) + r.check('KDS on again → the sign-in comes back by itself', await shown(page, 'sign-in-screen', 8000)) + + // ── moved to another app: whoever is on it is signed out ───────────────── + await page.locator(`[data-user="${mgr.id}"]`).click() + await page.getByLabel('Password').fill('password') + await page.getByRole('button', { name: 'Sign in' }).click() + await shown(page, 'app-kds') + await api('POST', `/api/devices/${kitchen.id}/reassign`, { token: boss, body: { app_key: 'pos_counter' } }) + await page.waitForFunction(() => document.querySelector('[data-testid="sign-in-screen"]'), null, { timeout: 8000 }).catch(() => {}) + r.check('moved to Counter POS → signed out, sign-in for the POS', + await page.getByTestId('sign-in-screen').count() === 1 && (await page.getByTestId('sign-in-screen').textContent()).includes('Kitchen')) + + // ── a customer display: no sign-in ─────────────────────────────────────── + const cd = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 } })).newPage()) + await pairFromManager(cd, boss, { app_key: 'customer_display', name: 'Counter display' }) + r.check('customer display (sign-in "none") goes straight into its app', await shown(cd, 'app-customer_display', 15_000) + && await cd.getByTestId('terminal-bar').count() === 0) + + // ── server unreachable → banner → back ─────────────────────────────────── + await cd.context().setOffline(true) + await cd.evaluate(() => window.__xeniaClient.get('/api/devices/me').catch(() => {})) + r.check('server unreachable → the banner shows', await shown(cd, 'offline-banner', 8000)) + await cd.context().setOffline(false) + // back online: the live connection reconnects by itself (browser `online`); Try again also works + await cd.getByRole('button', { name: 'Try again' }).click({ timeout: 2000 }).catch(() => {}) + await cd.getByTestId('offline-banner').waitFor({ state: 'detached', timeout: 10_000 }).catch(() => {}) + r.check('…and goes away once the server answers', await cd.getByTestId('offline-banner').count() === 0) + + // ── removed → pairing again ────────────────────────────────────────────── + await api('POST', `/api/devices/${kitchen.id}/revoke`, { token: boss }) + r.check('removed in the manager → back to pairing with a notice and a new code', await shown(page, 'removed-notice', 10_000) + && await shown(page, 'pairing-code', 15_000)) + await page.screenshot({ path: path.join(OUT, 'terminal-removed.png') }) + r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | ')) +} catch (e) { + r.check(`terminal: ${e.message.split('\n')[0]}`, false) +} finally { + await browser.close() + term.stop() + await backend.stop() +} +process.exit(r.done() ? 1 : 0)