feat(backend): live connection and per-device settings for paired screens (platform-v2 3.1a)

- WebSocket: credentials may come in the first frame ({cursor, token?, device?}).
  A device token alone connects a paired screen (login-none apps get every event, a
  sign-in app only events addressed to it); a terminal session's JWT needs its own
  device, as over HTTP. Refusals send {type: refused, data: {code}} + close 4001/4003.
- ws_bus: registry of open sockets by user, session and device. Ending a session
  closes its sockets (session.ended); revoke/reassign close the device's sockets
  (device.revoked / device.updated); edits and module on/off send device.updated.
  Events can target devices (device_ids=..., sync_events.target_device_ids, rev 0014).
  Pushes go through each socket's own loop (call_soon_threadsafe).
- Device config: DeviceApp.config = typed ConfigFields, validated on pair/edit/
  reassign (validation.device_config), effective values (defaults filled) in both
  device views and the module catalogue. First field: auto_sign_out_minutes (KDS, POS).
- Manager: DeviceConfigFields renders an app's fields in the pair and edit dialogs.
- @xenia/api createLiveClient: `credentials` and `onRefused` options.
- Tests: tests/test_live.py (11), module texts for config fields, live client,
  devices logic, manager.mjs device setting + live socket checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 16:31:59 +02:00
co-authored by Claude Opus 5.5
parent 034426f870
commit bda5cde92b
31 changed files with 974 additions and 145 deletions
+1 -1
View File
@@ -42,7 +42,7 @@ 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); 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 a screen → give a chef the kitchen permissions → the chef signs in on that screen) | Edge | ~1 min |
| `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 |
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
+28 -1
View File
@@ -43,6 +43,19 @@ async function devicePicksUpToken(req) {
const res = await fetch(`${backend.url}/api/devices/pair-request/${req.code}`, { headers: { 'X-Xenia-Pair-Secret': req.secret } })
return (await res.json()).device_token
}
// A paired screen's live connection (plan 3.1a): the device token goes in the first frame.
function deviceSocket(token) {
const ws = new WebSocket(`${backend.url.replace(/^http/, 'ws')}/api/ws/connect`)
const s = { messages: [], closeCode: null }
s.ready = new Promise(resolve => {
ws.onopen = () => ws.send(JSON.stringify({ cursor: 0, device: token }))
ws.onmessage = e => { const m = JSON.parse(e.data); s.messages.push(m); if (m.type === 'ready') resolve(true) }
ws.onclose = e => { s.closeCode = e.code; resolve(false) }
})
s.closed = () => new Promise(resolve => { const t = setInterval(() => { if (s.closeCode != null) { clearInterval(t); resolve(s.closeCode) } }, 50); setTimeout(() => { clearInterval(t); resolve(s.closeCode) }, 8000) })
s.close = () => ws.close()
return s
}
const asDevice = (token, url) => fetch(`${backend.url}${url}`, { headers: { 'X-Xenia-Device': token } })
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { client: 'manager', username, ...secret } }).then(d => d.access_token)
@@ -171,6 +184,7 @@ try {
await dlg.getByLabel('Code shown on the device').fill(typed)
r.check('devices: the code is normalized as typed (lower case, dash)', await dlg.getByLabel('Code shown on the device').inputValue() === req.code)
await dlg.getByLabel('How staff sign in').selectOption('pin')
await dlg.getByLabel('Sign out after').selectOption('10')
await dlg.getByRole('button', { name: 'Pair a device' }).click()
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
const row = page.locator('[data-testid^="device-"][data-status]').first()
@@ -178,23 +192,34 @@ try {
const deviceToken = await devicePicksUpToken(req)
const me = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
r.check('devices: the device got its token and runs the kitchen display', me.app_key === 'kds' && me.name === 'Kitchen' && me.login_mode === 'pin', JSON.stringify(me))
r.check('devices: the app setting chosen when pairing reaches the device (3.1a)', me.config?.auto_sign_out_minutes === 10, JSON.stringify(me.config))
await page.reload()
await row.waitFor({ timeout: 10_000 })
r.check('devices: after it connected → "Online", sign-in PIN', await row.getAttribute('data-status') === 'online' && (await row.textContent()).includes('PIN'))
r.check('devices: usage shows kitchen screens in use', (await page.getByTestId('device-usage').textContent()).includes('Kitchen screens: 1'))
const sock = deviceSocket(deviceToken)
r.check('devices: the screen opens a live connection with its device token alone (3.1a)', await sock.ready)
await row.getByRole('button', { name: 'Edit' }).click()
r.check('devices: the edit dialog shows the device setting', await dlg.getByLabel('Sign out after').inputValue() === '10')
await dlg.getByLabel('Name').fill('Kitchen 1')
await dlg.getByLabel('Sign out after').selectOption('5')
await dlg.getByRole('button', { name: 'Save' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {})
r.check('devices: renamed', (await row.textContent()).includes('Kitchen 1') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).name === 'Kitchen 1')
const me2 = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
r.check('devices: renamed, setting changed', (await row.textContent()).includes('Kitchen 1') && me2.name === 'Kitchen 1' && me2.config?.auto_sign_out_minutes === 5, JSON.stringify(me2))
await sleep(300)
r.check('devices: the screen is told at once (device.updated)', sock.messages.some(m => m.type === 'device.updated'), JSON.stringify(sock.messages))
await row.getByRole('button', { name: 'Change app' }).click()
await dlg.getByLabel('App to run').selectOption('pos_counter')
await dlg.getByRole('button', { name: 'Save' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Counter POS'), null, { timeout: 8000 }).catch(() => {})
r.check('devices: app changed to Counter POS (the device follows)', (await row.textContent()).includes('Counter POS') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).app_key === 'pos_counter')
r.check('devices: changing the app closes the screen connection (4003)', await sock.closed() === 4003)
await page.screenshot({ path: path.join(OUT, 'manager-devices.png'), fullPage: true })
const sock2 = deviceSocket(deviceToken)
await sock2.ready
await row.getByRole('button', { name: 'Remove' }).click()
await dlg.getByRole('button', { name: 'Remove' }).click()
@@ -202,6 +227,8 @@ try {
const after = await asDevice(deviceToken, '/api/devices/me')
r.check('devices: removed → gone from the list, the device is refused (device.revoked)',
await page.getByText('No devices yet').count() === 1 && after.status === 401 && (await after.json()).error.code === 'device.revoked')
r.check('devices: removing it sends device.revoked and closes its connection',
await sock2.closed() === 4003 && sock2.messages.some(m => m.type === 'device.revoked'), JSON.stringify(sock2.messages))
await page.getByLabel('Show removed devices').check()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status="removed"]'), null, { timeout: 8000 }).catch(() => {})
r.check('devices: "show removed" lists it as removed', await page.locator('[data-status="removed"]').count() === 1)