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:
@@ -20,7 +20,7 @@ import ChatThreadPage from './pages/ChatThreadPage'
|
||||
import ShiftOverviewPage from './pages/ShiftOverviewPage'
|
||||
import OrderLogPage from './pages/OrderLogPage'
|
||||
import { NotificationProvider } from './context/NotificationContext'
|
||||
import { SSEProvider } from './context/SSEContext'
|
||||
import { LiveProvider } from './context/LiveContext'
|
||||
import ConnectivityBar from './components/ConnectivityBar'
|
||||
import AppShell from './components/AppShell'
|
||||
import UpdatePrompt from './components/UpdatePrompt'
|
||||
@@ -442,7 +442,7 @@ export default function App() {
|
||||
<FavoritesLoader />
|
||||
<AuthRehydrator />
|
||||
<OfflineListener />
|
||||
<SSEProvider>
|
||||
<LiveProvider>
|
||||
<NotificationProvider>
|
||||
<ConnectivityBar />
|
||||
{/* 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 />} />
|
||||
</Routes>
|
||||
</NotificationProvider>
|
||||
</SSEProvider>
|
||||
</LiveProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
@@ -4,21 +4,21 @@ import useConnectionStore from '../store/connectionStore'
|
||||
* A 3px bar pinned to the very top of the screen (above the header).
|
||||
* Always visible — color signals connection state at a glance:
|
||||
*
|
||||
* sseAlive=true → solid green (SSE stream live)
|
||||
* online only → solid blue (HTTP reachable, SSE not yet connected)
|
||||
* liveAlive=true → solid green (live connection up)
|
||||
* online only → solid blue (HTTP reachable, live connection not up yet)
|
||||
* reconnecting → amber, animated sweep
|
||||
* offline → red, animated sweep
|
||||
* offline >5min → flashing red
|
||||
*/
|
||||
export default function ConnectivityBar() {
|
||||
const { status, sseAlive, flashing } = useConnectionStore()
|
||||
const { status, liveAlive, flashing } = useConnectionStore()
|
||||
|
||||
const isOnline = status === 'online'
|
||||
const isReconnecting = status === 'reconnecting'
|
||||
const isOffline = status === 'offline'
|
||||
|
||||
const color = isOnline
|
||||
? (sseAlive ? '#22c55e' : '#3b82f6')
|
||||
? (liveAlive ? '#22c55e' : '#3b82f6')
|
||||
: isReconnecting
|
||||
? '#f59e0b'
|
||||
: '#ef4444'
|
||||
|
||||
@@ -44,8 +44,8 @@ export default function ServerRediscovery() {
|
||||
})
|
||||
|
||||
const watchdog = setInterval(() => {
|
||||
const { status, sseAlive } = useConnectionStore.getState()
|
||||
if (status !== 'online' || !sseAlive) attempt()
|
||||
const { status, liveAlive } = useConnectionStore.getState()
|
||||
if (status !== 'online' || !liveAlive) attempt()
|
||||
}, WATCHDOG_MS)
|
||||
window.addEventListener('backend-offline', attempt)
|
||||
|
||||
|
||||
@@ -9,15 +9,15 @@ import { flushAllOfflineOps } from '../services/offlineOrders'
|
||||
import useChatStore from '../store/chatStore'
|
||||
import useKdsReadyStore from '../store/kdsReadyStore'
|
||||
|
||||
const SSEContext = createContext(null)
|
||||
const LiveContext = createContext(null)
|
||||
|
||||
export function useSSEContext() {
|
||||
return useContext(SSEContext)
|
||||
export function useLiveContext() {
|
||||
return useContext(LiveContext)
|
||||
}
|
||||
|
||||
export function SSEProvider({ children }) {
|
||||
export function LiveProvider({ children }) {
|
||||
const { token } = useAuthStore()
|
||||
const { setLost, setOnline, setSseAlive } = useConnectionStore()
|
||||
const { setLost, setOnline, setLiveAlive } = useConnectionStore()
|
||||
const queryClient = useQueryClient()
|
||||
const wsAlive = useRef(false)
|
||||
const syncingRef = useRef(false) // prevent concurrent syncs
|
||||
@@ -109,17 +109,17 @@ export function SSEProvider({ children }) {
|
||||
const handleCameOnline = useCallback(async () => {
|
||||
const wasOffline = useConnectionStore.getState().status !== 'online'
|
||||
setOnlineRef.current()
|
||||
window.dispatchEvent(new Event('sse-reconnected'))
|
||||
window.dispatchEvent(new Event('live-reconnected'))
|
||||
if (wasOffline) {
|
||||
await flushOfflineQueue()
|
||||
}
|
||||
await fullRefresh()
|
||||
}, [fullRefresh, flushOfflineQueue])
|
||||
|
||||
// ── SSE event handler ─────────────────────────────────────────────────────────
|
||||
// ── Live event handler ─────────────────────────────────────────────────────────
|
||||
|
||||
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) {
|
||||
case 'order_updated': {
|
||||
@@ -206,21 +206,21 @@ export function SSEProvider({ children }) {
|
||||
}
|
||||
}, [snapshotTables, snapshotCatalogue, snapshotProducts, queryClient])
|
||||
|
||||
// ── SSE lifecycle ─────────────────────────────────────────────────────────────
|
||||
// ── Live connection lifecycle ─────────────────────────────────────────────────────────────
|
||||
|
||||
const handleConnect = useCallback(async () => {
|
||||
wsAlive.current = true
|
||||
setSseAlive(true)
|
||||
setLiveAlive(true)
|
||||
await handleCameOnline()
|
||||
}, [handleCameOnline, setSseAlive])
|
||||
}, [handleCameOnline, setLiveAlive])
|
||||
|
||||
const handleDisconnect = useCallback(() => {
|
||||
wsAlive.current = false
|
||||
setSseAlive(false)
|
||||
setLiveAlive(false)
|
||||
// The WS hook will auto-reconnect with exponential backoff.
|
||||
// Don't immediately declare offline — wait for the axios interceptor
|
||||
// or visibility handler to confirm the server is truly unreachable.
|
||||
}, [setSseAlive])
|
||||
}, [setLiveAlive])
|
||||
|
||||
const { reconnect } = useWebSocket({
|
||||
token,
|
||||
@@ -259,7 +259,7 @@ export function SSEProvider({ children }) {
|
||||
await handleCameOnline()
|
||||
} else if (!wsAlive.current) {
|
||||
// WS dropped silently while sleeping — re-establish and refresh
|
||||
setSseAlive(false)
|
||||
setLiveAlive(false)
|
||||
reconnect()
|
||||
await fullRefresh()
|
||||
} else {
|
||||
@@ -282,8 +282,8 @@ export function SSEProvider({ children }) {
|
||||
}, [token, fullRefresh])
|
||||
|
||||
return (
|
||||
<SSEContext.Provider value={{ reconnect, fullRefresh }}>
|
||||
<LiveContext.Provider value={{ reconnect, fullRefresh }}>
|
||||
{children}
|
||||
</SSEContext.Provider>
|
||||
</LiveContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -178,7 +178,7 @@ export function NotificationProvider({ children }) {
|
||||
|
||||
// SSE message_sent events → add to pending without polling
|
||||
useEffect(() => {
|
||||
function onSSEEvent(e) {
|
||||
function onLiveEvent(e) {
|
||||
const { type, data } = e.detail
|
||||
if (type !== 'message_sent') return
|
||||
if (!user) return
|
||||
@@ -216,18 +216,18 @@ export function NotificationProvider({ children }) {
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('sse-event', onSSEEvent)
|
||||
return () => window.removeEventListener('sse-event', onSSEEvent)
|
||||
window.addEventListener('live-event', onLiveEvent)
|
||||
return () => window.removeEventListener('live-event', onLiveEvent)
|
||||
}, [user?.id, persistentPopup, popupMode])
|
||||
|
||||
// Fallback: re-fetch unread when SSE reconnects
|
||||
useEffect(() => {
|
||||
function onSSEConnect() {
|
||||
function onLiveConnect() {
|
||||
fetchUnread()
|
||||
fetchRecent()
|
||||
}
|
||||
window.addEventListener('sse-reconnected', onSSEConnect)
|
||||
return () => window.removeEventListener('sse-reconnected', onSSEConnect)
|
||||
window.addEventListener('live-reconnected', onLiveConnect)
|
||||
return () => window.removeEventListener('live-reconnected', onLiveConnect)
|
||||
}, [fetchUnread, fetchRecent])
|
||||
|
||||
async function ackMessage(messageId) {
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -48,8 +48,10 @@ export function useWebSocket({ token, onEvent, onConnect, onDisconnect, enabled
|
||||
useEffect(() => {
|
||||
if (!token || !enabled) return
|
||||
const live = createLiveClient({
|
||||
// Same host as the page (web) or the active venue's server (native)
|
||||
url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
|
||||
// Same host as the page (web) or the active venue's server (native). The token goes in
|
||||
// the first frame, never in the address (proxy logs; phase 4.0).
|
||||
url: () => wsUrl('/api/ws/connect'),
|
||||
credentials: () => ({ token }),
|
||||
cursor: idbCursor,
|
||||
onEvent: (type, data) => onEventRef.current?.(type, data),
|
||||
onReady: () => onConnectRef.current?.(),
|
||||
|
||||
@@ -300,7 +300,7 @@ export default function ChatThreadPage() {
|
||||
// ── SSE wiring ────────────────────────────────────────────────────────────────
|
||||
|
||||
useEffect(() => {
|
||||
function onSSE(e) {
|
||||
function onLive(e) {
|
||||
const { type, data } = e.detail
|
||||
// conversationId from useParams is a string; SSE payload has an integer
|
||||
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)
|
||||
}
|
||||
}
|
||||
window.addEventListener('sse-event', onSSE)
|
||||
return () => window.removeEventListener('sse-event', onSSE)
|
||||
window.addEventListener('live-event', onLive)
|
||||
return () => window.removeEventListener('live-event', onLive)
|
||||
}, [conversationId, addMessage, markRead, upsertConversation, updateLastRead])
|
||||
|
||||
// ── Send message ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1197,7 +1197,7 @@ export default function TableDetailPage() {
|
||||
}, [tableId, standaloneOrderId]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
function onSSE(e) {
|
||||
function onLive(e) {
|
||||
const { type, data } = e.detail
|
||||
if ((type === 'kds_item_updated' || type === 'kds_order_updated') && order && data.order_id === order.id) {
|
||||
load()
|
||||
@@ -1215,8 +1215,8 @@ export default function TableDetailPage() {
|
||||
navigate('/tables', { replace: true })
|
||||
}
|
||||
}
|
||||
window.addEventListener('sse-event', onSSE)
|
||||
return () => window.removeEventListener('sse-event', onSSE)
|
||||
window.addEventListener('live-event', onLive)
|
||||
return () => window.removeEventListener('live-event', onLive)
|
||||
}, [order?.id, tableId])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -377,8 +377,8 @@ export default function TableListPage() {
|
||||
|
||||
useEffect(() => {
|
||||
const handler = () => load()
|
||||
window.addEventListener('sse-reconnected', handler)
|
||||
return () => window.removeEventListener('sse-reconnected', handler)
|
||||
window.addEventListener('live-reconnected', handler)
|
||||
return () => window.removeEventListener('live-reconnected', handler)
|
||||
}, [])
|
||||
|
||||
useEffect(() => { if (connStatus === 'online') setOffline(false) }, [connStatus])
|
||||
@@ -465,7 +465,7 @@ export default function TableListPage() {
|
||||
// ── SSE live updates ───────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
if (isOffline) return
|
||||
function onSSE(e) {
|
||||
function onLive(e) {
|
||||
const { type, data } = e.detail
|
||||
if (type === 'order_updated' || type === 'order_paid') {
|
||||
client.get(`/api/orders/${data.order_id}`)
|
||||
@@ -499,8 +499,8 @@ export default function TableListPage() {
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
window.addEventListener('sse-event', onSSE)
|
||||
return () => window.removeEventListener('sse-event', onSSE)
|
||||
window.addEventListener('live-event', onLive)
|
||||
return () => window.removeEventListener('live-event', onLive)
|
||||
}, [isOffline])
|
||||
|
||||
// ── Derived maps ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -411,15 +411,7 @@ async function _flushPay(op, idMap) {
|
||||
await db.offline_ops.update(op.localId, { synced: 1 })
|
||||
}
|
||||
|
||||
// ─── Kept for SSEContext compat ───────────────────────────────────────────────
|
||||
|
||||
export async function flushOfflineOrders() {
|
||||
// no-op — handled by flushAllOfflineOps
|
||||
}
|
||||
|
||||
export async function flushOfflineOps() {
|
||||
// no-op — handled by flushAllOfflineOps
|
||||
}
|
||||
// ─── Queue size ───────────────────────────────────────────────────────────────
|
||||
|
||||
export async function pendingOrderCount() {
|
||||
const ops = await db.offline_ops.toArray()
|
||||
|
||||
@@ -19,13 +19,13 @@ const FLASH_MS = 5 * 60 * 1000 // 5 minutes before bar starts flashing
|
||||
|
||||
const useConnectionStore = create((set, get) => ({
|
||||
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
|
||||
flashing: false, // true when offline > 5 min
|
||||
_graceTimer: null,
|
||||
_flashTimer: null,
|
||||
|
||||
setSseAlive: (alive) => set({ sseAlive: alive }),
|
||||
setLiveAlive: (alive) => set({ liveAlive: alive }),
|
||||
|
||||
setLost: () => {
|
||||
const { status, _graceTimer } = get()
|
||||
@@ -58,7 +58,7 @@ const useConnectionStore = create((set, get) => ({
|
||||
isOnline: () => get().status === 'online',
|
||||
isOffline: () => get().status === 'offline' || get().status === 'reconnecting',
|
||||
|
||||
// Legacy compat — SSEContext still calls these
|
||||
// Manual offline entry (immediate, no grace period)
|
||||
enterEmergency: () => {
|
||||
// treated as manual offline entry (immediate, no grace period)
|
||||
const { _graceTimer, _flashTimer } = get()
|
||||
|
||||
Reference in New Issue
Block a user