feat(api): @xenia/api + @xenia/access; the manager logs in and loads bootstrap through them

Platform-v2 step 2.5 (APPS_PLATFORM D-7, D-10, §9):
- @xenia/api: createApiClient (app passes its axios; session/device headers,
  err.xenia codes, 401/offline hooks, manager-override retry: ask PIN, grant,
  retry once with X-Xenia-Override); errorMessage; createLiveClient = the
  waiter's WebSocket logic (cursor replay, backoff, online) moved unchanged
- @xenia/access: AccessProvider (bootstrap per session token, language +
  venue formats, translated ui labels, approval dialog), useAccess/useCan/
  useModule, Can, RequireModule
- i18n: errors namespace for every backend code (en/el, test vs core/errors.py),
  override/access texts
- manager: client from createApiClient, AccessProvider in a layout route,
  /kds behind RequireModule, usePermissions from bootstrap keys; login and
  unlock no longer treat a wrong password/PIN as "session ended" (a wrong
  lock-screen PIN used to log the manager out)
- waiter: useWebSocket is a thin wrapper over createLiveClient
- tests: api/access unit tests; new e2e suite tests/e2e/manager.mjs; CS-18

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 20:38:31 +02:00
co-authored by Claude Opus 5.5
parent dbb8d5f0f4
commit 78c8824356
35 changed files with 1419 additions and 196 deletions
+1
View File
@@ -19,6 +19,7 @@
"@capacitor/core": "8.5.2",
"@capgo/capacitor-updater": "8.51.25",
"@tanstack/react-query": "^5.100.11",
"@xenia/api": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.15.1",
"dexie": "^4.4.2",
+34 -122
View File
@@ -1,40 +1,36 @@
/**
* Persistent WebSocket hook — replaces useSSE.
* Persistent WebSocket hook — the waiter's live events.
*
* Protocol:
* 1. Connect to ws[s]://host/api/ws/connect?token=<jwt>
* 2. Send { cursor: <last_seq> } immediately (0 = first connect)
* 3. Receive replayed missed events, then { type: "ready" }
* 4. Live events: { seq, type, data }
* 5. Keepalive: server sends { type: "ping" } every 25s
*
* The hook stores `lastSeq` in IndexedDB so it survives page reloads.
* On every clean reconnect, missed events are replayed automatically.
* The connection logic (cursor replay, reconnect backoff 2 s → ×1.5 → 30 s, reconnect when
* the network comes back) is the shared client in @xenia/api (createLiveClient, plan step
* 2.5), lifted from this file without changing behaviour. This hook keeps the waiter's
* parts: the URL from the active venue (CS-8) and the cursor in IndexedDB, so it survives
* page reloads and missed events are replayed on every reconnect.
*/
import { useCallback, useEffect, useRef } from 'react'
import { createLiveClient } from '@xenia/api'
import db from '../db/posdb'
import { wsUrl } from '../config/server'
const INITIAL_RECONNECT_DELAY = 2_000
const MAX_RECONNECT_DELAY = 30_000
const CURSOR_KEY = 'ws_last_seq'
// ── Cursor persistence (IDB) ──────────────────────────────────────────────────
async function loadCursor() {
try {
const row = await db.kv?.get(CURSOR_KEY)
return row?.value ?? 0
} catch {
return 0
}
}
async function saveCursor(seq) {
try {
await db.kv?.put({ key: CURSOR_KEY, value: seq })
} catch {}
const idbCursor = {
async load() {
try {
const row = await db.kv?.get(CURSOR_KEY)
return row?.value ?? 0
} catch {
return 0
}
},
async save(seq) {
try {
await db.kv?.put({ key: CURSOR_KEY, value: seq })
} catch { /* storage unavailable: replay starts from 0 next time */ }
},
}
// ── Hook ──────────────────────────────────────────────────────────────────────
@@ -47,112 +43,28 @@ export function useWebSocket({ token, onEvent, onConnect, onDisconnect, enabled
useEffect(() => { onConnectRef.current = onConnect }, [onConnect])
useEffect(() => { onDisconnectRef.current = onDisconnect }, [onDisconnect])
const wsRef = useRef(null)
const reconnectTimer = useRef(null)
const reconnectDelay = useRef(INITIAL_RECONNECT_DELAY)
const unmounted = useRef(false)
const connectRef = useRef(null)
const lastSeq = useRef(0)
const liveRef = useRef(null)
useEffect(() => {
if (!token || !enabled) return
unmounted.current = false
// Load persisted cursor before first connect
loadCursor().then(seq => {
lastSeq.current = seq
if (!unmounted.current) connectRef.current?.()
})
async function connect() {
if (unmounted.current) return
if (wsRef.current) {
wsRef.current.onclose = null // prevent double-reconnect
wsRef.current.close()
wsRef.current = null
}
const live = createLiveClient({
// Same host as the page (web) or the active venue's server (native)
const url = wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`)
const ws = new WebSocket(url)
wsRef.current = ws
ws.onopen = () => {
reconnectDelay.current = INITIAL_RECONNECT_DELAY
// Send cursor so server can replay missed events
ws.send(JSON.stringify({ cursor: lastSeq.current }))
}
ws.onmessage = (e) => {
let msg
try { msg = JSON.parse(e.data) } catch { return }
if (msg.type === 'ping') return // keepalive — no response needed
if (msg.type === 'ready') {
// Replay complete — we're now on the live stream
onConnectRef.current?.()
return
}
// Live or replayed event
if (msg.seq && msg.seq > lastSeq.current) {
lastSeq.current = msg.seq
saveCursor(msg.seq)
}
if (msg.type && msg.data !== undefined) {
onEventRef.current?.(msg.type, msg.data)
}
}
ws.onerror = () => {
// onerror always fires before onclose — let onclose handle reconnect
}
ws.onclose = () => {
wsRef.current = null
onDisconnectRef.current?.()
if (unmounted.current) return
// Schedule next attempt with current delay, then increase for the one after
reconnectTimer.current = setTimeout(() => {
reconnectDelay.current = Math.min(
reconnectDelay.current * 1.5,
MAX_RECONNECT_DELAY,
)
connect()
}, reconnectDelay.current)
}
}
connectRef.current = connect
// When the browser detects network restoration, immediately reset backoff and reconnect.
// This fires as soon as the OS reports connectivity — no need to wait for the
// backed-off timer or for the user to switch tabs.
function onNetworkOnline() {
clearTimeout(reconnectTimer.current)
reconnectDelay.current = INITIAL_RECONNECT_DELAY
connect()
}
window.addEventListener('online', onNetworkOnline)
url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
cursor: idbCursor,
onEvent: (type, data) => onEventRef.current?.(type, data),
onReady: () => onConnectRef.current?.(),
onDisconnect: () => onDisconnectRef.current?.(),
})
liveRef.current = live
live.start()
return () => {
unmounted.current = true
clearTimeout(reconnectTimer.current)
window.removeEventListener('online', onNetworkOnline)
if (wsRef.current) {
wsRef.current.onclose = null
wsRef.current.close()
wsRef.current = null
}
live.stop()
if (liveRef.current === live) liveRef.current = null
}
}, [token, enabled])
const reconnect = useCallback(() => {
clearTimeout(reconnectTimer.current)
reconnectDelay.current = INITIAL_RECONNECT_DELAY
connectRef.current?.()
liveRef.current?.reconnect()
}, [])
return { reconnect }