refactor(connect): one live connection, no token in any address (SSE removed)

Plan step 4.0. Owner (2026-11-17): no phone in use needs to keep working, so no
compatibility path.
- Removed the SSE channel: routers/sse.py (/api/sse/stream, which still accepted a JWT whose
  session had ended — a signed-out phone could keep listening), services/sse_bus.py (every
  backend module now calls services/ws_bus.broadcast_sync directly), waiter useSSE.js.
- Credentials only in the first frame: the waiter's useWebSocket and the manager's
  LiveProvider send {token} there like the terminal; routers/ws.py no longer reads ?token=
  (a token in a URL ends up in proxy and server logs).
- Waiter: SSEContext → LiveContext (LiveProvider, useLiveContext, liveAlive, the
  'live-event' / 'live-reconnected' window events), dead SSE compat code removed.
- Tests: a token in the address is refused, /api/sse/stream is 404; e2e browser (3 delivery
  modes) and manager assert no token in the live connection's address. Android taps now
  wait for their element (the fixed sleeps made the suite flaky, KI-009).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 10:49:21 +02:00
co-authored by Claude Opus 5.5
parent d0c6a10e47
commit f85894a72e
43 changed files with 112 additions and 350 deletions
+2 -2
View File
@@ -53,7 +53,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below | | `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below |
| `waiter_pwa/src/native/pairing.js`, `src/pages/VenuesPage.jsx` | Pairing with a venue (QR / typed address) and the venue switcher | | `waiter_pwa/src/native/pairing.js`, `src/pages/VenuesPage.jsx` | Pairing with a venue (QR / typed address) and the venue switcher |
| `waiter_pwa/src/api/client.js` | axios instance: auth header, 401 → logout, network error → offline | | `waiter_pwa/src/api/client.js` | axios instance: auth header, 401 → logout, network error → offline |
| `waiter_pwa/src/context/SSEContext.jsx`, `src/hooks/useWebSocket.js` | Real-time lifecycle, event → store/cache updates, visibility refresh; the socket itself is `createLiveClient` from `@xenia/api` | | `waiter_pwa/src/context/LiveContext.jsx`, `src/hooks/useWebSocket.js` | Real-time lifecycle, event → store/cache updates, visibility refresh; the socket itself is `createLiveClient` from `@xenia/api` |
| `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders | | `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders |
| `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand | | `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand |
| `install.sh` | Site installer. **Writes its own copy of the proxy config.** | | `install.sh` | Site installer. **Writes its own copy of the proxy config.** |
@@ -77,7 +77,7 @@ A v1 database (tables, no `alembic_version`) is refused at startup; v1 data come
*(On `main`, the v1 rule still applies: `_run_migrations()` ALTER list, additive only.)* *(On `main`, the v1 rule still applies: `_run_migrations()` ALTER list, additive only.)*
**CS-2. New real-time events need both ends.** **CS-2. New real-time events need both ends.**
If the backend emits a new event type, handle it in `waiter_pwa/src/context/SSEContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored. If the backend emits a new event type, handle it in `waiter_pwa/src/context/LiveContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored.
Events carry IDs; clients re-fetch the full object (`/api/orders/{id}`) instead of trusting partial payloads. Events carry IDs; clients re-fetch the full object (`/api/orders/{id}`) instead of trusting partial payloads.
Control frames from `routers/ws.py` (3.1a) are not stored and have no seq: `device.updated` (a paired screen re-reads `GET /api/devices/me`), and just before the server closes a socket `session.ended` (4001) or `device.revoked` / `device.updated` (4003). The waiter and the manager ignore them (their next request gets the 401 that signs them out); the terminal acts on them. Events for one device: `ws_bus.broadcast_sync(type, data, device_ids=[…])`. Control frames from `routers/ws.py` (3.1a) are not stored and have no seq: `device.updated` (a paired screen re-reads `GET /api/devices/me`), and just before the server closes a socket `session.ended` (4001) or `device.revoked` / `device.updated` (4003). The waiter and the manager ignore them (their next request gets the 401 that signs them out); the terminal acts on them. Events for one device: `ws_bus.broadcast_sync(type, data, device_ids=[…])`.
+1 -1
View File
@@ -102,7 +102,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
db.commit() db.commit()
logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience) logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience)
try: try:
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience)) broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience))
except Exception: except Exception:
logger.exception("notification.event_failed id=%s", row.id) logger.exception("notification.event_failed id=%s", row.id)
-2
View File
@@ -43,12 +43,10 @@ def _init_chat():
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
import asyncio import asyncio
from services.sse_bus import init_loop as sse_init_loop
from services.ws_bus import init_loop as ws_init_loop, prune_old_events from services.ws_bus import init_loop as ws_init_loop, prune_old_events
from services.reservation_tasks import start_reservation_tasks from services.reservation_tasks import start_reservation_tasks
from services.printer_service import start_print_retry_thread from services.printer_service import start_print_retry_thread
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
sse_init_loop(loop)
ws_init_loop(loop) ws_init_loop(loop)
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases. # Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
from core.schema import upgrade_to_head from core.schema import upgrade_to_head
-1
View File
@@ -41,7 +41,6 @@ MODULE = Module(
Mount('routers.waiters', '/api/waiters'), Mount('routers.waiters', '/api/waiters'),
Mount('routers.system', '/api/system'), Mount('routers.system', '/api/system'),
Mount('routers.settings', '/api/settings'), Mount('routers.settings', '/api/settings'),
Mount('routers.sse', '/api/sse'),
Mount('routers.ws', '/api/ws'), Mount('routers.ws', '/api/ws'),
Mount('routers.recovery', '/api/recovery'), Mount('routers.recovery', '/api/recovery'),
Mount('routers.devices', '/api/devices'), Mount('routers.devices', '/api/devices'),
+1 -1
View File
@@ -20,7 +20,7 @@ from schemas.chat import (
MessageOut, MessageOut,
ParticipantOut, ParticipantOut,
) )
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
+1 -1
View File
@@ -38,7 +38,7 @@ from core.timeutil import utcnow
from database import get_db from database import get_db
from models.order import Order, OrderItem from models.order import Order, OrderItem
from schemas.order import OrderItemOut, OrderOut from schemas.order import OrderItemOut, OrderOut
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
router = APIRouter() router = APIRouter()
+1 -1
View File
@@ -236,7 +236,7 @@ def _apply_rule(rule, body: RuleBody):
def _changed(): def _changed():
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
broadcast_sync("fees_changed", {}) broadcast_sync("fees_changed", {})
+1 -1
View File
@@ -7,7 +7,7 @@ from models.flag import TableFlagDef, TableFlagAssignment
from schemas.flag import FlagDefCreate, FlagDefUpdate, FlagDefOut, FlagAssignmentOut, SetTableFlagsRequest from schemas.flag import FlagDefCreate, FlagDefUpdate, FlagDefOut, FlagAssignmentOut, SetTableFlagsRequest
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from models.user import User from models.user import User
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
+1 -1
View File
@@ -58,7 +58,7 @@ from core.access.context import current_device
from core.modules import device_config from core.modules import device_config
from core.access.deps import require from core.access.deps import require
from routers.deps import get_current_user, require_kds from routers.deps import get_current_user, require_kds
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
router = APIRouter(dependencies=[Depends(require_kds)]) router = APIRouter(dependencies=[Depends(require_kds)])
+1 -1
View File
@@ -11,7 +11,7 @@ from schemas.message import (
QuickTemplateCreate, QuickTemplateUpdate, QuickTemplateOut, QuickTemplateCreate, QuickTemplateUpdate, QuickTemplateOut,
) )
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
+1 -1
View File
@@ -55,7 +55,7 @@ class RevertPaymentRequest(BaseModel):
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
from models.settings import PosSettings from models.settings import PosSettings
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
+1 -1
View File
@@ -624,7 +624,7 @@ def pos_refund(order_id: int, body: RefundBody, request: Request, db: Session =
→ {refund_id, order_id, amount, method, drawer, fiscal}""" → {refund_id, order_id, amount, method, drawer, fiscal}"""
from models.order import Order, OrderItem from models.order import Order, OrderItem
from services import fiscal, refunds from services import fiscal, refunds
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
order = db.get(Order, order_id) order = db.get(Order, order_id)
if order is None: if order is None:
raise XeniaError("order.not_found", order_id=order_id) raise XeniaError("order.not_found", order_id=order_id)
+1 -1
View File
@@ -606,7 +606,7 @@ def accept_deal_offer(
)) ))
db.commit() db.commit()
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
broadcast_sync() broadcast_sync()
return { return {
+1 -1
View File
@@ -21,7 +21,7 @@ from schemas.product import (
CategoryReparentRequest, ModifierGroupCreate, ModifierGroupOut, CategoryReparentRequest, ModifierGroupCreate, ModifierGroupOut,
) )
from routers.deps import get_current_user, require_menu_manager from routers.deps import get_current_user, require_menu_manager
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
-61
View File
@@ -1,61 +0,0 @@
"""
SSE stream endpoint — one long-lived GET per connected phone.
Authentication: token passed as query param ?token=<jwt>
(EventSource API in browsers cannot set custom headers, so query param is the standard pattern.)
The client receives a stream of JSON lines:
data: {"type": "...", "data": {...}}\n\n
A keepalive comment (": ping") is sent every 25 seconds to prevent proxy timeouts.
"""
from core.access.deps import public
import asyncio
from fastapi import Depends, APIRouter, Query
from fastapi.responses import StreamingResponse
from routers.deps import decode_token
from services.sse_bus import subscribe, unsubscribe
router = APIRouter()
KEEPALIVE_INTERVAL = 25 # seconds
async def _event_stream(user_id: int):
q = await subscribe(user_id)
try:
while True:
try:
payload = await asyncio.wait_for(q.get(), timeout=KEEPALIVE_INTERVAL)
yield f"data: {payload}\n\n"
except asyncio.TimeoutError:
# keepalive — prevents nginx/proxies from closing idle connections
yield ": ping\n\n"
except asyncio.CancelledError:
pass
finally:
await unsubscribe(user_id, q)
@router.get("/stream", dependencies=[Depends(public())])
async def sse_stream(token: str = Query(...)):
"""
Open an SSE stream for the authenticated user.
The phone connects once on login and stays connected.
On reconnect (after network drop) it does a full GET first, then reconnects here.
"""
# decode_token raises HTTPException on invalid/expired — no manual check needed
payload = decode_token(token)
user_id: int = int(payload["sub"])
return StreamingResponse(
_event_stream(user_id),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no", # disable nginx buffering
"Connection": "keep-alive",
},
)
+1 -1
View File
@@ -16,7 +16,7 @@ from schemas.table import (
TableBatchCreate, MAX_TABLE_NAME_LENGTH, TableBatchCreate, MAX_TABLE_NAME_LENGTH,
) )
from routers.deps import get_current_user, require_tables_manager from routers.deps import get_current_user, require_tables_manager
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
# Tables with a pending reservation due within this many hours get the RESERVED badge # Tables with a pending reservation due within this many hours get the RESERVED badge
RESERVATION_LOOKAHEAD_HOURS = 4 RESERVATION_LOOKAHEAD_HOURS = 4
+10 -10
View File
@@ -2,12 +2,12 @@
WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal). WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal).
Protocol: Protocol:
1. Client connects: ws://host/api/ws/connect (terminal: no query) 1. Client connects: ws://host/api/ws/connect (no query: a token in a URL ends up in
or: ws://host/api/ws/connect?token=<jwt> (waiter, manager) proxy and server logs; the `?token=` form was removed in phase 4.0)
2. Client immediately sends its first frame: 2. Client immediately sends its first frame:
{ "cursor": <last_seq_id>, "token"?: <jwt>, "device"?: <device token> } { "cursor": <last_seq_id>, "token"?: <jwt>, "device"?: <device token> }
(cursor 0 = first connect / no history). Credentials in the frame stay out of URLs (cursor 0 = first connect / no history). Every client (waiter, manager, terminal)
and proxy logs; the terminal always sends them there. sends its credentials here.
3. Server checks who it is (below). Refused → { "type": "refused", "data": {code} } 3. Server checks who it is (below). Refused → { "type": "refused", "data": {code} }
and close code 4001 (sign in again) or 4003 (device problem). and close code 4001 (sign in again) or 4003 (device problem).
4. Server replays missed events the socket may see (seq > cursor) as individual frames 4. Server replays missed events the socket may see (seq > cursor) as individual frames
@@ -38,7 +38,7 @@ import asyncio
import json import json
import logging import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect
from starlette.websockets import WebSocketState from starlette.websockets import WebSocketState
from core.errors import XeniaError from core.errors import XeniaError
@@ -102,21 +102,21 @@ def authenticate(db, token: str | None, device_token: str | None) -> dict:
@router.websocket("/connect", dependencies=[Depends(public())]) @router.websocket("/connect", dependencies=[Depends(public())])
async def ws_endpoint(websocket: WebSocket, token: str | None = Query(None)): async def ws_endpoint(websocket: WebSocket):
await websocket.accept() await websocket.accept()
# ── First frame: cursor (+ credentials) ─────────────────────────────────── # ── First frame: cursor + credentials ─────────────────────────────────────
cursor, device_token = 0, None cursor, token, device_token = 0, None, None
try: try:
msg = json.loads(await asyncio.wait_for(websocket.receive_text(), timeout=FIRST_FRAME_TIMEOUT)) msg = json.loads(await asyncio.wait_for(websocket.receive_text(), timeout=FIRST_FRAME_TIMEOUT))
if isinstance(msg, dict): if isinstance(msg, dict):
cursor = int(msg.get("cursor") or 0) cursor = int(msg.get("cursor") or 0)
token = msg.get("token") or token token = msg.get("token") or None
device_token = msg.get("device") or None device_token = msg.get("device") or None
except WebSocketDisconnect: except WebSocketDisconnect:
return return
except Exception: except Exception:
pass # no (valid) first frame: fresh connect, credentials from the query only pass # no (valid) first frame: no credentials → refused below
# ── Auth ────────────────────────────────────────────────────────────────── # ── Auth ──────────────────────────────────────────────────────────────────
try: try:
+1 -1
View File
@@ -540,7 +540,7 @@ async def _pull_pending_orders():
return return
from database import SessionLocal from database import SessionLocal
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
db = SessionLocal() db = SessionLocal()
booked, at_table = [], [] booked, at_table = [], []
@@ -161,7 +161,7 @@ def fire(db, r) -> list | None:
def send_to_kitchen(db, order_id: int, item_ids: list) -> None: def send_to_kitchen(db, order_id: int, item_ids: list) -> None:
"""Kitchen tickets and the KDS for a fired booking's order (after commit).""" """Kitchen tickets and the KDS for a fired booking's order (after commit)."""
from services.printer_service import route_and_print_sync from services.printer_service import route_and_print_sync
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
if item_ids: if item_ids:
try: try:
route_and_print_sync(order_id, item_ids, db) route_and_print_sync(order_id, item_ids, db)
+1 -1
View File
@@ -80,7 +80,7 @@ def after(db, placed: dict, opener_id: int) -> None:
from core.i18n import t, venue_language from core.i18n import t, venue_language
from routers.kds import _save_and_broadcast_message from routers.kds import _save_and_broadcast_message
from services.printer_service import route_and_print_sync from services.printer_service import route_and_print_sync
from services.sse_bus import broadcast_sync from services.ws_bus import broadcast_sync
from services.table_qr import label from services.table_qr import label
order, table, ids = placed["order"], placed["table"], placed["item_ids"] order, table, ids = placed["order"], placed["table"], placed["item_ids"]
try: try:
-90
View File
@@ -1,90 +0,0 @@
"""
SSE Event Bus — in-memory broadcaster for Server-Sent Events.
All routers import `broadcast_sync()` to push events from sync routes.
The SSE endpoint imports `subscribe()` / `unsubscribe()` to manage per-client queues.
Event shape (JSON-serialisable dict):
{ "type": "<event_type>", "data": { ... } }
Supported event types:
order_updated — order created / item added / transferred / merged
order_paid — items paid on an order
order_closed — order closed or cancelled
table_list_changed — table added/removed
table_flags_changed — flags set/cleared on a table
message_sent — new staff message (targeted or broadcast)
shift_changed — shift started / ended by manager
business_day_changed — business day opened / closed
"""
import asyncio
import json
from typing import Dict, Set
# Captured once at startup by init_loop() called from lifespan.
# Sync route threads use this to schedule coroutines safely.
_main_loop: asyncio.AbstractEventLoop | None = None
# waiter_id → set of asyncio.Queue (one per SSE connection for that user)
_queues: Dict[int, Set[asyncio.Queue]] = {}
def init_loop(loop: asyncio.AbstractEventLoop) -> None:
"""Call once from the FastAPI lifespan (async context) to capture the event loop."""
global _main_loop
_main_loop = loop
async def subscribe(user_id: int) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=256)
if user_id not in _queues:
_queues[user_id] = set()
_queues[user_id].add(q)
return q
async def unsubscribe(user_id: int, q: asyncio.Queue) -> None:
if user_id in _queues:
_queues[user_id].discard(q)
if not _queues[user_id]:
del _queues[user_id]
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None) -> None:
"""
Fire-and-forget broadcast from a synchronous FastAPI route (thread-pool worker).
Delegates to ws_bus which persists the event and pushes to WS clients.
Also pushes to legacy SSE clients so the old endpoint keeps working during transition.
"""
# WS bus handles persistence + WS delivery
from services.ws_bus import broadcast_sync as ws_broadcast_sync
ws_broadcast_sync(event_type, data, user_ids=user_ids)
# Legacy SSE push (no persistence needed — WS is the source of truth)
if _main_loop is None:
return
_main_loop.call_soon_threadsafe(
_main_loop.create_task,
broadcast(event_type, data, user_ids=user_ids),
)
async def broadcast(event_type: str, data: dict, *, user_ids: list[int] | None = None) -> None:
"""
Push an event to connected clients.
user_ids=None → broadcast to ALL connected users
user_ids=[...] → send only to those specific user IDs
"""
payload = json.dumps({"type": event_type, "data": data})
targets = (
{uid: qs for uid, qs in _queues.items() if uid in user_ids}
if user_ids is not None
else dict(_queues)
)
for qs in targets.values():
for q in list(qs):
try:
q.put_nowait(payload)
except asyncio.QueueFull:
pass # slow client — drop rather than block
+2 -2
View File
@@ -1,7 +1,7 @@
""" """
WebSocket Event Bus — replaces sse_bus.py for real-time communication. WebSocket Event Bus: every live event the backend sends (phase 4.0: the only one; SSE is gone).
Routers keep calling sse_bus.broadcast_sync() (which calls broadcast_sync() here). Every router and service calls broadcast_sync() here (user_ids / device_ids to address it).
The WS endpoint (routers/ws.py) registers each open socket with connect()/disconnect(). The WS endpoint (routers/ws.py) registers each open socket with connect()/disconnect().
Protocol (JSON frames): Protocol (JSON frames):
+1 -1
View File
@@ -72,7 +72,7 @@ def _no_event_persistence(monkeypatch):
"""services.ws_bus writes every broadcast to sync_events through its OWN connection, """services.ws_bus writes every broadcast to sync_events through its OWN connection,
which waits on the test's open transaction until SQLite's 5 s lock timeout (and then which waits on the test's open transaction until SQLite's 5 s lock timeout (and then
fails quietly). Tests don't use the replay buffer, so the write is skipped here. fails quietly). Tests don't use the replay buffer, so the write is skipped here.
Tests about events capture services.sse_bus.broadcast_sync instead.""" Tests about events capture services.ws_bus.broadcast_sync instead."""
import services.ws_bus as ws_bus import services.ws_bus as ws_bus
monkeypatch.setattr(ws_bus, "_persist_event", lambda *a, **k: 0) monkeypatch.setattr(ws_bus, "_persist_event", lambda *a, **k: 0)
+8 -4
View File
@@ -69,13 +69,17 @@ def expect_closed(sock, close):
# ── who may connect ────────────────────────────────────────────────────────── # ── who may connect ──────────────────────────────────────────────────────────
def test_user_token_in_query_still_works(client, make_user, login): def test_a_token_in_the_address_is_ignored(client, make_user, login):
"""Phase 4.0: credentials only in the first frame (a token in a URL ends up in logs)."""
h = login(make_user(role="waiter"), "waiter") h = login(make_user(role="waiter"), "waiter")
with client.websocket_connect(f"{WS}?token={h['Authorization'][7:]}") as sock: with client.websocket_connect(f"{WS}?token={h['Authorization'][7:]}") as sock:
sock.send_json({"cursor": 0}) sock.send_json({"cursor": 0})
expect_ready(sock) assert sock.receive_json()["type"] == "refused"
ws_bus.broadcast_sync("order_updated", {"order_id": 1})
assert sock.receive_json() == {"seq": 0, "type": "order_updated", "data": {"order_id": 1}}
def test_the_sse_stream_is_gone(client, make_user, login):
h = login(make_user(role="waiter"), "waiter")
assert client.get(f"/api/sse/stream?token={h['Authorization'][7:]}").status_code == 404
def test_nothing_or_garbage_is_refused(client): def test_nothing_or_garbage_is_refused(client):
+2 -2
View File
@@ -12,8 +12,8 @@ URL = "/api/platform/notifications"
@pytest.fixture @pytest.fixture
def events(monkeypatch): def events(monkeypatch):
sent = [] sent = []
import services.sse_bus as bus import services.ws_bus as bus
monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, user_ids=None: sent.append((t, d, sorted(user_ids or [])))) monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, user_ids=None, device_ids=None: sent.append((t, d, sorted(user_ids or []))))
return sent return sent
+2 -1
View File
@@ -24,7 +24,8 @@ export default function LiveProvider({ children }) {
const emit = (type, data) => listeners.current.get(type)?.forEach(fn => { try { fn(data) } catch { /* one listener must not stop the others */ } }) const emit = (type, data) => listeners.current.get(type)?.forEach(fn => { try { fn(data) } catch { /* one listener must not stop the others */ } })
let seq = 0 let seq = 0
const live = createLiveClient({ const live = createLiveClient({
url: () => wsUrlFor(`/api/ws/connect?token=${encodeURIComponent(token)}`), url: () => wsUrlFor('/api/ws/connect'),
credentials: () => ({ token }), // in the first frame, never in the address (phase 4.0)
cursor: { load: () => seq, save: s => { seq = s } }, cursor: { load: () => seq, save: s => { seq = s } },
onEvent: emit, onEvent: emit,
onReady: () => { onReady: () => {
+3 -4
View File
@@ -3,7 +3,7 @@
// hook is now a thin wrapper around this. No React. // hook is now a thin wrapper around this. No React.
// //
// Protocol (local_backend/routers/ws.py): // Protocol (local_backend/routers/ws.py):
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt> (or no query, see `credentials`) // 1. connect to ws[s]://host/api/ws/connect (never a token in the address: phase 4.0)
// 2. send { cursor: <last seq>, ...credentials() } at once (0 = first connect / no history) // 2. send { cursor: <last seq>, ...credentials() } at once (0 = first connect / no history)
// 3. the server replays missed events, then sends { type: "ready" } // 3. the server replays missed events, then sends { type: "ready" }
// — or { type: "refused", data: { code } } and closes (4001 sign in again, 4003 device) // — or { type: "refused", data: { code } } and closes (4001 sign in again, 4003 device)
@@ -15,11 +15,10 @@
// the `cursor` store the app provides (the waiter keeps it in IndexedDB). // the `cursor` store the app provides (the waiter keeps it in IndexedDB).
// //
// const live = createLiveClient({ // const live = createLiveClient({
// url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`), // url: () => wsUrl('/api/ws/connect'),
// credentials: () => ({ token }), // a paired screen: ({ device: deviceToken, token: sessionToken })
// cursor: { load: async () => seq, save: seq => … }, // cursor: { load: async () => seq, save: seq => … },
// onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …, // 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 // onRefused: code => …, // e.g. 'device.revoked', 'auth.session_ended'; it keeps retrying
// }) // })
// live.start(); …; live.reconnect(); …; live.stop() // live.start(); …; live.reconnect(); …; live.stop()
+2 -1
View File
@@ -103,7 +103,8 @@ async function basics() {
v = await attach() v = await attach()
let vs = await venuesState(v) let vs = await venuesState(v)
r.check('second venue paired and active', vs.active === 'test-site-2' && Object.keys(vs.venues).length === 2) r.check('second venue paired and active', vs.active === 'test-site-2' && Object.keys(vs.venues).length === 2)
r.check('second venue starts logged out (own session)', (await v.evaluate('location.pathname')) === '/login') const path2 = await v.evaluate('location.pathname')
r.check('second venue starts logged out (own session)', path2 === '/login', `${path2} ${JSON.stringify(vs)}`)
await tap(v, 'button', 'Αλλαγή') await tap(v, 'button', 'Αλλαγή')
await sleep(1200) await sleep(1200)
await tap(v, 'button', `${H}:8055`) await tap(v, 'button', `${H}:8055`)
+1
View File
@@ -53,6 +53,7 @@ try {
const dbs = await page.evaluate(async () => (await indexedDB.databases()).map(d => d.name)) const dbs = await page.evaluate(async () => (await indexedDB.databases()).map(d => d.name))
r1.check(`${m.name}: lands on /tables`, page.url().includes('/tables'), page.url()) r1.check(`${m.name}: lands on /tables`, page.url().includes('/tables'), page.url())
r1.check(`${m.name}: live WebSocket via ${m.wsHost}`, frames.some(f => f.includes('"ready"')) && wsUrls.some(u => new URL(u).host === m.wsHost)) r1.check(`${m.name}: live WebSocket via ${m.wsHost}`, frames.some(f => f.includes('"ready"')) && wsUrls.some(u => new URL(u).host === m.wsHost))
r1.check(`${m.name}: no token in the live connection's address (4.0)`, wsUrls.some(u => u.includes('/api/ws/')) && wsUrls.filter(u => u.includes('/api/')).every(u => !/token=/.test(u)), wsUrls.filter(u => u.includes('/api/')).join(' '))
r1.check(`${m.name}: IndexedDB "${m.db}"`, dbs.includes(m.db), dbs.join(',')) r1.check(`${m.name}: IndexedDB "${m.db}"`, dbs.includes(m.db), dbs.join(','))
r1.check(`${m.name}: secure context = ${m.secure}`, (await page.evaluate(() => window.isSecureContext)) === m.secure) r1.check(`${m.name}: secure context = ${m.secure}`, (await page.evaluate(() => window.isSecureContext)) === m.secure)
if (m.name.startsWith('venue')) r1.check(`${m.name}: API calls go to the venue server`, [...apiHosts].every(h => h === '127.0.0.1:8055'), [...apiHosts].join(',')) if (m.name.startsWith('venue')) r1.check(`${m.name}: API calls go to the venue server`, [...apiHosts].every(h => h === '127.0.0.1:8055'), [...apiHosts].join(','))
+11 -4
View File
@@ -80,12 +80,19 @@ export async function reloadApp(v, target = '/') {
const statusBar = () => Number(adb('shell', 'dumpsys', 'window').match(/statusBars.*?frame=\[0,0\]\[\d+,(\d+)\]/s)?.[1] || 0) const statusBar = () => Number(adb('shell', 'dumpsys', 'window').match(/statusBars.*?frame=\[0,0\]\[\d+,(\d+)\]/s)?.[1] || 0)
/** Real tap on the element matching a CSS selector (and containing `text`). */ /** Real tap on the element matching a CSS selector (and containing `text`). */
export async function tap(v, selector, text = '', { last = false } = {}) { export async function tap(v, selector, text = '', { last = false, timeout = 10_000 } = {}) {
const r = await v.evaluate(`(() => { // waits for the element (a relaunch or a route change on the emulator can take a few
// seconds; fixed sleeps made the suite flaky, KI-009) instead of failing at once
const find = () => v.evaluate(`(() => {
const els = [...document.querySelectorAll(${JSON.stringify(selector)})].filter(e => e.textContent.includes(${JSON.stringify(text)})) const els = [...document.querySelectorAll(${JSON.stringify(selector)})].filter(e => e.textContent.includes(${JSON.stringify(text)}))
const b = els[${last ? 'els.length - 1' : '0'}]?.getBoundingClientRect() const b = els[${last ? 'els.length - 1' : '0'}]?.getBoundingClientRect()
return b ? { x: b.x + b.width / 2, y: b.y + b.height / 2, dpr: devicePixelRatio } : null return b && b.width > 0 ? { x: b.x + b.width / 2, y: b.y + b.height / 2, dpr: devicePixelRatio } : null
})()`) })()`).catch(() => null)
let r = await find()
for (const until = Date.now() + timeout; !r && Date.now() < until;) {
await new Promise(res => setTimeout(res, 300))
r = await find()
}
if (!r) throw new Error(`nothing to tap: ${selector} "${text}"`) if (!r) throw new Error(`nothing to tap: ${selector} "${text}"`)
adb('shell', 'input', 'tap', String(Math.round(r.x * r.dpr)), String(Math.round(r.y * r.dpr + statusBar()))) adb('shell', 'input', 'tap', String(Math.round(r.x * r.dpr)), String(Math.round(r.y * r.dpr + statusBar())))
} }
+3
View File
@@ -78,6 +78,8 @@ try {
page.on('pageerror', e => errors.push(e.message)) page.on('pageerror', e => errors.push(e.message))
const bootstraps = [] const bootstraps = []
page.on('request', q => { if (q.url().includes('/api/platform/bootstrap')) bootstraps.push(q.headers().authorization || 'anonymous') }) page.on('request', q => { if (q.url().includes('/api/platform/bootstrap')) bootstraps.push(q.headers().authorization || 'anonymous') })
const managerWs = []
page.on('websocket', ws => managerWs.push(ws.url()))
// ── Wrong password: the message shows, no reload ─────────────────────────── // ── Wrong password: the message shows, no reload ───────────────────────────
await uiLogin(page, 'wrong-password') await uiLogin(page, 'wrong-password')
@@ -751,6 +753,7 @@ try {
(await chefRow.textContent().catch(() => '')).includes('Kitchen pass · Kitchen display')) (await chefRow.textContent().catch(() => '')).includes('Kitchen pass · Kitchen display'))
await o.screenshot({ path: path.join(OUT, 'manager-owner-flow.png'), fullPage: true }) await o.screenshot({ path: path.join(OUT, 'manager-owner-flow.png'), fullPage: true })
r.check('live: the manager connection carries no token in its address (4.0)', managerWs.some(u => u.includes('/api/ws/')) && managerWs.filter(u => u.includes('/api/')).every(u => !/token=/.test(u)), managerWs.filter(u => u.includes('/api/')).join(' ')) // (Vite's own dev socket has its token)
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | ')) r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
} finally { } finally {
await browser.close() await browser.close()
+3 -3
View File
@@ -20,7 +20,7 @@ import ChatThreadPage from './pages/ChatThreadPage'
import ShiftOverviewPage from './pages/ShiftOverviewPage' import ShiftOverviewPage from './pages/ShiftOverviewPage'
import OrderLogPage from './pages/OrderLogPage' import OrderLogPage from './pages/OrderLogPage'
import { NotificationProvider } from './context/NotificationContext' import { NotificationProvider } from './context/NotificationContext'
import { SSEProvider } from './context/SSEContext' import { LiveProvider } from './context/LiveContext'
import ConnectivityBar from './components/ConnectivityBar' import ConnectivityBar from './components/ConnectivityBar'
import AppShell from './components/AppShell' import AppShell from './components/AppShell'
import UpdatePrompt from './components/UpdatePrompt' import UpdatePrompt from './components/UpdatePrompt'
@@ -442,7 +442,7 @@ export default function App() {
<FavoritesLoader /> <FavoritesLoader />
<AuthRehydrator /> <AuthRehydrator />
<OfflineListener /> <OfflineListener />
<SSEProvider> <LiveProvider>
<NotificationProvider> <NotificationProvider>
<ConnectivityBar /> <ConnectivityBar />
{/* Native builds ship their UI in the app bundle — no service worker to update */} {/* Native builds ship their UI in the app bundle — no service worker to update */}
@@ -471,7 +471,7 @@ export default function App() {
<Route path="*" element={<Navigate to="/tables?tab=tables" replace />} /> <Route path="*" element={<Navigate to="/tables?tab=tables" replace />} />
</Routes> </Routes>
</NotificationProvider> </NotificationProvider>
</SSEProvider> </LiveProvider>
</BrowserRouter> </BrowserRouter>
</QueryClientProvider> </QueryClientProvider>
) )
@@ -4,21 +4,21 @@ import useConnectionStore from '../store/connectionStore'
* A 3px bar pinned to the very top of the screen (above the header). * A 3px bar pinned to the very top of the screen (above the header).
* Always visible — color signals connection state at a glance: * Always visible — color signals connection state at a glance:
* *
* sseAlive=true → solid green (SSE stream live) * liveAlive=true → solid green (live connection up)
* online only → solid blue (HTTP reachable, SSE not yet connected) * online only → solid blue (HTTP reachable, live connection not up yet)
* reconnecting → amber, animated sweep * reconnecting → amber, animated sweep
* offline → red, animated sweep * offline → red, animated sweep
* offline >5min → flashing red * offline >5min → flashing red
*/ */
export default function ConnectivityBar() { export default function ConnectivityBar() {
const { status, sseAlive, flashing } = useConnectionStore() const { status, liveAlive, flashing } = useConnectionStore()
const isOnline = status === 'online' const isOnline = status === 'online'
const isReconnecting = status === 'reconnecting' const isReconnecting = status === 'reconnecting'
const isOffline = status === 'offline' const isOffline = status === 'offline'
const color = isOnline const color = isOnline
? (sseAlive ? '#22c55e' : '#3b82f6') ? (liveAlive ? '#22c55e' : '#3b82f6')
: isReconnecting : isReconnecting
? '#f59e0b' ? '#f59e0b'
: '#ef4444' : '#ef4444'
@@ -44,8 +44,8 @@ export default function ServerRediscovery() {
}) })
const watchdog = setInterval(() => { const watchdog = setInterval(() => {
const { status, sseAlive } = useConnectionStore.getState() const { status, liveAlive } = useConnectionStore.getState()
if (status !== 'online' || !sseAlive) attempt() if (status !== 'online' || !liveAlive) attempt()
}, WATCHDOG_MS) }, WATCHDOG_MS)
window.addEventListener('backend-offline', attempt) window.addEventListener('backend-offline', attempt)
@@ -9,15 +9,15 @@ import { flushAllOfflineOps } from '../services/offlineOrders'
import useChatStore from '../store/chatStore' import useChatStore from '../store/chatStore'
import useKdsReadyStore from '../store/kdsReadyStore' import useKdsReadyStore from '../store/kdsReadyStore'
const SSEContext = createContext(null) const LiveContext = createContext(null)
export function useSSEContext() { export function useLiveContext() {
return useContext(SSEContext) return useContext(LiveContext)
} }
export function SSEProvider({ children }) { export function LiveProvider({ children }) {
const { token } = useAuthStore() const { token } = useAuthStore()
const { setLost, setOnline, setSseAlive } = useConnectionStore() const { setLost, setOnline, setLiveAlive } = useConnectionStore()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const wsAlive = useRef(false) const wsAlive = useRef(false)
const syncingRef = useRef(false) // prevent concurrent syncs const syncingRef = useRef(false) // prevent concurrent syncs
@@ -109,17 +109,17 @@ export function SSEProvider({ children }) {
const handleCameOnline = useCallback(async () => { const handleCameOnline = useCallback(async () => {
const wasOffline = useConnectionStore.getState().status !== 'online' const wasOffline = useConnectionStore.getState().status !== 'online'
setOnlineRef.current() setOnlineRef.current()
window.dispatchEvent(new Event('sse-reconnected')) window.dispatchEvent(new Event('live-reconnected'))
if (wasOffline) { if (wasOffline) {
await flushOfflineQueue() await flushOfflineQueue()
} }
await fullRefresh() await fullRefresh()
}, [fullRefresh, flushOfflineQueue]) }, [fullRefresh, flushOfflineQueue])
// ── SSE event handler ───────────────────────────────────────────────────────── // ── Live event handler ─────────────────────────────────────────────────────────
const handleEvent = useCallback(async (type, data) => { const handleEvent = useCallback(async (type, data) => {
window.dispatchEvent(new CustomEvent('sse-event', { detail: { type, data } })) window.dispatchEvent(new CustomEvent('live-event', { detail: { type, data } }))
switch (type) { switch (type) {
case 'order_updated': { case 'order_updated': {
@@ -206,21 +206,21 @@ export function SSEProvider({ children }) {
} }
}, [snapshotTables, snapshotCatalogue, snapshotProducts, queryClient]) }, [snapshotTables, snapshotCatalogue, snapshotProducts, queryClient])
// ── SSE lifecycle ───────────────────────────────────────────────────────────── // ── Live connection lifecycle ─────────────────────────────────────────────────────────────
const handleConnect = useCallback(async () => { const handleConnect = useCallback(async () => {
wsAlive.current = true wsAlive.current = true
setSseAlive(true) setLiveAlive(true)
await handleCameOnline() await handleCameOnline()
}, [handleCameOnline, setSseAlive]) }, [handleCameOnline, setLiveAlive])
const handleDisconnect = useCallback(() => { const handleDisconnect = useCallback(() => {
wsAlive.current = false wsAlive.current = false
setSseAlive(false) setLiveAlive(false)
// The WS hook will auto-reconnect with exponential backoff. // The WS hook will auto-reconnect with exponential backoff.
// Don't immediately declare offline — wait for the axios interceptor // Don't immediately declare offline — wait for the axios interceptor
// or visibility handler to confirm the server is truly unreachable. // or visibility handler to confirm the server is truly unreachable.
}, [setSseAlive]) }, [setLiveAlive])
const { reconnect } = useWebSocket({ const { reconnect } = useWebSocket({
token, token,
@@ -259,7 +259,7 @@ export function SSEProvider({ children }) {
await handleCameOnline() await handleCameOnline()
} else if (!wsAlive.current) { } else if (!wsAlive.current) {
// WS dropped silently while sleeping — re-establish and refresh // WS dropped silently while sleeping — re-establish and refresh
setSseAlive(false) setLiveAlive(false)
reconnect() reconnect()
await fullRefresh() await fullRefresh()
} else { } else {
@@ -282,8 +282,8 @@ export function SSEProvider({ children }) {
}, [token, fullRefresh]) }, [token, fullRefresh])
return ( return (
<SSEContext.Provider value={{ reconnect, fullRefresh }}> <LiveContext.Provider value={{ reconnect, fullRefresh }}>
{children} {children}
</SSEContext.Provider> </LiveContext.Provider>
) )
} }
@@ -178,7 +178,7 @@ export function NotificationProvider({ children }) {
// SSE message_sent events → add to pending without polling // SSE message_sent events → add to pending without polling
useEffect(() => { useEffect(() => {
function onSSEEvent(e) { function onLiveEvent(e) {
const { type, data } = e.detail const { type, data } = e.detail
if (type !== 'message_sent') return if (type !== 'message_sent') return
if (!user) return if (!user) return
@@ -216,18 +216,18 @@ export function NotificationProvider({ children }) {
}) })
} }
window.addEventListener('sse-event', onSSEEvent) window.addEventListener('live-event', onLiveEvent)
return () => window.removeEventListener('sse-event', onSSEEvent) return () => window.removeEventListener('live-event', onLiveEvent)
}, [user?.id, persistentPopup, popupMode]) }, [user?.id, persistentPopup, popupMode])
// Fallback: re-fetch unread when SSE reconnects // Fallback: re-fetch unread when SSE reconnects
useEffect(() => { useEffect(() => {
function onSSEConnect() { function onLiveConnect() {
fetchUnread() fetchUnread()
fetchRecent() fetchRecent()
} }
window.addEventListener('sse-reconnected', onSSEConnect) window.addEventListener('live-reconnected', onLiveConnect)
return () => window.removeEventListener('sse-reconnected', onSSEConnect) return () => window.removeEventListener('live-reconnected', onLiveConnect)
}, [fetchUnread, fetchRecent]) }, [fetchUnread, fetchRecent])
async function ackMessage(messageId) { async function ackMessage(messageId) {
-94
View File
@@ -1,94 +0,0 @@
import { useCallback, useEffect, useRef } from 'react'
import { apiBase } from '../config/server'
const INITIAL_RECONNECT_DELAY = 3000
const MAX_RECONNECT_DELAY = 30000
/**
* Opens an SSE connection to /api/sse/stream?token=<jwt>.
*
* Callbacks (onEvent, onConnect, onDisconnect) are stored in refs so they are
* always current without causing the EventSource to reconnect when they change.
*
* The connection is created/destroyed only when `token` or `enabled` changes.
*/
export function useSSE({ token, onEvent, onConnect, onDisconnect, enabled = true }) {
// Keep callbacks in refs so the EventSource closure always calls the latest version
const onEventRef = useRef(onEvent)
const onConnectRef = useRef(onConnect)
const onDisconnectRef = useRef(onDisconnect)
useEffect(() => { onEventRef.current = onEvent }, [onEvent])
useEffect(() => { onConnectRef.current = onConnect }, [onConnect])
useEffect(() => { onDisconnectRef.current = onDisconnect }, [onDisconnect])
const esRef = useRef(null)
const reconnectTimer = useRef(null)
const reconnectDelay = useRef(INITIAL_RECONNECT_DELAY)
const unmounted = useRef(false)
// Expose reconnect so SSEContext can trigger it after heartbeat recovery
const reconnectRef = useRef(null)
useEffect(() => {
if (!token || !enabled) return
unmounted.current = false
function connect() {
if (unmounted.current) return
if (esRef.current) {
esRef.current.close()
esRef.current = null
}
const url = `${apiBase()}/api/sse/stream?token=${encodeURIComponent(token)}`
const es = new EventSource(url)
esRef.current = es
es.onopen = () => {
reconnectDelay.current = INITIAL_RECONNECT_DELAY
onConnectRef.current?.()
}
es.onmessage = (e) => {
try {
const { type, data } = JSON.parse(e.data)
onEventRef.current?.(type, data)
} catch {
// malformed event — ignore
}
}
es.onerror = () => {
es.close()
esRef.current = null
onDisconnectRef.current?.()
if (unmounted.current) return
reconnectTimer.current = setTimeout(() => {
reconnectDelay.current = Math.min(
reconnectDelay.current * 1.5,
MAX_RECONNECT_DELAY
)
connect()
}, reconnectDelay.current)
}
}
reconnectRef.current = connect
connect()
return () => {
unmounted.current = true
clearTimeout(reconnectTimer.current)
esRef.current?.close()
esRef.current = null
}
}, [token, enabled])
// Stable reference — never changes, so heartbeat useEffect dep array stays stable
const reconnect = useCallback(() => {
clearTimeout(reconnectTimer.current)
reconnectDelay.current = INITIAL_RECONNECT_DELAY
reconnectRef.current?.()
}, [])
return { reconnect }
}
+4 -2
View File
@@ -48,8 +48,10 @@ export function useWebSocket({ token, onEvent, onConnect, onDisconnect, enabled
useEffect(() => { useEffect(() => {
if (!token || !enabled) return if (!token || !enabled) return
const live = createLiveClient({ const live = createLiveClient({
// Same host as the page (web) or the active venue's server (native) // Same host as the page (web) or the active venue's server (native). The token goes in
url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`), // the first frame, never in the address (proxy logs; phase 4.0).
url: () => wsUrl('/api/ws/connect'),
credentials: () => ({ token }),
cursor: idbCursor, cursor: idbCursor,
onEvent: (type, data) => onEventRef.current?.(type, data), onEvent: (type, data) => onEventRef.current?.(type, data),
onReady: () => onConnectRef.current?.(), onReady: () => onConnectRef.current?.(),
+3 -3
View File
@@ -300,7 +300,7 @@ export default function ChatThreadPage() {
// ── SSE wiring ──────────────────────────────────────────────────────────────── // ── SSE wiring ────────────────────────────────────────────────────────────────
useEffect(() => { useEffect(() => {
function onSSE(e) { function onLive(e) {
const { type, data } = e.detail const { type, data } = e.detail
// conversationId from useParams is a string; SSE payload has an integer // conversationId from useParams is a string; SSE payload has an integer
if (type === 'chat_message' && String(data.conversation_id) === conversationId) { if (type === 'chat_message' && String(data.conversation_id) === conversationId) {
@@ -338,8 +338,8 @@ export default function ChatThreadPage() {
updateLastRead(data.conversation_id, data.user_id, data.read_at) updateLastRead(data.conversation_id, data.user_id, data.read_at)
} }
} }
window.addEventListener('sse-event', onSSE) window.addEventListener('live-event', onLive)
return () => window.removeEventListener('sse-event', onSSE) return () => window.removeEventListener('live-event', onLive)
}, [conversationId, addMessage, markRead, upsertConversation, updateLastRead]) }, [conversationId, addMessage, markRead, upsertConversation, updateLastRead])
// ── Send message ────────────────────────────────────────────────────────────── // ── Send message ──────────────────────────────────────────────────────────────
+3 -3
View File
@@ -1197,7 +1197,7 @@ export default function TableDetailPage() {
}, [tableId, standaloneOrderId]) // eslint-disable-line react-hooks/exhaustive-deps }, [tableId, standaloneOrderId]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { useEffect(() => {
function onSSE(e) { function onLive(e) {
const { type, data } = e.detail const { type, data } = e.detail
if ((type === 'kds_item_updated' || type === 'kds_order_updated') && order && data.order_id === order.id) { if ((type === 'kds_item_updated' || type === 'kds_order_updated') && order && data.order_id === order.id) {
load() load()
@@ -1215,8 +1215,8 @@ export default function TableDetailPage() {
navigate('/tables', { replace: true }) navigate('/tables', { replace: true })
} }
} }
window.addEventListener('sse-event', onSSE) window.addEventListener('live-event', onLive)
return () => window.removeEventListener('sse-event', onSSE) return () => window.removeEventListener('live-event', onLive)
}, [order?.id, tableId]) }, [order?.id, tableId])
useEffect(() => { useEffect(() => {
+5 -5
View File
@@ -377,8 +377,8 @@ export default function TableListPage() {
useEffect(() => { useEffect(() => {
const handler = () => load() const handler = () => load()
window.addEventListener('sse-reconnected', handler) window.addEventListener('live-reconnected', handler)
return () => window.removeEventListener('sse-reconnected', handler) return () => window.removeEventListener('live-reconnected', handler)
}, []) }, [])
useEffect(() => { if (connStatus === 'online') setOffline(false) }, [connStatus]) useEffect(() => { if (connStatus === 'online') setOffline(false) }, [connStatus])
@@ -465,7 +465,7 @@ export default function TableListPage() {
// ── SSE live updates ─────────────────────────────────────────────────────── // ── SSE live updates ───────────────────────────────────────────────────────
useEffect(() => { useEffect(() => {
if (isOffline) return if (isOffline) return
function onSSE(e) { function onLive(e) {
const { type, data } = e.detail const { type, data } = e.detail
if (type === 'order_updated' || type === 'order_paid') { if (type === 'order_updated' || type === 'order_paid') {
client.get(`/api/orders/${data.order_id}`) client.get(`/api/orders/${data.order_id}`)
@@ -499,8 +499,8 @@ export default function TableListPage() {
}).catch(() => {}) }).catch(() => {})
} }
} }
window.addEventListener('sse-event', onSSE) window.addEventListener('live-event', onLive)
return () => window.removeEventListener('sse-event', onSSE) return () => window.removeEventListener('live-event', onLive)
}, [isOffline]) }, [isOffline])
// ── Derived maps ─────────────────────────────────────────────────────────── // ── Derived maps ───────────────────────────────────────────────────────────
+1 -9
View File
@@ -411,15 +411,7 @@ async function _flushPay(op, idMap) {
await db.offline_ops.update(op.localId, { synced: 1 }) await db.offline_ops.update(op.localId, { synced: 1 })
} }
// ─── Kept for SSEContext compat ─────────────────────────────────────────────── // ─── Queue size ───────────────────────────────────────────────────────────────
export async function flushOfflineOrders() {
// no-op — handled by flushAllOfflineOps
}
export async function flushOfflineOps() {
// no-op — handled by flushAllOfflineOps
}
export async function pendingOrderCount() { export async function pendingOrderCount() {
const ops = await db.offline_ops.toArray() const ops = await db.offline_ops.toArray()
+3 -3
View File
@@ -19,13 +19,13 @@ const FLASH_MS = 5 * 60 * 1000 // 5 minutes before bar starts flashing
const useConnectionStore = create((set, get) => ({ const useConnectionStore = create((set, get) => ({
status: 'online', // 'online' | 'reconnecting' | 'offline' status: 'online', // 'online' | 'reconnecting' | 'offline'
sseAlive: false, // true when SSE stream is actively connected liveAlive: false, // true when the live connection is up
lostAt: null, // Date when connection was first lost lostAt: null, // Date when connection was first lost
flashing: false, // true when offline > 5 min flashing: false, // true when offline > 5 min
_graceTimer: null, _graceTimer: null,
_flashTimer: null, _flashTimer: null,
setSseAlive: (alive) => set({ sseAlive: alive }), setLiveAlive: (alive) => set({ liveAlive: alive }),
setLost: () => { setLost: () => {
const { status, _graceTimer } = get() const { status, _graceTimer } = get()
@@ -58,7 +58,7 @@ const useConnectionStore = create((set, get) => ({
isOnline: () => get().status === 'online', isOnline: () => get().status === 'online',
isOffline: () => get().status === 'offline' || get().status === 'reconnecting', isOffline: () => get().status === 'offline' || get().status === 'reconnecting',
// Legacy compat — SSEContext still calls these // Manual offline entry (immediate, no grace period)
enterEmergency: () => { enterEmergency: () => {
// treated as manual offline entry (immediate, no grace period) // treated as manual offline entry (immediate, no grace period)
const { _graceTimer, _flashTimer } = get() const { _graceTimer, _flashTimer } = get()