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
+12 -5
View File
@@ -3,10 +3,12 @@
// hook is now a thin wrapper around this. No React.
//
// Protocol (local_backend/routers/ws.py):
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt>
// 2. send { cursor: <last seq> } at once (0 = first connect / no history)
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt> (or no query, see `credentials`)
// 2. send { cursor: <last seq>, ...credentials() } at once (0 = first connect / no history)
// 3. the server replays missed events, then sends { type: "ready" }
// 4. live events: { seq, type, data }
// — or { type: "refused", data: { code } } and closes (4001 sign in again, 4003 device)
// 4. live events: { seq, type, data }; control events without seq: `device.updated`, and
// before the server closes: `session.ended`, `device.revoked` (plan step 3.1a)
// 5. keepalive: { type: "ping" } every 25 s (no answer needed)
// On close: reconnect after 2 s, then ×1.5 each time up to 30 s; a successful open resets
// it. The browser's `online` event reconnects at once. The cursor survives reloads through
@@ -16,6 +18,9 @@
// url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
// cursor: { load: async () => seq, save: seq => … },
// onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …,
// // terminal (paired device): credentials go in the first frame, never in the URL
// credentials: () => ({ device: deviceToken, token: sessionToken }),
// onRefused: code => …, // e.g. 'device.revoked', 'auth.session_ended'; it keeps retrying
// })
// live.start(); …; live.reconnect(); …; live.stop()
@@ -31,7 +36,7 @@ export function wsUrlFor(path, baseURL = '') {
}
export function createLiveClient({
url, cursor, onEvent, onReady, onDisconnect,
url, cursor, onEvent, onReady, onDisconnect, credentials, onRefused,
WebSocketImpl = globalThis.WebSocket,
windowTarget = typeof window !== 'undefined' ? window : null,
timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id) },
@@ -54,7 +59,8 @@ export function createLiveClient({
socket.onopen = () => {
reconnectDelay = INITIAL_RECONNECT_DELAY
socket.send(JSON.stringify({ cursor: lastSeq })) // the server replays what we missed
const extra = Object.fromEntries(Object.entries(credentials?.() || {}).filter(([, v]) => v != null && v !== ''))
socket.send(JSON.stringify({ cursor: lastSeq, ...extra })) // the server replays what we missed
}
socket.onmessage = e => {
@@ -62,6 +68,7 @@ export function createLiveClient({
try { msg = JSON.parse(e.data) } catch { return }
if (msg.type === 'ping') return
if (msg.type === 'ready') { onReady?.(); return }
if (msg.type === 'refused') { onRefused?.(msg.data?.code); return }
if (msg.seq && msg.seq > lastSeq) {
lastSeq = msg.seq
cursor?.save?.(msg.seq)
+23
View File
@@ -157,3 +157,26 @@ test('wsUrlFor', () => {
assert.equal(wsUrlFor('/api/ws/connect?token=a', 'https://10.0.2.2:18443'), 'wss://10.0.2.2:18443/api/ws/connect?token=a')
assert.equal(wsUrlFor('/api/ws/connect', 'http://192.168.1.5'), 'ws://192.168.1.5/api/ws/connect')
})
test('credentials go in the first frame (empty ones left out); refusals reach onRefused', async () => {
FakeWS.all = []
const refused = []
const events = []
const live = createLiveClient({
url: 'ws://venue/api/ws/connect',
credentials: () => ({ device: 'dev-token', token: null }),
onEvent: (type, data) => events.push([type, data]),
onRefused: code => refused.push(code),
WebSocketImpl: FakeWS, windowTarget: new FakeWindow(), timers: fakeTimers(),
})
await live.start()
const ws = FakeWS.all.at(-1)
assert.equal(ws.url, 'ws://venue/api/ws/connect')
ws.open()
assert.deepEqual(ws.sent, [{ cursor: 0, device: 'dev-token' }])
ws.msg({ type: 'refused', data: { code: 'device.revoked' } })
ws.msg({ type: 'device.updated', data: { device_id: 3 } })
assert.deepEqual(refused, ['device.revoked'])
assert.deepEqual(events, [['device.updated', { device_id: 3 }]])
live.stop()
})
+2 -1
View File
@@ -54,7 +54,8 @@
"invalid": "Κάποια πεδία δεν είναι σωστά.",
"unknown_language": "Μη υποστηριζόμενη γλώσσα: {{language}}.",
"unknown_timezone": "Άγνωστη ζώνη ώρας: {{timezone}}.",
"setting_value": "Η ρύθμιση {{key}} δεν μπορεί να πάρει την τιμή «{{value}}»."
"setting_value": "Η ρύθμιση {{key}} δεν μπορεί να πάρει την τιμή «{{value}}».",
"device_config": "Αυτή η ρύθμιση συσκευής δεν είναι έγκυρη: {{key}}."
},
"internal": {
"error": "Κάτι πήγε στραβά στον διακομιστή (αίτημα {{request_id}})."
+1
View File
@@ -172,6 +172,7 @@
"signIn": "Πώς συνδέεται το προσωπικό",
"link": "Συνδεδεμένη συσκευή",
"noLink": "Καμία",
"none": "Κανένα",
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές."
+28
View File
@@ -125,6 +125,20 @@
"permissions": {
"access": "Χρήση της οθόνης κουζίνας",
"bump": "Σήμανση πιάτων ως έτοιμων"
},
"config": {
"auto_sign_out_minutes": {
"label": "Αποσύνδεση μετά από",
"hint": "Επιστροφή στην οθόνη σύνδεσης όταν κανείς δεν έχει χρησιμοποιήσει την οθόνη για τόσο χρόνο.",
"choices": {
"0": "Ποτέ",
"2": "2 λεπτά",
"5": "5 λεπτά",
"10": "10 λεπτά",
"30": "30 λεπτά",
"60": "1 ώρα"
}
}
}
},
"menu_tablet": {
@@ -169,6 +183,20 @@
},
"permissions": {
"access": "Χρήση του ταμείου πάγκου"
},
"config": {
"auto_sign_out_minutes": {
"label": "Αποσύνδεση μετά από",
"hint": "Επιστροφή στην οθόνη σύνδεσης όταν κανείς δεν έχει χρησιμοποιήσει την οθόνη για τόσο χρόνο.",
"choices": {
"0": "Ποτέ",
"2": "2 λεπτά",
"5": "5 λεπτά",
"10": "10 λεπτά",
"30": "30 λεπτά",
"60": "1 ώρα"
}
}
}
},
"pricing": {
+2 -1
View File
@@ -54,7 +54,8 @@
"invalid": "Some fields are invalid.",
"unknown_language": "Unsupported language: {{language}}.",
"unknown_timezone": "Unknown time zone: {{timezone}}.",
"setting_value": "{{key}} can't be set to \"{{value}}\"."
"setting_value": "{{key}} can't be set to \"{{value}}\".",
"device_config": "This device setting is not valid: {{key}}."
},
"internal": {
"error": "Something went wrong on the server (request {{request_id}})."
+1
View File
@@ -172,6 +172,7 @@
"signIn": "How staff sign in",
"link": "Linked device",
"noLink": "None",
"none": "None",
"linkHint": "For example a customer display that shows a counter POS's order.",
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
"noApps": "No device app is turned on. Turn one on in Apps first."
+28
View File
@@ -125,6 +125,20 @@
"permissions": {
"access": "Use the kitchen display",
"bump": "Mark items ready"
},
"config": {
"auto_sign_out_minutes": {
"label": "Sign out after",
"hint": "Back to the sign-in screen when nobody has used the screen for this long.",
"choices": {
"0": "Never",
"2": "2 minutes",
"5": "5 minutes",
"10": "10 minutes",
"30": "30 minutes",
"60": "1 hour"
}
}
}
},
"menu_tablet": {
@@ -169,6 +183,20 @@
},
"permissions": {
"access": "Use the counter POS"
},
"config": {
"auto_sign_out_minutes": {
"label": "Sign out after",
"hint": "Back to the sign-in screen when nobody has used the screen for this long.",
"choices": {
"0": "Never",
"2": "2 minutes",
"5": "5 minutes",
"10": "10 minutes",
"30": "30 minutes",
"60": "1 hour"
}
}
}
},
"pricing": {