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 <app>.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 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 17:29:18 +02:00
co-authored by Claude Opus 5.5
parent 7ff3c3b48e
commit c24cb72640
22 changed files with 928 additions and 83 deletions
+3 -2
View File
@@ -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 |
+12
View File
@@ -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) }
}
+26 -21
View File
@@ -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)
+1
View File
@@ -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])
+156
View File
@@ -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)